"use client"

import { useEffect, useState } from "react"
import { useFormik } from "formik"
import FormField from "@/shared/components/form/form-field"
import type { FormFieldType, ModeType, TableColumn } from "@/shared/types/common"
import { _VEHICLE_REPAIR_DOCUMENT_TYPES, vehicleRepairFormFields } from "../utils/form-fields-vehicle-repair"
import FormContainer from "@/layouts/form/form-container"
import { vehicleRepairSchema } from "../utils/vehicle-repair-schema"
import TabbedForm from "@/shared/components/tabs/tabbed-form"
import DocumentForm from "@/shared/components/documents/documents-form"
import { _documents } from "@/shared/_mock/_documents"
import VehicleRepairTab from "../components/vehicle-repair-tab"
import {
  mapVehicleRepairToRequest,
  VehicleRepairPageFilterParams,
  type VehicleRepairListResponse,
  type VehicleRepairRequest,
} from "@/shared/types/fleet-management/vehicle-repair"
import { useVehicleRepairStore } from "@/shared/api/stores/fleet-service/vehicle-repair-store"
import { useSnackbar } from "notistack"
import { useVehicleStore } from "@/shared/api/stores/vehicleStore"
import { useInfrastructureStore } from "@/shared/api/stores/admin-service/infrastructureStore"
import { useServiceProviderStore } from "@/shared/api/stores/fleet-service/service-provider-store"
import { useInterventionStore } from "@/shared/api/stores/fleet-service/intervention-store"

interface VehicleRepairFormProps {
  repair: VehicleRepairListResponse
  mode: ModeType
  onEdit: (updatedRepair: VehicleRepairRequest) => void
  onClose: (isSaved: boolean) => void
  tableHead: TableColumn[]
  setHasUnsavedChanges?: (value: boolean) => void
  updateTabContent?: (tabId: string, newContent: VehicleRepairRequest) => void
  tabId?: string
}

