import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Stack,
  Typography,
} from '@mui/material';
import { useState, useEffect } from 'react';
import { StyledTextField } from '@/shared/theme/css';
import { pxToRem } from '@/shared/theme/typography';
import { outlinedColor } from '@/shared/components/table/styles';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPen } from '@fortawesome/free-solid-svg-icons';
import { FleetFileNode } from '../hooks/use-fleet-file-manager';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

interface RenameDialogProps {
  open: boolean;
  onClose: () => void;
  onRename: (newName: string) => void;
  item: FleetFileNode | null;
}

export default function RenameDialog({ 
  open, 
  onClose, 
  onRename, 
  item 
}: RenameDialogProps) {
  const [newName, setNewName] = useState('');
  const [error, setError] = useState('');

  useEffect(() => {
    if (item && open) {
      // Remove file extension for files to make renaming easier
      if (item.type === 'file') {
        const nameParts = item.name.split('.');
        if (nameParts.length > 1) {
          setNewName(nameParts.slice(0, -1).join('.'));
        } else {
          setNewName(item.name);
        }
      } else {
        setNewName(item.name);
      }
    }
  }, [item, open]);

  const handleSubmit = (event: React.FormEvent) => {
    event.preventDefault();
    
    if (!newName.trim()) {
      setError('Le nom est obligatoire');
      return;
    }
    
    if (newName.includes('/') || newName.includes('\\')) {
      setError('Le nom ne peut pas contenir / ou \\');
      return;
    }
    
    if (newName === item?.name || (item?.type === 'file' && getFullFileName(newName, item) === item.name)) {
      setError('Le nouveau nom doit être différent de l&apos;actuel');
      return;
    }
    
    const finalName = item?.type === 'file' ? getFullFileName(newName, item) : newName.trim();
    onRename(finalName);
    handleClose();
  };

  const handleClose = () => {
    setNewName('');
    setError('');
    onClose();
  };

  const getFullFileName = (nameWithoutExt: string, fileItem: FleetFileNode): string => {
    const nameParts = fileItem.name.split('.');
    if (nameParts.length > 1) {
      const extension = nameParts[nameParts.length - 1];
      return `${nameWithoutExt.trim()}.${extension}`;
    }
    return nameWithoutExt.trim();
  };

  if (!item) return null;

  return (
    <Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>
      <DialogTitle
        sx={{
          fontSize: pxToRem(20),
          color: 'primary.main',
          fontWeight: (theme) => theme.typography.fontWeightBold,
          display: 'flex',
          alignItems: 'center',
          gap: 1,
        }}
      >
        <FontAwesomeIcon icon={faPen} />
        Renommer {item.type === 'folder' ? 'le dossier' : 'le fichier'}
      </DialogTitle>
      
      <form onSubmit={handleSubmit}>
        <DialogContent>
          <Stack spacing={3}>
            <ConditionalComponent isValid={!!item}>
              <Typography variant="body2" color="text.secondary">
                {item?.type === 'folder' 
                  ? `Renommer le dossier : ${item?.name}`
                  : `Renommer le fichier : ${item?.name}`
                }
              </Typography>
            </ConditionalComponent>
            
            <StyledTextField
              fullWidth
              label={item?.type === 'folder' ? 'Nouveau nom du dossier' : 'Nouveau nom du fichier'}
              placeholder={item?.type === 'folder' ? 'Entrez le nouveau nom du dossier' : 'Entrez le nouveau nom (sans extension)'}
              value={newName}
              onChange={(e) => {
                setNewName(e.target.value);
                if (error) setError('');
              }}
              error={!!error}
              helperText={error || (item?.type === 'file' ? `Extension actuelle : .${item?.name.split('.').pop()}` : '')}
              autoFocus
              required
            />

            <ConditionalComponent isValid={item?.type === 'file' && newName.length > 0 && !error}>
              <Typography variant="caption" color="info.main">
                Le fichier sera renommé en : {getFullFileName(newName, item!)}
              </Typography>
            </ConditionalComponent>

            <ConditionalComponent isValid={item?.type === 'folder' && newName.length > 0 && !error}>
              <Typography variant="caption" color="info.main">
                Le dossier sera renommé en : {newName}
              </Typography>
            </ConditionalComponent>
          </Stack>
        </DialogContent>
        
        <DialogActions>
          <Button
            sx={{ ...outlinedColor }}
            variant="outlined"
            onClick={handleClose}
          >
            Annuler
          </Button>
          <Button type="submit" variant="contained">
            Renommer
          </Button>
        </DialogActions>
      </form>
    </Dialog>
  );
} 