'use client';

import { useState, useMemo, useEffect } from 'react';
import { Grid, Box, Button, Stack, Typography, IconButton, Alert } from '@mui/material';
import { Document, DocumentType, DocumentStatus } from '@/shared/types/document';
import { ModeType } from '@/shared/types/common';
import FormContainer from '@/layouts/form/form-container';
import FormField from '@/shared/components/form/form-field';
import { FormFieldType } from '@/shared/types/common';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import ActionButtons from '@/shared/components/form/buttons-action';
import { documentformfeilds } from '../utils/form-feilds-document';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPaperclip, faEnvelope, faTimes, faFile } 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 { _documentsRh } from '@/shared/_mock/_documentsRh';
import ConditionalComponent from '../../../../components/table/ConditionalComponent';
import { useFormik } from 'formik';
import * as Yup from 'yup';
import { documentSchema } from '../utils/document-schema';

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

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

  const formik = useFormik<Document>({
    initialValues: document,
    validationSchema: documentSchema,
    onSubmit: (values) => {
      onSave({
        ...values,
        uploadDate: values.uploadDate || new Date(),
        lastModified: new Date(),
      });
      onClose(true);
    },
  });

  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 handleTypeChange = (event: React.ChangeEvent<{ value: unknown }>) => {
    const newType = event.target.value as string;
    formik.setFieldValue('type', newType as DocumentType);
    if (newType !== 'autre') {
      formik.setFieldValue('customType', undefined);
    }
  };

  const handleStatusChange = (event: React.ChangeEvent<{ value: unknown }>) => {
    formik.setFieldValue('status', event.target.value as DocumentStatus);
  };

  const handleRequesterChange = (event: React.ChangeEvent<{ value: unknown }>) => {
    const requesterId = event.target.value as string;
    const selectedRequester = _documentsRh.find(r => r.id === requesterId);
    if (selectedRequester) {
      formik.setFieldValue('id', selectedRequester.id);
      formik.setFieldValue('name', selectedRequester.name);
    }
  };

  const renderField = (field: FormFieldType<Document>, 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="Fiche Document">
      
      <ConditionalComponent isValid={isReadOnly}>
        <EditExportButtons
          onEdit={() => onEdit(formik.values)}
          onExport={() => void 0}
          tooltipTitle="Document"
        />
      </ConditionalComponent>

      <form onSubmit={formik.handleSubmit}>
        <Grid container spacing={4}>
          {documentformfeilds.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={document?.name}
      />

      <ConditionalComponent isValid={!!formik.values.file}>
        <Box
          sx={{
            mt: 2,
            display: 'inline-flex',
            alignItems: 'center',
            bgcolor: '#f8f9fa',
            borderRadius: 1,
            p: 1,
            gap: 1,
            border: '1px solid',
            borderColor: 'divider',
            width: 'fit-content',
            maxWidth: '300px',
          }}
        >
          <Box
            sx={{
              width: 40,
              height: 40,
              borderRadius: 1,
              bgcolor: '#ff8fab',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            <FontAwesomeIcon icon={faFile} size="lg" style={{ color: '#fff' }} />
          </Box>
          <Box>
            <Typography variant="subtitle2">
              {formik.values.file && 'name' in formik.values.file && 'extension' in formik.values.file 
                ? `${formik.values.file.name}.${formik.values.file.extension}` 
                : ''}
            </Typography>
            <Typography variant="body2" color="text.secondary">
              Document
            </Typography>
          </Box>
          <IconButton
            size="small"
            sx={{ ml: 1 }}
            onClick={() => formik.setFieldValue('file', undefined)}
          >
            <FontAwesomeIcon icon={faTimes} />
          </IconButton>
        </Box>
      </ConditionalComponent>
    </FormContainer>
  );
} 