import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Stack,
  Typography,
  Box,
  LinearProgress,
  Alert,
  MenuItem,
  FormControl,
  InputLabel,
  Select,
  CircularProgress,
} from '@mui/material';
import { useState, useRef, useEffect } from 'react';
import { StyledTextField } from '@/shared/theme/css';
import { pxToRem } from '@/shared/theme/typography';
import { outlinedColor, AddButton } from '@/shared/components/table/styles';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faUpload, faFile, faTimes } from '@fortawesome/free-solid-svg-icons';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import FontAwesome from '@/shared/components/fontawesome';
import { useVehicleStore } from '@/shared/api/stores/fleet-service/vehicle-store';

interface UploadFileDialogProps {
  open: boolean;
  onClose: () => void;
  onUpload: (files: File[], metadata: FileMetadata) => void;
  currentPath: string[];
}

interface FileMetadata {
  vehicleId?: string;
  documentType?: string;
  category?: string;
  description?: string;
}

const DOCUMENT_TYPES = [
  { value: 'assurance', label: 'Assurance' },
  { value: 'carte_grise', label: 'Carte grise' },
  { value: 'controle_technique', label: 'Contrôle technique' },
  { value: 'contrat_location', label: 'Contrat de location' },
  { value: 'revision', label: 'Révision' },
  { value: 'permis_conduire', label: 'Permis de conduire' },
  { value: 'autre', label: 'Autre' },
];

const CATEGORIES = [
  { value: 'VEHICULE', label: 'Véhicule' },
  { value: 'MAINTENANCE', label: 'Maintenance' },
  { value: 'LEGAL', label: 'Légal' },
  { value: 'ASSURANCE', label: 'Assurance' },
];

