'use client';

import type React from 'react';
import { useRef, useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  Grid,
  Typography,
  Box,
  IconButton,
} from '@mui/material';
import { faTimes, faEye } from '@fortawesome/free-solid-svg-icons';
import type { IFormulaire } from '@/shared/types/formulaire';
import { LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import FontAwesome from '@/shared/components/fontawesome';
import { isFieldVisible } from './form-field/form-field-utils';
import { FieldRenderer } from './form-field/field-renderer';
import ConditionalComponent from '../../../../components/table/ConditionalComponent';

interface FormulairePreviewDialogProps {
  open: boolean;
  onClose: () => void;
  formData: IFormulaire;
}

export default function FormulairePreviewDialog({
  open,
  onClose,
  formData,
}: FormulairePreviewDialogProps) {
  const [previewData, setPreviewData] = useState<Record<string, any>>({});
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handlePreviewInputChange = (id: string, value: any) => {
    setPreviewData((prev) => ({
      ...prev,
      [id]: value,
    }));
  };

  const handleFileClick = (fieldId: string) => {
    if (fileInputRef.current) {
      fileInputRef.current.click();
      fileInputRef.current.dataset.targetField = fieldId;
    }
  };

  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    const fieldId = e.target.dataset.targetField;

    if (file && fieldId) {
      setPreviewData((prev) => ({
        ...prev,
        [fieldId]: file.name,
      }));
    }
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="md"
      fullWidth
      sx={{
        '& .MuiDialog-paper': {
          borderRadius: 4,
          maxHeight: 'calc(100vh - 90px)',
        },
      }}
      aria-labelledby="form-preview-title"
    >
      <DialogTitle
        id="form-preview-title"
        sx={{
          p: 2,
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          flexShrink: 0,
          backgroundColor: 'grey.200',
        }}
      >
        <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
          <FontAwesome icon={faEye} width={18} />
          <Typography variant="h6">Prévisualisation: {formData.title}</Typography>
        </Box>
        <IconButton onClick={onClose} edge="end" aria-label="fermer la prévisualisation">
          <FontAwesome width={16} icon={faTimes} />
        </IconButton>
      </DialogTitle>

      <DialogContent sx={{ p: 3, mt: 2, overflow: 'auto', flex: 1 }}>
        <ConditionalComponent
          isValid={formData.fields && formData.fields.length > 0}
          defaultComponent={
            <Typography variant="body1" align="center" sx={{ my: 4 }}>
              Ce formulaire ne contient aucun champ.
            </Typography>
          }
        >
          <Box component="form">
            <input
              type="file"
              ref={fileInputRef}
              style={{ display: 'none' }}
              onChange={handleFileUpload}
            />
            <LocalizationProvider dateAdapter={AdapterDateFns}>
              <Grid container spacing={3}>
                {formData.fields.map((champ) => (
                  <Grid item xs={12} key={champ.id}>
                    <ConditionalComponent isValid={isFieldVisible(champ, previewData)}>
                      <FieldRenderer
                        field={champ}
                        value={previewData[champ.id]}
                        onChange={handlePreviewInputChange}
                        fileInputRef={fileInputRef}
                        handleFileClick={handleFileClick}
                      />
                    </ConditionalComponent>
                  </Grid>
                ))}
              </Grid>
            </LocalizationProvider>
          </Box>
        </ConditionalComponent>
      </DialogContent>
    </Dialog>
  );
}
