"use client"

import { useState, useEffect } from "react"
import { Grid, Button, Stack } from "@mui/material"
import {
  type IDocumentRequest,
  DocumentType,
  RequestStatus,
  RequestType,
  PriorityLevel,
} from "@/shared/types/document-request"
import type { ModeType } from "@/shared/types/common"
import FormContainer from "@/layouts/form/form-container"
import FormField from "@/shared/components/form/form-field"
import type { FormFieldType } from "@/shared/types/common"
import EditExportButtons from "@/shared/components/form/edit-export-buttons"
import ActionButtons from "@/shared/components/form/buttons-action"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faPaperclip, faEnvelope } from "@fortawesome/free-solid-svg-icons"
import MassUploadFile from "@/shared/components/mass-import/mass-upload-file"
import { TypeImport } from "@/shared/types/common"
import SendDocumentDialog from "../components/send-document-dialog"
import ConditionalComponent from "../../../../components/table/ConditionalComponent"
import { useFormik } from "formik"
import * as Yup from "yup"
import { useDocumentRequestStore } from "@/shared/api/stores/admin-service/requestDocsStore"

type Props = {
  request: IDocumentRequest
  mode: ModeType
  onSave: (data: IDocumentRequest) => void
  onClose: (force: boolean) => void
  onEdit: (request: IDocumentRequest) => void
  updateTabContent: (tabId: string, newContent: IDocumentRequest) => void
  tabId: string
}

const documentRequestSchema = Yup.object().shape({
  userName: Yup.string().required("Le nom est requis"),
  title: Yup.string().required("Le type est requis"),
  type: Yup.string().required("Le type de document est requis"),
  priority: Yup.string().required("La priorité est requise"),
  description: Yup.string(),
  observation: Yup.string(),
})

const documentRequestFormFields: FormFieldType<IDocumentRequest>[] = [
  {
    name: "codeReq",
    label: "N° Demande",
    type: "text",
    required: false,
  },
  {
    name: "userName",
    label: "Nom du demandeur",
    type: "text",
    required: true,
  },
  {
    name: "title",
    label: "Type de demande",
    type: "select",
    required: true,
    options: [
      { value: RequestType.PERSONAL_JUSTIFICATION, label: "Justificatif personnel" },
      { value: RequestType.OFFICIAL_DOCUMENT, label: "Document officiel" },
      { value: RequestType.ADMINISTRATIVE_FILE, label: "Fichier administratif" },
      { value: RequestType.EMPLOYMENT_CONTRACT, label: "Contrat de travail" },
      { value: RequestType.OTHER, label: "Autre" },
    ],
  },
  {
    name: "type",
    label: "Type de document",
    type: "select",
    required: true,
    options: [
      { value: DocumentType.ID_CARD, label: "Carte d'identité" },
      { value: DocumentType.PASSPORT, label: "Passeport" },
      { value: DocumentType.DRIVER_LICENSE, label: "Permis de conduire" },
      { value: DocumentType.WORK_CERTIFICATE, label: "Attestation de travail" },
    ],
  },
  {
    name: "statut",
    label: "Statut",
    type: "select",
    required: true,
    options: [
      { value: RequestStatus.EN_ATTENTE, label: "En attente" },
      { value: RequestStatus.EN_TRAITEMENT, label: "En traitement" },
      { value: RequestStatus.VALIDEE, label: "Validée" },
      { value: RequestStatus.REFUSEE, label: "Refusée" },
    ],
  },
  {
    name: "priority",
    label: "Priorité",
    type: "select",
    required: true,
    options: [
      { value: PriorityLevel.BASSE, label: "Basse" },
      { value: PriorityLevel.NORMALE, label: "Normale" },
      { value: PriorityLevel.HAUTE, label: "Haute" },
      { value: PriorityLevel.URGENTE, label: "Urgente" },
    ],
  },
  {
    name: "submissionDate",
    label: "Date de soumission",
    type: "date",
    required: false,
  },
  {
    name: "processingDate",
    label: "Date de traitement",
    type: "date",
    required: false,
  },
  {
    name: "description",
    label: "Description",
    type: "textarea",
    required: false,
  },
  {
    name: "observation",
    label: "Observation",
    type: "textarea",
    required: false,
  },
]