export default function UploadFileDialog({ 
  open, 
  onClose, 
  onUpload, 
  currentPath 
}: UploadFileDialogProps) {
  const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
  const [metadata, setMetadata] = useState<FileMetadata>({});
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState('');
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  const { vehiclesPage, loading: loadingVehicles, fetchVehiclesPage } = useVehicleStore();
  
  useEffect(() => {
    if (open) {
      fetchVehiclesPage({ page: 0, size: 1000, orderBy: 'id', orderDir: 'desc' });
    }
  }, [open, fetchVehiclesPage]);

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(event.target.files || []);
    setSelectedFiles(files);
    setError('');
  };

  const handleRemoveFile = (index: number) => {
    setSelectedFiles(prev => prev.filter((_, i) => i !== index));
  };

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    
    if (selectedFiles.length === 0) {
      setError('Veuillez sélectionner au moins un fichier');
      return;
    }

    setUploading(true);
    try {
      // Simulate upload delay
      await new Promise(resolve => setTimeout(resolve, 1500));
      onUpload(selectedFiles, metadata);
      handleClose();
    } catch (err) {
      setError('Erreur lors du téléchargement');
    } finally {
      setUploading(false);
    }
  };

  const handleClose = () => {
    setSelectedFiles([]);
    setMetadata({});
    setError('');
    setUploading(false);
    onClose();
  };

  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const totalSize = selectedFiles.reduce((sum, file) => sum + file.size, 0);

  return (
    <Dialog open={open} onClose={handleClose} maxWidth="md" fullWidth>
      <DialogTitle
        sx={{
          fontSize: pxToRem(20),
          color: 'primary.main',
          fontWeight: (theme) => theme.typography.fontWeightBold,
          display: 'flex',
          alignItems: 'center',
          gap: 1,
        }}
      >
        <FontAwesome icon={faUpload} width={20} />
        Télécharger des fichiers
      </DialogTitle>
      
      <form onSubmit={handleSubmit}>
        <DialogContent>
          <Stack spacing={3}>
            <Typography variant="body2" color="text.secondary">
              Ajouter des fichiers dans : {currentPath.join(' > ')}
            </Typography>

            {/* File Selection */}
            <Box>
              <AddButton
                variant="outlined"
                onClick={() => fileInputRef.current?.click()}
                startIcon={<FontAwesome icon={faUpload} width={16} />}
                sx={{ mb: 2 }}
                disabled={uploading}
              >
                Sélectionner des fichiers
              </AddButton>
              <input
                ref={fileInputRef}
                type="file"
                multiple
                hidden
                onChange={handleFileSelect}
                accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.gif"
              />
            </Box>

            {/* Selected Files */}
            <ConditionalComponent isValid={selectedFiles.length > 0}>
              <Box sx={{ border: 1, borderColor: 'divider', borderRadius: 1, p: 2 }}>
                <Typography variant="subtitle2" sx={{ mb: 2 }}>
                  Fichiers sélectionnés ({selectedFiles.length})
                </Typography>
                <Stack spacing={1}>
                  {selectedFiles.map((file, index) => (
                    <Box
                      key={index}
                      sx={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        p: 1,
                        bgcolor: 'grey.50',
                        borderRadius: 1,
                      }}
                    >
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <FontAwesome icon={faFile} width={16} />
                        <Box>
                          <Typography variant="body2">{file.name}</Typography>
                          <Typography variant="caption" color="text.secondary">
                            {formatFileSize(file.size)}
                          </Typography>
                        </Box>
                      </Box>
                      <Button
                        size="small"
                        onClick={() => handleRemoveFile(index)}
                        disabled={uploading}
                      >
                        <FontAwesome icon={faTimes} width={14} />
                      </Button>
                    </Box>
                  ))}
                </Stack>
                <Typography variant="caption" color="text.secondary" sx={{ mt: 1, display: 'block' }}>
                  Taille totale: {formatFileSize(totalSize)}
                </Typography>
              </Box>
            </ConditionalComponent>

            {/* Metadata Form */}
            <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 2 }}>
              <FormControl size="small">
                <InputLabel>Véhicule (optionnel)</InputLabel>
                <Select
                  value={metadata.vehicleId || ''}
                  onChange={(e) => {
                    console.log('🚗 Vehicle selected:', e.target.value);
                    setMetadata(prev => ({ ...prev, vehicleId: e.target.value }));
                  }}
                  label="Véhicule (optionnel)"
                  disabled={loadingVehicles}
                >
                  <MenuItem value="">Aucun véhicule</MenuItem>
                  {loadingVehicles && (
                    <MenuItem disabled>
                      <CircularProgress size={16} sx={{ mr: 1 }} />
                      Chargement des véhicules...
                    </MenuItem>
                  )}
                  {!loadingVehicles && vehiclesPage && vehiclesPage.length > 0 && 
                    vehiclesPage.map((vehicle) => (
                      <MenuItem key={vehicle.id} value={vehicle.id}>
                        {vehicle.registrationPlate} - {vehicle.brandName} {vehicle.modelName}
                      </MenuItem>
                    ))
                  }
                  {!loadingVehicles && (!vehiclesPage || vehiclesPage.length === 0) && (
                    <MenuItem disabled>
                      Aucun véhicule disponible
                    </MenuItem>
                  )}
                </Select>
              </FormControl>

              <FormControl size="small">
                <InputLabel>Type de document</InputLabel>
                <Select
                  value={metadata.documentType || ''}
                  onChange={(e) => setMetadata(prev => ({ ...prev, documentType: e.target.value }))}
                  label="Type de document"
                >
                  <MenuItem value="">Sélectionner un type</MenuItem>
                  {DOCUMENT_TYPES.map((type) => (
                    <MenuItem key={type.value} value={type.value}>
                      {type.label}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>

              <FormControl size="small">
                <InputLabel>Catégorie</InputLabel>
                <Select
                  value={metadata.category || ''}
                  onChange={(e) => setMetadata(prev => ({ ...prev, category: e.target.value }))}
                  label="Catégorie"
                >
                  <MenuItem value="">Sélectionner une catégorie</MenuItem>
                  {CATEGORIES.map((category) => (
                    <MenuItem key={category.value} value={category.value}>
                      {category.label}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>

              <StyledTextField
                size="small"
                label="Description"
                placeholder="Description optionnelle"
                value={metadata.description || ''}
                onChange={(e) => setMetadata(prev => ({ ...prev, description: e.target.value }))}
              />
            </Box>

            {/* Upload Progress */}
            <ConditionalComponent isValid={uploading}>
              <Box>
                <Typography variant="body2" sx={{ mb: 1 }}>
                  Téléchargement en cours...
                </Typography>
                <LinearProgress />
              </Box>
            </ConditionalComponent>

            {/* Error Display */}
            <ConditionalComponent isValid={!!error}>
              <Alert severity="error">{error}</Alert>
            </ConditionalComponent>

            {/* Upload completed info */}
            <ConditionalComponent isValid={selectedFiles.length > 0 && !uploading}>
              <Typography variant="caption" color="text.secondary">
                Prêt à télécharger {selectedFiles.length} fichier(s)
              </Typography>
            </ConditionalComponent>
          </Stack>
        </DialogContent>
        
        <DialogActions>
          <Button
            sx={{ ...outlinedColor }}
            variant="outlined"
            onClick={handleClose}
            disabled={uploading}
          >
            Annuler
          </Button>
          <Button 
            type="submit" 
            variant="contained"
            disabled={selectedFiles.length === 0 || uploading}
          >
            <ConditionalComponent isValid={uploading}>
              Téléchargement...
            </ConditionalComponent>
            <ConditionalComponent isValid={!uploading}>
              Télécharger
              <ConditionalComponent isValid={selectedFiles.length > 0}>
                {` (${selectedFiles.length})`}
              </ConditionalComponent>
            </ConditionalComponent>
          </Button>
        </DialogActions>
      </form>
    </Dialog>
  );
} 