"use client"

import type React from "react"

import { useState, useEffect } from "react"
import { Grid, Button, Box } from "@mui/material"
import type { IDemande } from "@/shared/types/demande"
import { TypeDemande } from "@/shared/types/demande"
import { DemandeStatus } from "@/shared/types/demande"
import FormField from "@/shared/components/form/form-field"
import type { FormFieldType, ModeType } from "@/shared/types/common"
import FormContainer from "@/layouts/form/form-container"
import FormActions from "@/shared/components/form/form-actions"
import { Upload } from "@mui/icons-material"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import DemandeDetailsForm from "../components/demande-details"
import TabbedForm from "@/shared/components/tabs/tabbed-form"
import { mainColor } from "@/shared/components/table/styles"
import { Stack } from "@mui/system"

interface DemandeFormProps {
  demande: IDemande
  mode: ModeType
  onSave: (updated: IDemande) => void
  onEdit: (updated: IDemande) => void
  onClose: () => void
}

// Document type options
const typeDemandeOptions = Object.values(TypeDemande).map((type) => ({
  value: type,
  label: type,
}))

// Form fields for demande
const demandeFormFields: FormFieldType<IDemande>[] = [
  {
    name: "typeDemande",
    label: "Type de demande",
    type: "select",
    required: true,
    options: typeDemandeOptions,
  },
  {
    name: "description",
    label: "Commentaire / Justificatif / Remarque",
    type: "textarea",
    required: false,
    multiline: true,
    rows: 4,
  },
]

export default function DemandeForm({ demande, mode, onSave, onClose, onEdit }: DemandeFormProps) {
  const [formData, setFormData] = useState<IDemande>(demande)
  const [selectedFile, setSelectedFile] = useState<File | null>(null)

  useEffect(() => {
    setFormData(demande)
  }, [demande])

  const isReadOnly = mode === "view"

  const renderField = (field: FormFieldType<IDemande>) => (
    <FormField
      field={field}
      value={formData[field.name]}
      onChange={(name, value) => setFormData((prev) => ({ ...prev, [name]: value }))}
      isReadOnly={isReadOnly}
    />
  )

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files[0]) {
      setSelectedFile(event.target.files[0])
    }
  }

  const generateUniqueId = (prefix: string) => {
    return `${prefix}-${Date.now()}-${Math.floor(Math.random() * 1000)
      .toString()
      .padStart(3, "0")}`
  }

  const handleSave = () => {

    const updatedData = {
      ...formData,

      id: formData.id || generateUniqueId("id"),
      numeroDemande: formData.numeroDemande || generateUniqueId("DEM"),

      status: DemandeStatus.EN_ATTENTE,

      dateCreation: new Date().toISOString().split("T")[0],
      dateMiseAJour: new Date().toISOString().split("T")[0],

      intitule: formData.intitule || "Demande de document",
      utilisateur: formData.utilisateur || "Utilisateur actuel",
      fichierAttache: !!selectedFile,
    }

    // Save the updated data
    onSave(updatedData)
    onClose()
  }

  const tabs = [
      {
        label: "Détails",
        content: (
          <DemandeDetailsForm
            renderField={renderField}
            mode={mode}
            onEdit={() => onEdit(formData)}
            onClose={onClose}
            onSave={handleSave}
            demande={formData}
          />
        ),
      }
    ]

  const validee : boolean = formData.status === DemandeStatus.VALIDEE;
  const refusee : boolean = formData.status === DemandeStatus.REFUSEE;
  const en_traitement : boolean = formData.status === DemandeStatus.EN_TRAITEMENT;
  const en_attente : boolean = formData.status === DemandeStatus.EN_ATTENTE;
    
  return (
    <FormContainer 
    titre={"Détails de Votre Demande"}>
      <form>
        <Grid container spacing={3}>
          {demandeFormFields.map((field) => (
            <Grid item xs={12} sm={field.name === "description" ? 12 : 6} key={field.name}>
              {renderField(field)}
            </Grid>
          ))}
          <ConditionalComponent isValid={validee || refusee}>
          <TabbedForm tabs={tabs} sx={{ mt: 4 }} />
          </ConditionalComponent>
          <ConditionalComponent isValid={!validee}>
          <Grid item xs={12}>
            <Box
              sx={{
                border: "1px dashed",
                borderColor: "divider",
                borderRadius: 1,
                p: 3,
                textAlign: "center",
                bgcolor: "background.neutral",
                position: "relative",
              }}
            >
              <input
                type="file"
                onChange={handleFileChange}
                style={{
                  opacity: 0,
                  position: "absolute",
                  top: 0,
                  left: 0,
                  width: "100%",
                  height: "100%",
                  cursor: "pointer",
                }}
                disabled={isReadOnly}
              />
              <Upload sx={{ color: "text.secondary", mb: 1 }} />
              <ConditionalComponent isValid={!!selectedFile}>
                <Box sx={{ typography: "body2", color: "text.secondary" }}>
                  {selectedFile?.name}
                </Box>
              </ConditionalComponent>
              <ConditionalComponent isValid={!selectedFile}>
                <Box sx={{ typography: "body2", color: "text.secondary" }}>
                  <>
                    <Box component="span" sx={{ color: "primary.main", textDecoration: "underline" }}>
                      Joindre un fichier
                    </Box>
                    {" ou glisser-déposer ici"}
                  </>
                </Box>
              </ConditionalComponent>
              <ConditionalComponent isValid={!!selectedFile && !isReadOnly}>
                <Button size="small" color="error" sx={{ mt: 1 }} onClick={() => setSelectedFile(null)}>
                  Supprimer
                </Button>
              </ConditionalComponent>
            </Box>
          </Grid>
          </ConditionalComponent>
        </Grid>

        <Stack direction="row" justifyContent="flex-end" spacing={2} sx={{ mt: 3 }}>
          <ConditionalComponent isValid={validee || en_traitement}>
          <FormActions
            onCancel={onClose}
            onEdit={() => onEdit(formData)}
            mode={mode}
            readOnly={isReadOnly}
          />
          </ConditionalComponent>
          <ConditionalComponent isValid={refusee || en_attente}>
          <FormActions
            onCancel={onClose}
            onSave={handleSave}
            onEdit={() => onEdit(formData)}
            mode={mode}
            readOnly={isReadOnly}
          />
          </ConditionalComponent>
          
          <ConditionalComponent isValid={validee}>
            <Button
                    variant="outlined"
                    sx={{
                      textTransform: "none",
                      margin : 2,
                      textAlign : "center",
                      ...mainColor
                    }}
                  >
                    Télécharger Le Document
                  </Button>
          </ConditionalComponent>
        </Stack>
      </form>
    </FormContainer>
  )
}