export default function DocumentForm({
  request,
  mode,
  onSave,
  onClose,
  onEdit,
  updateTabContent,
  tabId,
}: Props) {
  const [uploadModalOpen, setUploadModalOpen] = useState(false)
  const [sendDialogOpen, setSendDialogOpen] = useState(false)
  const isReadOnly = mode === "view"
  const { updateRequest } = useDocumentRequestStore()

  const formik = useFormik<IDocumentRequest>({
    initialValues: request,
    validationSchema: documentRequestSchema,
    onSubmit: async (values) => {
      try {
        if (mode === "edit") {
          await updateRequest(
            {
              type: values.type,
              priority: values.priority,
              observation: values.observation,
              description: values.description,
              status : values.statut
            },
            values.codeReq,
          )
        }
        onSave(values)
        onClose(true)
      } catch (error) {
        console.error("Error saving request:", error)
      }
    },
  })

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

  const handleSendDocument = (data: { recipient: string; subject: string; content: string }) => {
    setSendDialogOpen(false)
  }

  const renderField = (field: FormFieldType<IDocumentRequest>, index: number) => {
    const fieldValue = formik.values[field.name]
    const fieldError =
      formik.touched[field.name] && formik.errors[field.name] ? (formik.errors[field.name] as string) : undefined

    return (
      <FormField
        field={field}
        value={fieldValue}
        formData={formik.values}
        onChange={(name, value) => {
          formik.setFieldValue(name, value)
        }}
        isReadOnly={isReadOnly}
        error={fieldError}
      />
    )
  }

  return (
    <FormContainer titre="Demande de Document">
      <ConditionalComponent isValid={isReadOnly}>
        <EditExportButtons
          onEdit={() => onEdit(formik.values)}
          onExport={() => void 0}
          tooltipTitle="Demande de Document"
        />
      </ConditionalComponent>

      <form onSubmit={formik.handleSubmit}>
        <Grid container spacing={4}>
          {documentRequestFormFields.map((field, index) => (
            <Grid item xs={12} sm={4} key={`${field.name}-${index}`}>
              {renderField(field, index)}
            </Grid>
          ))}
          <Grid item xs={12}>
            <ConditionalComponent isValid={!isReadOnly}>
              <ActionButtons
                onSave={() => {
                  formik.validateForm().then((errors) => {
                    formik.submitForm()
                  })
                }}
                onCancel={() => onClose(false)}
                mode={mode}
              />
            </ConditionalComponent>
          </Grid>
        </Grid>
      </form>

      <ConditionalComponent isValid={mode !== "add"}>
        <Stack
          direction="row"
          spacing={2}
          sx={{
            mt: 3,
            borderTop: "1px solid",
            borderColor: "divider",
            pt: 3,
          }}
        >
          <Button
            variant="contained"
            startIcon={<FontAwesomeIcon icon={faPaperclip} />}
            onClick={() => setUploadModalOpen(true)}
          >
            Attacher un fichier
          </Button>

          <Button
            variant="contained"
            startIcon={<FontAwesomeIcon icon={faEnvelope} />}
            onClick={() => setSendDialogOpen(true)}
          >
            Envoyer au demandeur
          </Button>
        </Stack>
      </ConditionalComponent>

      <MassUploadFile
        open={uploadModalOpen}
        onClose={() => setUploadModalOpen(false)}
        type={TypeImport.CIRCUIT}
        skipExport={true}
      />

      <SendDocumentDialog
        open={sendDialogOpen}
        onClose={() => setSendDialogOpen(false)}
        onSend={handleSendDocument}
        recipientName={request?.userName}
      />
    </FormContainer>
  )
}