export default function VehicleRepairForm({
  repair,
  mode,
  onClose,
  onEdit,
  tableHead,
  setHasUnsavedChanges,
  updateTabContent,
  tabId,
}: VehicleRepairFormProps) {
  const isReadOnly = mode === "view"
  const isAddMode = mode === "add"

  const { enqueueSnackbar } = useSnackbar()

  const [formData, setFormData] = useState<VehicleRepairRequest>({} as VehicleRepairRequest)

  const [vehicleOptions, setVehicleOptions] = useState<{ value: string; label: string }[]>([])
  const [serviceProviderOptions, setServiceProviderOptions] = useState<{ value: string; label: string }[]>([])
  const [interventionOptions, setInterventionOptions] = useState<{ value: string; label: string }[]>([])
  const [departmentOptions, setDepartmentOptions] = useState<{ value: string; label: string }[]>([])
  const [params, setParams] = useState<VehicleRepairPageFilterParams>({
      page: 0,
      size: 20,
      orderBy: "id",
      orderDir: "desc",
    })

  const { repairById, getRepairById, createRepair, updateRepair, fetchRepairsPage } = useVehicleRepairStore()

  const handleFormSubmit = async (values: VehicleRepairRequest) => {
    if (mode === "edit") {
      try {
        const agency = await getAgencyById(values.departmentId);
        const sector = await getSectorById(String(agency?.id))
        values.sectorName = sector?.name;
        await updateRepair(repair.id, values)
        fetchRepairsPage(params)
        if (setHasUnsavedChanges) setHasUnsavedChanges(false)
        onClose(true)
        enqueueSnackbar("Réparation modifiée avec succès", { variant: "success" })
      } catch (error: any) {
        enqueueSnackbar(error.message, { variant: "error" })
        return
      }
    } else if (mode === "add" || mode === "copy") {
      try {
        const agency = await getAgencyById(values.departmentId);
        const sector = await getSectorById(String(agency?.id))
        values.sectorName = sector?.name;
        await createRepair(values)
        fetchRepairsPage(params)
        if (setHasUnsavedChanges) setHasUnsavedChanges(false)
        onClose(true)
        enqueueSnackbar("Réparation créée avec succès", { variant: "success" })
      } catch (error: any) {
        enqueueSnackbar(error.message, { variant: "error" })
        return
      }
    }
  }

   const {
      getAllVehicles
      } = useVehicleStore();
    const {
      fetchDepartmentNamesForRepair,
      getAgencyById,
      getSectorById
    } = useInfrastructureStore();
    const {
      fetchAllServiceProviders
    } = useServiceProviderStore();
    const {
      fetchAllInterventions
    } = useInterventionStore();

  const getInitialValues = async () => {
    const allVehicles = await getAllVehicles();
    const allInterventions = await fetchAllInterventions();
    const allServiceProviders = await fetchAllServiceProviders();
    const allDepartments = await fetchDepartmentNamesForRepair();
    // setVehicleOptions(...);
    setVehicleOptions(allVehicles.map((vehicle) => ({ value: vehicle.id.toString(), label: vehicle.vehiculeName })));
    // setServiceProviderOptions(...);
    setServiceProviderOptions(allServiceProviders.map((sp) => ({ value: sp.id.toString(), label: sp.name })));
    // setInterventionOptions(...);
    setInterventionOptions(allInterventions.map((intervention) => ({ value: intervention.id.toString(), label: intervention.interventionType })));
    setDepartmentOptions(allDepartments.map((dept: any) => ({value: String(dept.id),label: dept.name,}))
      );

    if (repair?.id && mode !== "add") {
      await getRepairById(repair?.id)
    }
  }
  useEffect(() => {
    getInitialValues()
  }, [])

  useEffect(() => {
    if (repairById) {
      setFormData(mapVehicleRepairToRequest(repairById))
    }
  }, [repairById])

  const formik = useFormik<VehicleRepairRequest>({
    initialValues: formData,
    validationSchema: vehicleRepairSchema,
    onSubmit: (values) => {
      handleFormSubmit(values)
      if (setHasUnsavedChanges) setHasUnsavedChanges(false)
      onClose(true)
    },
    enableReinitialize: true,
  })

  useEffect(() => {
    if (updateTabContent && tabId && mode !== "view") {
      updateTabContent(tabId, formik.values)
    }
  }, [formik.values, updateTabContent, tabId, mode])

  const renderField = (field: FormFieldType<VehicleRepairRequest>) => {
    const handleChange = (name: string, value: any) => {
      formik.setFieldValue(name, value)
    }

    return (
      <FormField
        field={field}
        value={formik.values[field.name as keyof VehicleRepairRequest]}
        onChange={handleChange}
        error={
          formik.touched[field.name as keyof VehicleRepairRequest]
            ? (formik.errors[field.name as keyof VehicleRepairRequest] as string | undefined)
            : undefined
        }
        onBlur={formik.handleBlur}
        isReadOnly={isReadOnly}
      />
    )
  }

  const repairFields = vehicleRepairFormFields(vehicleOptions, serviceProviderOptions, interventionOptions, departmentOptions)

  const tabs = [
    {
      label: "Détails réparation",
      content: (
        <VehicleRepairTab
          renderField={renderField}
          repairFields={repairFields}
          isReadOnly={isReadOnly}
          formik={formik}
          onEdit={onEdit}
          onSave={() => {
            formik.validateForm().then(() => {
              formik.submitForm()
            })
          }}
          onClose={onClose}
          tableHead={tableHead}
          mode={mode}
          setHasUnsavedChanges={setHasUnsavedChanges}
        />
      ),
    },
    {
      label: "Documents",
      content: <DocumentForm documents={isAddMode ? [] : _documents} documentTypes={_VEHICLE_REPAIR_DOCUMENT_TYPES} />,
      disabled: isAddMode,
    },
  ]

  return (
    <FormContainer titre="Fiche Réparation Véhicule">
      <TabbedForm tabs={tabs} />
    </FormContainer>
  )
}
