import {
  Box,
  Typography,
  Stack,
  Button,
  IconButton,
  TextField,
  MenuItem,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  Collapse,
  Drawer,
  Autocomplete,
} from '@mui/material';
import { useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
  faFolder,
  faFolderOpen,
  faFile,
  faTrash,
  faArchive,
  faUpload,
  faChevronRight,
  faChevronDown,
  faTimes,
  faArrowLeft,
  faFolderPlus,
  faSquarePlus,
  faFileUpload,
  faFileArrowUp,
  faArrowRight,
} from '@fortawesome/free-solid-svg-icons';
import { StyledTextField } from '@/shared/theme/css';
import { AddButton } from '@/shared/components/table/styles';
import FontAwesome from '@/shared/components/fontawesome';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

interface DocumentNode {
  id: string;
  name: string;
  type: 'folder' | 'file';
  category?: string;
  documentType?: 'attestation' | 'contrat' | 'fiche de paie';
  children?: DocumentNode[];
}

interface DocumentLibraryProps {
  open: boolean;
  onClose: () => void;
}

// Add this constant for predefined document types
const PREDEFINED_DOCUMENT_TYPES = ['attestation', 'contrat', 'fiche de paie'];

export default function DocumentLibrary({ open, onClose }: DocumentLibraryProps) {
  const [expanded, setExpanded] = useState<string[]>([]);
  const [selected, setSelected] = useState<string>('');
  const [openUpload, setOpenUpload] = useState(false);
  const [documentType, setDocumentType] = useState<string>('');
  const [documents, setDocuments] = useState<DocumentNode[]>([
    {
      id: '1',
      name: 'Contrats',
      type: 'folder',
      children: [{ id: '1-1', name: 'Contrat CDI', type: 'file', documentType: 'contrat' }],
    },
    {
      id: '2',
      name: 'Attestations',
      type: 'folder',
      children: [
        { id: '2-1', name: 'Attestation Emploi', type: 'file', documentType: 'attestation' },
      ],
    },
  ]);
  const [isAddingFolder, setIsAddingFolder] = useState(false);
  const [newFolderName, setNewFolderName] = useState('');

  const handleDelete = (nodeId: string) => {
    console.log('Delete document:', nodeId);
  };

  const handleArchive = (nodeId: string) => {
    console.log('Archive document:', nodeId);
  };

  const toggleExpand = (nodeId: string) => {
    setExpanded((prev) =>
      prev.includes(nodeId) ? prev.filter((id) => id !== nodeId) : [...prev, nodeId]
    );
  };

  const handleAddFolder = () => {
    if (newFolderName.trim()) {
      const newFolder: DocumentNode = {
        id: `folder-${Date.now()}`,
        name: newFolderName.trim(),
        type: 'folder',
        children: [],
      };
      setDocuments([...documents, newFolder]);
      setNewFolderName('');
      setIsAddingFolder(false);
    }
  };

  const renderDocumentNode = (node: DocumentNode) => {
    const isExpanded = expanded.includes(node.id);
    const isFolder = node.type === 'folder';

    return (
      <Box key={node.id}>
        <ListItem
          sx={{
            cursor: 'pointer',
            bgcolor: selected === node.id ? 'action.selected' : 'transparent',
            '&:hover': { bgcolor: 'action.hover' },
          }}
          onClick={() => {
            if (isFolder) {
              toggleExpand(node.id);
            }
            setSelected(node.id);
          }}
        >
          <ListItemIcon sx={{ minWidth: 35 }}>
            <FontAwesomeIcon icon={isFolder ? (isExpanded ? faFolderOpen : faFolder) : faFile} />
          </ListItemIcon>
          <ListItemText primary={node.name} />
          <ConditionalComponent isValid={isFolder && !!node.children?.length}>
            <FontAwesomeIcon icon={isExpanded ? faChevronDown : faChevronRight} />
          </ConditionalComponent>
          <ConditionalComponent isValid={!isFolder}>
            <Stack direction="row" spacing={1}>
              <IconButton
                size="small"
                onClick={(e) => {
                  e.stopPropagation();
                  handleArchive(node.id);
                }}
              >
                <FontAwesomeIcon icon={faArchive} />
              </IconButton>
              <IconButton
                size="small"
                onClick={(e) => {
                  e.stopPropagation();
                  handleDelete(node.id);
                }}
              >
                <FontAwesomeIcon icon={faTrash} />
              </IconButton>
            </Stack>
          </ConditionalComponent>
        </ListItem>
        <ConditionalComponent isValid={isFolder && !!node.children?.length}>
          <Collapse in={isExpanded}>
            <List sx={{ pl: 4 }}>{node.children?.map((child) => renderDocumentNode(child))}</List>
          </Collapse>
        </ConditionalComponent>
      </Box>
    );
  };

  return (
    <Drawer
      anchor="right"
      open={open}
      onClose={onClose}
      variant="persistent"
      sx={{
        '& .MuiDrawer-paper': {
          width: 700,
          boxSizing: 'border-box',
          borderLeft: '1px solid',
          borderColor: 'divider',
        },
      }}
    >
      <Box sx={{ p: 2, borderBottom: '1px solid', borderColor: 'divider' }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          <IconButton
            onClick={onClose}
            sx={{
              width: 28,
              height: 28,
              borderRadius: '8px',
              backgroundColor: 'primary.lighter',
              color: 'primary.main',
              '&:hover': {
                backgroundColor: 'primary.light',
              },
            }}
          >
            <FontAwesomeIcon icon={faArrowLeft} width={16} />
          </IconButton>
          <Typography variant="h6" sx={{ fontSize: '1rem', fontWeight: 600 }}>
            Bibliothèque de documents
          </Typography>
        </Box>
      </Box>

      <Box sx={{ p: 3 }}>
        <Stack direction="row" justifyContent="space-between" mb={3}>
          <Button
            startIcon={<FontAwesomeIcon icon={faFolderPlus} />}
            variant="outlined"
            onClick={() => setIsAddingFolder(true)}
          >
            Nouveau dossier
          </Button>

          <Button
            endIcon={<FontAwesomeIcon icon={faSquarePlus} />}
            variant="contained"
            onClick={() => setOpenUpload(true)}
          >
            Ajouter un document
          </Button>
        </Stack>

        <Box sx={{ display: 'flex', gap: 3 }}>
          {/* Left side: Document Tree */}
          <Box sx={{ width: 300, borderRight: '1px solid', borderColor: 'divider', pr: 2 }}>
            <ConditionalComponent isValid={isAddingFolder}>
              <Box sx={{ mb: 2, py: 2, bgcolor: 'background.paper', borderRadius: 1 }}>
                <Stack spacing={2}>
                  <StyledTextField
                    fullWidth
                    size="small"
                    label="Nom du dossier"
                    value={newFolderName}
                    placeholder="Entrez le nom du dossier"
                    onChange={(e) => setNewFolderName(e.target.value)}
                    autoFocus
                    InputLabelProps={{
                      shrink: true,
                    }}
                  />
                  <Stack direction="row" spacing={1} justifyContent="flex-end">
                    <Button size="small" onClick={() => setIsAddingFolder(false)}>
                      Annuler
                    </Button>
                    <Button
                      size="small"
                      variant="contained"
                      onClick={handleAddFolder}
                      disabled={!newFolderName.trim()}
                    >
                      Créer
                    </Button>
                  </Stack>
                </Stack>
              </Box>
            </ConditionalComponent>

            <List>{documents.map((node) => renderDocumentNode(node))}</List>
          </Box>

          {/* Right side: Document Details or Upload Form */}
          <Box sx={{ flex: 1, bgcolor: 'background.paper', borderRadius: 1, p: 3 }}>
            <ConditionalComponent
              isValid={!!openUpload}
              defaultComponent={
                <Box sx={{ textAlign: 'center', color: 'text.secondary', py: 8 }}>
                  <Typography>Sélectionnez un document pour voir les détails</Typography>
                </Box>
              }
            >
              <Box>
                <Stack direction="row" justifyContent="space-between" alignItems="center" mb={3}>
                  <Typography variant="h6">Ajouter un document</Typography>
                  <IconButton onClick={() => setOpenUpload(false)}>
                    <FontAwesomeIcon icon={faTimes} />
                  </IconButton>
                </Stack>

                <Stack spacing={3}>
                  <Autocomplete
                    freeSolo
                    value={documentType}
                    onChange={(_, newValue) => setDocumentType(newValue || '')}
                    options={PREDEFINED_DOCUMENT_TYPES}
                    renderInput={(params) => (
                      <StyledTextField
                        {...params}
                        label="Type de document"
                        fullWidth
                        sx={{
                          '& .MuiInputBase-root': {
                            padding: 0,
                          },
                        }}
                        placeholder={'Sélectionnez un type'}
                        InputLabelProps={{
                          shrink: true,
                        }}
                      />
                    )}
                  />
                  <Box>
                    <AddButton
                      variant="outlined"
                      sx={{ minHeight: '43px' }}
                      endIcon={<FontAwesome icon={faFileArrowUp} width={18} />}
                      fullWidth
                    >
                      Sélectionner un fichier
                      <input type="file" hidden />
                    </AddButton>
                  </Box>
                  <Stack direction="row" spacing={1} justifyContent="flex-end">
                    <Button onClick={() => setOpenUpload(false)}>Annuler</Button>
                    <Button variant="contained">Importer</Button>
                  </Stack>
                </Stack>
              </Box>
            </ConditionalComponent>
          </Box>
        </Box>
      </Box>
    </Drawer>
  );
}
