// Updated demande-new-view.tsx to use IDocumentRequest and AddDocumentRequestDto
"use client";

import { useState, useEffect } from "react";
import { Grid, Button, Box } from "@mui/material";
import type { IDocumentRequest, AddDocumentRequestDTO } from "@/shared/types/document-request";
import { DocumentType, PriorityLevel, RequestStatus, RequestType } from "@/shared/types/document-request";
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";
import { useDocumentRequestStore } from "@/shared/api/stores/admin-service/requestDocsStore";

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

const documentTypeOptions = [
  { label: "Carte d'identité", value: DocumentType.ID_CARD },
  { label: "Certificat de travail", value: DocumentType.WORK_CERTIFICATE },
  { label: "Permis de conduire", value: DocumentType.DRIVER_LICENSE },
  { label: "Passeport", value: DocumentType.PASSPORT },
];

const priorityOptions = [
  { label: "Basse", value: PriorityLevel.BASSE },
  { label: "Normale", value: PriorityLevel.NORMALE },
  { label: "Haute", value: PriorityLevel.HAUTE },
  { label: "Urgente", value: PriorityLevel.URGENTE },
];

const titleOptions = [
  { label: "Justificatif personnel", value: RequestType.PERSONAL_JUSTIFICATION },
  { label: "Document officiel", value: RequestType.OFFICIAL_DOCUMENT },
  { label: "Fichier administratif", value: RequestType.ADMINISTRATIVE_FILE },
  { label: "Contrat de travail", value: RequestType.EMPLOYMENT_CONTRACT },
  { label: "Autre", value: RequestType.OTHER },
];

const demandeFormFields: FormFieldType<AddDocumentRequestDTO>[] = [
  {
    name: "title",
    label: "Intitulé",
    type: "select",
    required: true,
    options: titleOptions,
  },
  {
    name: "type",
    label: "Type de decument",
    type: "select",
    required: true,
    options: documentTypeOptions,
  },
  {
    name: "priority",
    label: "Priorité",
    type: "select",
    required: true,
    options: priorityOptions,
  },
  {
    name: "observation",
    label: "Observation",
    type: "textarea",
    required: false,
    multiline: true,
    rows: 4,
  },
  {
    name: "description",
    label: "Description",
    type: "textarea",
    required: false,
    multiline: true,
    rows: 4,
  },
];

export default function DemandeForm({ demande, mode, onSave, onClose, onEdit }: DemandeFormProps) {
  const [formData, setFormData] = useState<AddDocumentRequestDTO>({
      userId: Number(localStorage.getItem("userId")),
      userUuid: localStorage.getItem("userUuid"),
      userName : localStorage.getItem("userName"),
      title : demande.title,
      type: demande.type,
      priority: demande.priority,
      observation: demande?.observation,
      description: demande?.description,
  });
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const { addRequest, updateRequest } = useDocumentRequestStore();

  const isReadOnly = mode === "view";

  const renderField = (field: FormFieldType<AddDocumentRequestDTO>) => (
    <FormField
      field={field}
      value={formData[field.name]}
      onChange={(name, value) => setFormData((prev: any) => ({ ...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 handleSave = async () => {
  const dto = { ...formData };
  let result;
  if (mode === "edit" && demande.id) {
    result = await updateRequest({
      type : dto.type,
      priority : dto.priority,
      description : dto.description,
      observation : dto.observation,
      status : demande.statut
    }, demande.codeReq);
  } else {
    result = await addRequest(dto);
  }

  if (result) {
    onSave(result);
    onClose();
  }
};

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

  const validee = demande.statut === RequestStatus.VALIDEE;
  const refusee = demande.statut === RequestStatus.REFUSEE;
  const en_traitement = demande.statut === RequestStatus.EN_TRAITEMENT;
  const en_attente = demande.statut === RequestStatus.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}>
            <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(demande)} mode={mode} readOnly={isReadOnly} />
          </ConditionalComponent>
          <ConditionalComponent isValid={refusee || en_attente}>
            <FormActions onCancel={onClose} onSave={handleSave} onEdit={() => onEdit(demande)} 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>
  );
}
