'use client';

import React, { useEffect, useState } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Grid,
  Button,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Stack,
  Paper,
} from '@mui/material';
import { useTheme } from '@mui/material/styles';
import FontAwesome from '@/shared/components/fontawesome';
import {
  faFileImport,
  faCheck,
  faCloudUploadAlt,
  faTrashAlt,
} from '@fortawesome/free-solid-svg-icons';
import Upload from '@/shared/components/upload/upload';
import { ISuiviCarteImport, PetrolierType } from '@/shared/types/flottes/suiviCartes';
import { enqueueSnackbar } from 'notistack';
import FileTemplatesList from './importfiles-FileTemplatesList';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

interface ImportSectionProps {
  onImportSuccess?: () => void;
}

export default function ImportSection({ onImportSuccess }: ImportSectionProps) {
  const theme = useTheme();
  const [formData, setFormData] = useState<ISuiviCarteImport>({
    id: '',
    petrolier: '',
    fichierPetrolier: null,
  });
  const [files, setFiles] = useState<File[]>([]);

  const petrolierOptions = Object.values(PetrolierType).map((petrolier) => ({
    label: petrolier,
    value: petrolier,
  }));

  const handlePetrolierChange = (value: string) => {
    setFormData((prev) => ({ ...prev, petrolier: value }));
  };

  const handleFilesDrop = (acceptedFiles: File[]) => {
    if (acceptedFiles.length > 0) {
      const file = acceptedFiles[0];
      setFiles(acceptedFiles);
      setFormData((prev) => ({ ...prev, fichierPetrolier: file }));
    }
  };

  const handleFilesRemove = () => {
    setFiles([]);
    setFormData((prev) => ({ ...prev, fichierPetrolier: null }));
  };

  const handleValidate = () => {
    if (!formData.petrolier) {
      enqueueSnackbar('Veuillez sélectionner un pétrolier', { variant: 'warning' });
      return;
    }

    if (!formData.fichierPetrolier) {
      enqueueSnackbar('Veuillez sélectionner un fichier à importer', { variant: 'warning' });
      return;
    }

    enqueueSnackbar('Import des données réussi avec succès !', { variant: 'success' });

    setFormData({
      id: '',
      petrolier: '',
      fichierPetrolier: null,
    });
    setFiles([]);

    if (onImportSuccess) {
      onImportSuccess();
    }
  };

  const [showUploadZone, setShowUploadZone] = useState(false);
  useEffect(() => {
    setShowUploadZone(!!formData.petrolier);
  }, [formData.petrolier]);

  return (
    <>
      <Card
        elevation={2}
        sx={{
          borderRadius: 3,
          border: `2px solid ${theme.palette.primary.light}20`,
          overflow: 'inherit',
        }}
      >
        <Box
          sx={{
            background: `linear-gradient(135deg, ${theme.palette.primary.main} 0%, ${theme.palette.primary.dark} 100%)`,
            p: 3,
            color: 'white',
          }}
        >
          <Stack direction="row" alignItems="center" spacing={2}>
            <FontAwesome icon={faFileImport} sx={{ fontSize: '2rem' }} />
            <Box>
              <Typography variant="h5" sx={{ fontWeight: 600, mb: 0.5 }}>
                Section d&apos;importation des données pétroliers
              </Typography>
              <Typography variant="body2" sx={{ opacity: 0.9 }}>
                Importez facilement vos données de cartes carburant depuis vos fournisseurs
              </Typography>
            </Box>
          </Stack>
        </Box>

        <CardContent sx={{ p: 4 }}>
          <Grid container spacing={4}>
            {/* Sélection du pétrolier */}
            <Grid item xs={12} md={6}>
              <FormControl fullWidth>
                <InputLabel id="petrolier-label">Pétrolier</InputLabel>
                <Select
                  labelId="petrolier-label"
                  value={formData.petrolier}
                  label="Pétrolier"
                  placeholder="Choisissez un pétrolier"
                  displayEmpty
                  onChange={(e) => handlePetrolierChange(e.target.value)}
                  startAdornment={
                    <FontAwesome
                      icon={faCheck}
                      sx={{
                        color: theme.palette.primary.main,
                        mr: 1,
                        fontSize: '1.1rem',
                      }}
                    />
                  }
                  sx={{
                    '& .MuiSelect-select': {
                      display: 'flex',
                      alignItems: 'center',
                    },
                  }}
                >
                  <MenuItem value="" disabled>
                    <em>Choisissez un pétrolier</em>
                  </MenuItem>
                  {petrolierOptions.map((option) => (
                    <MenuItem key={option.value} value={option.value}>
                      {option.label}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
              <FileTemplatesList />
            </Grid>

            {/* Zone d'upload de fichier */}
            <Grid item xs={12} md={6}>
              <ConditionalComponent isValid={showUploadZone} defaultComponent={null}>
                <Box>
                  <>
                    <Paper
                      sx={{
                        padding: '20px',
                        borderRadius: '8px',
                        boxShadow: 3,
                        backgroundColor: theme.palette.background.paper,
                      }}
                    >
                      <Upload
                        multiple
                        files={files}
                        onDrop={handleFilesDrop}
                        onRemove={handleFilesRemove}
                        accept={{
                          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': [
                            '.xlsx',
                          ],
                          'application/vnd.ms-excel': ['.xls'],
                          'text/csv': ['.csv'],
                        }}
                      />
                    </Paper>

                    <Box sx={{ mt: 2 }}>
                      <Grid container spacing={2}>
                        <ConditionalComponent isValid={!!files.length}>
                          <Grid item xs={12} md={6}>
                            <Button
                              variant="outlined"
                              color="error"
                              onClick={handleFilesRemove}
                              startIcon={<FontAwesome icon={faTrashAlt} />}
                              sx={{
                                width: '100%',
                                padding: '12px 16px',
                                borderRadius: '8px',
                                color: theme.palette.error.main,
                                borderColor: theme.palette.error.main,
                                '&:hover': {
                                  borderColor: theme.palette.error.dark,
                                  color: theme.palette.error.dark,
                                },
                              }}
                            >
                              Retirer
                            </Button>
                          </Grid>
                        </ConditionalComponent>
                        <Grid
                          item
                          xs={12}
                          md={6}
                          sx={{
                            ml: files.length === 0 ? 'auto' : 0,
                          }}
                        >
                          {' '}
                          <Button
                            variant="contained"
                            startIcon={<FontAwesome icon={faCloudUploadAlt} />}
                            onClick={handleValidate}
                            disabled={files.length === 0}
                            sx={{
                              backgroundColor: theme.palette.primary.main,
                              '&:hover': {
                                backgroundColor: theme.palette.primary.dark,
                              },
                              width: '100%',
                              padding: '12px 16px',
                              borderRadius: '8px',
                              boxShadow: 2,
                            }}
                          >
                            Importer
                          </Button>
                        </Grid>
                      </Grid>
                    </Box>
                  </>
                </Box>
              </ConditionalComponent>
            </Grid>
          </Grid>
        </CardContent>
      </Card>
    </>
  );
}