import React, { useEffect, useMemo, useState, useCallback, useRef } from 'react';
import {
  ThemeProvider,
  createTheme,
  useMediaQuery,
  Button,
  List,
  ListItem,
  ListItemText,
  IconButton,
  styled,
  CircularProgress,
  Divider,
  Menu,
  MenuItem,
  Box,
  Typography,
  TextField,
  Select,
  FormControl,
  InputLabel,
  Pagination,
  Stack,
  Chip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Paper,
  Alert,
  LinearProgress
} from '@mui/material';
import UploadIcon from '@mui/icons-material/Upload';
import FolderIcon from '@mui/icons-material/Folder';
import FolderOpenIcon from '@mui/icons-material/FolderOpen';
import DeleteIcon from '@mui/icons-material/Delete';
import RefreshIcon from '@mui/icons-material/Refresh';
import MoreVertIcon from '@mui/icons-material/MoreVert';
import ImageIcon from '@mui/icons-material/Image';
import DescriptionIcon from '@mui/icons-material/Description';
import InsertDriveFileIcon from '@mui/icons-material/InsertDriveFile';
import { useTLDraw } from '../../../../../contexts/TLDrawContext';
import { useAuth } from '../../../../../contexts/AuthContext';
import { useNavigate } from 'react-router-dom';
import {
  calculateDirectoryStats,
  isDirectoryPickerSupported,
  FileWithPath
} from '../../../../../utils/folderPicker';

const Container = styled('div')(() => ({
  padding: '8px',
  display: 'flex',
  flexDirection: 'column',
  gap: '8px',
  height: '100%'
}));

type Cabinet = { id: string; name: string };
type FileRow = {
  id: string;
  name: string;
  mime_type?: string;
  is_directory?: boolean;
  size_bytes?: number;
  processing_status?: string;
  relative_path?: string;
  created_at?: string;
};
type Artefact = { id: string; type: string; rel_path: string; created_at: string };

interface PaginationInfo {
  page: number;
  per_page: number;
  total_count: number;
  total_pages: number;
  has_next: boolean;
  has_prev: boolean;
  offset: number;
}

interface FileListResponse {
  files: FileRow[];
  pagination: PaginationInfo;
  filters: {
    search?: string;
    sort_by: string;
    sort_order: string;
    include_directories: boolean;
    parent_directory_id?: string;
  };
}

export const CCFilesPanel: React.FC = () => {
  const { tldrawPreferences } = useTLDraw() as { tldrawPreferences?: { colorScheme?: 'light' | 'dark' | 'system' } };
  const { user: authUser, accessToken } = useAuth();
  const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
  const [cabinets, setCabinets] = useState<Cabinet[]>([]);
  const [selectedCabinet, setSelectedCabinet] = useState<string>('');
  const [files, setFiles] = useState<FileRow[]>([]);
  const [pagination, setPagination] = useState<PaginationInfo | null>(null);
  const [loading, setLoading] = useState(false);
  const [menuAnchor, setMenuAnchor] = useState<null | { el: HTMLElement; fileId: string }>(null);
  const [artefacts, setArtefacts] = useState<Artefact[]>([]);

  // Pagination and filtering state
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(15); // Slightly more for main panel
  const [searchTerm, setSearchTerm] = useState('');
  const [sortBy, setSortBy] = useState('created_at');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
  const previousSearchTerm = useRef(searchTerm);

  // Directory navigation state
  const [currentDirectoryId, setCurrentDirectoryId] = useState<string | null>(null);
  const [breadcrumbs, setBreadcrumbs] = useState<{ id: string | null; name: string }[]>([
    { id: null, name: 'Root' }
  ]);
  const initialSelectionDone = useRef(false);

  // Directory upload state
  const [selectedFiles, setSelectedFiles] = useState<FileWithPath[]>([]);
  const [showDirectoryDialog, setShowDirectoryDialog] = useState(false);
  const [isDirectoryUploading, setIsDirectoryUploading] = useState(false);
  const [directoryStats, setDirectoryStats] = useState<{
    fileCount: number;
    directoryCount: number;
    totalSize: number;
    formattedSize: string;
  } | null>(null);

  const navigate = useNavigate();

  const theme = useMemo(() => {
    const mode = (tldrawPreferences?.colorScheme === 'system')
      ? (prefersDarkMode ? 'dark' : 'light')
      : (tldrawPreferences?.colorScheme === 'dark' ? 'dark' : 'light');
    return createTheme({ palette: { mode, divider: 'var(--color-divider)' } });
  }, [tldrawPreferences?.colorScheme, prefersDarkMode]);

  type RequestInitLike = { method?: string; body?: FormData | string | Blob | null; headers?: Record<string, string> } | undefined;
  type HeadersInitLike = Record<string, string>;

  const API_BASE: string = import.meta.env.VITE_API_BASE || (location.port.startsWith('517') ? 'http://127.0.0.1:8080' : '/api');

  const apiFetch = useCallback(async (url: string, init?: RequestInitLike) => {
    const headers: HeadersInitLike = {
      'Authorization': `Bearer ${accessToken || ''}`,
      ...(init?.headers || {})
    };
    const fullUrl = url.startsWith('http') ? url : `${API_BASE}${url}`;
    const res = await fetch(fullUrl, { ...(init || {}), headers });
    if (!res.ok) throw new Error(await res.text());
    return res.json();
  }, [accessToken, API_BASE]);

  const loadCabinets = useCallback(async () => {
    setLoading(true);
    try {
      const data = await apiFetch('/database/cabinets');
      const all = [...(data.owned || []), ...(data.shared || [])];
      setCabinets(all);
      if (all.length && !initialSelectionDone.current) {
        initialSelectionDone.current = true;
        setSelectedCabinet(all[0].id);
      }
    } catch (error) {
      console.error('Failed to load cabinets:', error);
    } finally {
      setLoading(false);
    }
  }, [apiFetch]);

  const loadFiles = useCallback(async (cabinetId: string, page: number = currentPage) => {
    if (!cabinetId) return;

    setLoading(true);
    try {
      // Build query parameters for pagination, search, and sorting
      const params = new URLSearchParams({
        cabinet_id: cabinetId,
        page: page.toString(),
        per_page: itemsPerPage.toString(),
        sort_by: sortBy,
        sort_order: sortOrder,
        include_directories: 'true'
      });

      // Add directory filtering
      if (currentDirectoryId) {
        params.append('parent_directory_id', currentDirectoryId);
      }

      if (searchTerm) {
        params.append('search', searchTerm);
      }

      // Use the new simple upload endpoint for listing files with pagination
      const data: FileListResponse = await apiFetch(`/simple-upload/files?${params.toString()}`);

      setFiles(data.files || []);
      setPagination(data.pagination);
    } catch (error) {
      console.error('Failed to load files:', error);
    } finally {
      setLoading(false);
    }
  }, [currentPage, itemsPerPage, sortBy, sortOrder, searchTerm, apiFetch, currentDirectoryId]);

  useEffect(() => {
    if (authUser?.id) {
      initialSelectionDone.current = false;
      loadCabinets();
    }
  }, [loadCabinets, authUser?.id]);

  // Main loading effect - handles pagination, sorting, cabinet changes, directory navigation
  useEffect(() => {
    if (selectedCabinet) {
      loadFiles(selectedCabinet, currentPage);
    }
  }, [selectedCabinet, loadFiles, currentPage, itemsPerPage, sortBy, sortOrder, currentDirectoryId]);

  // Reset to page 1 and root directory when cabinet changes
  useEffect(() => {
    if (selectedCabinet) {
      setCurrentPage(1);
      setCurrentDirectoryId(null);
      setBreadcrumbs([{ id: null, name: 'Root' }]);
    }
  }, [selectedCabinet]);

  // Search with debouncing - only when search term actually changes
  useEffect(() => {
    if (selectedCabinet && searchTerm !== previousSearchTerm.current) {
      previousSearchTerm.current = searchTerm;

      const timeoutId = setTimeout(() => {
        setCurrentPage(1); // Reset to first page when searching
        loadFiles(selectedCabinet, 1);
      }, 500); // 500ms debounce

      return () => clearTimeout(timeoutId);
    }
  }, [searchTerm, selectedCabinet, loadFiles]);

  // Directory navigation handlers
  const navigateToFolder = useCallback((folder: FileRow) => {
    if (!folder.is_directory) return;

    setCurrentDirectoryId(folder.id);
    setCurrentPage(1); // Reset to first page when entering folder

    // Add to breadcrumbs
    setBreadcrumbs(prev => [...prev, { id: folder.id, name: folder.name }]);
  }, []);

  const navigateToBreadcrumb = useCallback((targetBreadcrumb: { id: string | null; name: string }) => {
    setCurrentDirectoryId(targetBreadcrumb.id);
    setCurrentPage(1); // Reset to first page

    // Trim breadcrumbs to the selected one
    setBreadcrumbs(prev => {
      const targetIndex = prev.findIndex(b => b.id === targetBreadcrumb.id && b.name === targetBreadcrumb.name);
      return targetIndex !== -1 ? prev.slice(0, targetIndex + 1) : [{ id: null, name: 'Root' }];
    });
  }, []);

  // Sort files to group directories first, then regular files
  const sortedFiles = useMemo(() => {
    return [...files].sort((a, b) => {
      // Directories come first
      if (a.is_directory && !b.is_directory) return -1;
      if (!a.is_directory && b.is_directory) return 1;

      // Within the same type (both directories or both files), sort alphabetically by name
      return a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' });
    });
  }, [files]);

  // Check if we need a separator between directories and files
  const needsGroupSeparator = useMemo(() => {
    const hasDirectories = sortedFiles.some(f => f.is_directory);
    const hasFiles = sortedFiles.some(f => !f.is_directory);
    return hasDirectories && hasFiles;
  }, [sortedFiles]);

  const getGroupSeparatorIndex = useMemo(() => {
    if (!needsGroupSeparator) return -1;
    return sortedFiles.findIndex(f => !f.is_directory) - 1;
  }, [sortedFiles, needsGroupSeparator]);

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files || !selectedCabinet) return;
    const file = e.target.files[0];
    await uploadFile(file);
    (e.target as HTMLInputElement).value = '';
  };

  const handleDirectorySelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files || !selectedCabinet) return;

    // Convert FileList to FileWithPath array with relative paths
    const files: FileWithPath[] = [];
    Array.from(e.target.files).forEach(file => {
      const relativePath = (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name;
      (file as FileWithPath).relativePath = relativePath;
      files.push(file as FileWithPath);
    });

    if (files.length > 0) {
      prepareDirectoryUpload(files);
    }

    (e.target as HTMLInputElement).value = '';
  };

  const uploadFile = async (file: File) => {
    if (!selectedCabinet) return;
    const form = new FormData();
    form.append('cabinet_id', selectedCabinet);
    form.append('path', file.name);
    form.append('scope', 'teacher');
    form.append('file', file);
    await apiFetch('/database/files/upload', { method: 'POST', body: form });
    await loadFiles(selectedCabinet);
  };


  const prepareDirectoryUpload = (files: FileWithPath[]) => {
    if (files.length === 0) return;

    setSelectedFiles(files);
    setDirectoryStats(calculateDirectoryStats(files));
    setShowDirectoryDialog(true);
  };

  const startDirectoryUpload = async () => {
    if (!selectedCabinet || selectedFiles.length === 0) return;

    setIsDirectoryUploading(true);

    try {
      const firstFilePath = selectedFiles[0].relativePath;
      const directoryName = firstFilePath.split('/')[0] || 'uploaded-folder';

      const formData = new FormData();
      formData.append('cabinet_id', selectedCabinet);
      formData.append('scope', 'teacher');
      formData.append('directory_name', directoryName);

      selectedFiles.forEach(file => {
        formData.append('files', file);
      });

      const relativePaths = selectedFiles.map(f => f.relativePath);
      formData.append('file_paths', JSON.stringify(relativePaths));

      await apiFetch('/simple-upload/files/upload-directory', {
        method: 'POST',
        body: formData
      });

      await loadFiles(selectedCabinet);

      setShowDirectoryDialog(false);
      setSelectedFiles([]);
      setDirectoryStats(null);
    } catch (error) {
      console.error('Directory upload failed:', error);
    } finally {
      setIsDirectoryUploading(false);
    }
  };

  const handleDelete = async (fileId: string) => {
    await apiFetch(`/database/files/${fileId}`, { method: 'DELETE' });
    await loadFiles(selectedCabinet);
  };

  const handleGenerateInitial = async (fileId: string) => {
    await apiFetch(`/database/files/${fileId}/artefacts/initial`, { method: 'POST' });
    const arts = await apiFetch(`/database/files/${fileId}/artefacts`);
    setArtefacts(arts || []);
  };

  const openMenu = (el: HTMLElement, fileId: string) => setMenuAnchor({ el, fileId });
  const closeMenu = () => setMenuAnchor(null);
  const goToAIContent = () => {
    if (!menuAnchor) return;
    const fileId = menuAnchor.fileId;
    closeMenu();
    navigate(`/doc-intelligence/${encodeURIComponent(fileId)}`);
  };

  const iconForMime = (mime?: string, isDirectory?: boolean) => {
    if (isDirectory) return <FolderIcon />;
    if (!mime) return <InsertDriveFileIcon />;
    if (mime.startsWith('image/')) return <ImageIcon />;
    if (mime === 'application/pdf' || mime.startsWith('application/')) return <DescriptionIcon />;
    return <InsertDriveFileIcon />;
  };

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

  const getStatusColor = (status?: string) => {
    switch (status) {
      case 'uploaded': return 'primary';
      case 'processing': return 'warning';
      case 'completed': return 'success';
      case 'failed': return 'error';
      default: return 'default';
    }
  };

  return (
    <ThemeProvider theme={theme}>
      <Container>
        {/* Cabinet Selection Dropdown */}
        <Box sx={{ display: 'flex', gap: 1, alignItems: 'center', mb: 1 }}>
          <FormControl size="small" fullWidth>
            <InputLabel>Cabinet</InputLabel>
            <Select
              value={selectedCabinet}
              label="Cabinet"
              onChange={(e) => setSelectedCabinet(e.target.value)}
              startAdornment={<FolderIcon sx={{ color: 'action.active', mr: 1, fontSize: '1rem' }} />}
            >
              {cabinets.map(c => (
                <MenuItem key={c.id} value={c.id}>
                  <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}>
                    <Typography variant="body2">{c.name}</Typography>
                    {pagination && selectedCabinet === c.id && (
                      <Chip label={`${pagination.total_count} files`} size="small" sx={{ ml: 1 }} />
                    )}
                  </Box>
                </MenuItem>
              ))}
            </Select>
          </FormControl>

          <Button
            size="small"
            variant="outlined"
            onClick={() => {
              setCurrentPage(1);
              setSearchTerm('');
              loadCabinets();
            }}
            sx={{
              minWidth: 40,
              width: 40,
              height: 40, // Match the height of Select components
              padding: 0,
              '& .MuiButton-startIcon': {
                margin: 0
              }
            }}
          >
            <RefreshIcon fontSize="small" />
          </Button>
        </Box>

        {/* Search Box - Full Width */}
        <Box sx={{ mb: 1 }}>
          <TextField
            size="small"
            label="Search files"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            fullWidth
            placeholder="Type to search files..."
          />
        </Box>


        {/* Sort and Filter Controls */}
        <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap', alignItems: 'center', py: 1 }}>
          <FormControl size="small" sx={{ minWidth: 80 }}>
            <InputLabel>Sort</InputLabel>
            <Select
              value={sortBy}
              label="Sort"
              onChange={(e) => setSortBy(e.target.value)}
            >
              <MenuItem value="name">Name</MenuItem>
              <MenuItem value="created_at">Date</MenuItem>
              <MenuItem value="size_bytes">Size</MenuItem>
            </Select>
          </FormControl>

          <FormControl size="small" sx={{ minWidth: 60 }}>
            <InputLabel>Order</InputLabel>
            <Select
              value={sortOrder}
              label="Order"
              onChange={(e) => setSortOrder(e.target.value as 'asc' | 'desc')}
            >
              <MenuItem value="asc">↑</MenuItem>
              <MenuItem value="desc">↓</MenuItem>
            </Select>
          </FormControl>

          <FormControl size="small" sx={{ minWidth: 60 }}>
            <InputLabel>Per page</InputLabel>
            <Select
              value={itemsPerPage}
              label="Per page"
              onChange={(e) => {
                setItemsPerPage(Number(e.target.value));
                setCurrentPage(1);
              }}
            >
              <MenuItem value={10}>10</MenuItem>
              <MenuItem value={15}>15</MenuItem>
              <MenuItem value={25}>25</MenuItem>
            </Select>
          </FormControl>
        </Box>

        {/* Breadcrumb Navigation */}
        <Box sx={{
          display: 'flex',
          alignItems: 'center',
          gap: 1,
          py: 1,
          px: 1,
          bgcolor: 'background.paper',
          borderBottom: '1px solid var(--color-divider)'
        }}>
          {breadcrumbs.map((breadcrumb, index) => (
            <React.Fragment key={`${breadcrumb.id}-${breadcrumb.name}`}>
              {index > 0 && (
                <Typography variant="caption" color="textSecondary">
                  /
                </Typography>
              )}
              <Button
                size="small"
                variant="text"
                onClick={() => navigateToBreadcrumb(breadcrumb)}
                sx={{
                  minWidth: 'auto',
                  textTransform: 'none',
                  color: index === breadcrumbs.length - 1 ? 'primary.main' : 'text.secondary',
                  fontWeight: index === breadcrumbs.length - 1 ? 600 : 400
                }}
              >
                {breadcrumb.name}
              </Button>
            </React.Fragment>
          ))}
        </Box>

        {/* File List with Fixed Height */}
        <Box sx={{
          border: '1px solid var(--color-divider)',
          borderRadius: '4px',
          height: 300, // Fixed height for main panel
          overflow: 'auto',
          flex: 1,
          // Hide scrollbar while keeping scroll functionality
          scrollbarWidth: 'none', // Firefox
          '&::-webkit-scrollbar': {
            display: 'none' // WebKit browsers (Chrome, Safari, Edge)
          }
        }}>
          {loading ? (
            <Box sx={{ p: 2, textAlign: 'center' }}>
              <CircularProgress size={20} />
              <Typography variant="caption" display="block" sx={{ mt: 1 }}>
                Loading files...
              </Typography>
            </Box>
          ) : sortedFiles.length === 0 ? (
            <Box sx={{ p: 2, textAlign: 'center' }}>
              <Typography variant="body2" color="textSecondary">
                {searchTerm ? 'No files found matching your search.' : 'No files found. Upload some files!'}
              </Typography>
            </Box>
          ) : (
            <List dense disablePadding>
              {sortedFiles.map((f, index) => (
                <React.Fragment key={f.id}>
                  {f.is_directory ? (
                    <ListItem
                      button
                      onClick={() => navigateToFolder(f)}
                      sx={{
                        cursor: 'pointer',
                        '&:hover': {
                          backgroundColor: 'action.hover'
                        }
                      }}
                      secondaryAction={
                        <>
                          <IconButton size="small" onClick={(e) => openMenu(e.currentTarget, f.id)} title="File actions">
                            <MoreVertIcon />
                          </IconButton>
                          <IconButton edge="end" size="small" onClick={() => handleDelete(f.id)} title="Delete file">
                            <DeleteIcon />
                          </IconButton>
                        </>
                      }
                    >
                      {iconForMime(f.mime_type, f.is_directory)}
                      <ListItemText
                        sx={{ ml: 1 }}
                        primary={
                          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                            <Typography variant="body2" sx={{ wordBreak: 'break-all' }}>
                              {f.name}
                            </Typography>
                            {f.is_directory && <Chip label="Dir" size="small" />}
                            {f.processing_status && f.processing_status !== 'uploaded' && (
                              <Chip
                                label={f.processing_status}
                                size="small"
                                color={getStatusColor(f.processing_status)}
                              />
                            )}
                          </Box>
                        }
                        secondary={
                          <Typography variant="caption" color="textSecondary">
                            {f.size_bytes ? formatFileSize(f.size_bytes) : 'Unknown size'}
                            {f.mime_type && ` • ${f.mime_type.split('/')[1]}`}
                          </Typography>
                        }
                      />
                    </ListItem>
                  ) : (
                    <ListItem
                      secondaryAction={
                        <>
                          <IconButton size="small" onClick={(e) => openMenu(e.currentTarget, f.id)} title="File actions">
                            <MoreVertIcon />
                          </IconButton>
                          <IconButton edge="end" size="small" onClick={() => handleDelete(f.id)} title="Delete file">
                            <DeleteIcon />
                          </IconButton>
                        </>
                      }
                    >
                      {iconForMime(f.mime_type, f.is_directory)}
                      <ListItemText
                        sx={{ ml: 1 }}
                        primary={
                          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                            <Typography variant="body2" sx={{ wordBreak: 'break-all' }}>
                              {f.name}
                            </Typography>
                            {f.is_directory && <Chip label="Dir" size="small" />}
                            {f.processing_status && f.processing_status !== 'uploaded' && (
                              <Chip
                                label={f.processing_status}
                                size="small"
                                color={getStatusColor(f.processing_status)}
                              />
                            )}
                          </Box>
                        }
                        secondary={
                          <Typography variant="caption" color="textSecondary">
                            {f.size_bytes ? formatFileSize(f.size_bytes) : 'Unknown size'}
                            {f.mime_type && ` • ${f.mime_type.split('/')[1]}`}
                          </Typography>
                        }
                      />
                    </ListItem>
                  )}
                  {/* Group separator between directories and files */}
                  {index === getGroupSeparatorIndex && needsGroupSeparator && (
                    <Divider sx={{ my: 1, borderStyle: 'dashed', borderColor: 'divider' }} />
                  )}
                  {/* Regular divider between items */}
                  {index < sortedFiles.length - 1 && index !== getGroupSeparatorIndex && <Divider />}
                </React.Fragment>
              ))}
            </List>
          )}
        </Box>

        {/* Pagination Controls */}
        {pagination && pagination.total_pages > 1 && (
          <Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
            <Stack spacing={1} alignItems="center">
              <Pagination
                count={pagination.total_pages}
                page={pagination.page}
                onChange={(event, value) => setCurrentPage(value)}
                color="primary"
                size="small"
                showFirstButton
                showLastButton
              />
              <Typography variant="caption" color="textSecondary">
                {pagination.offset + 1}-{Math.min(pagination.offset + pagination.per_page, pagination.total_count)} of {pagination.total_count}
              </Typography>
            </Stack>
          </Box>
        )}

        {/* Upload Controls */}
        <Box sx={{ mt: 2, display: 'flex', gap: 1, flexDirection: 'column' }}>
          {/* File Inputs */}
          <input
            id="cc-file-input"
            type="file"
            style={{ display: 'none' }}
            onChange={handleUpload}
            disabled={!selectedCabinet}
          />

          <input
            id="cc-directory-input"
            type="file"
            style={{ display: 'none' }}
            {...({ webkitdirectory: '' } as React.InputHTMLAttributes<HTMLInputElement>)}
            multiple
            onChange={handleDirectorySelect}
            disabled={!selectedCabinet}
          />

          {/* Upload Buttons */}
          <Box sx={{ display: 'flex', gap: 1 }}>
            <Button
              variant="outlined"
              startIcon={<UploadIcon />}
              onClick={() => selectedCabinet && document.getElementById('cc-file-input')?.click()}
              disabled={!selectedCabinet}
              fullWidth
            >
              Upload File
            </Button>

            <Button
              variant="outlined"
              startIcon={<FolderOpenIcon />}
              onClick={() => selectedCabinet && document.getElementById('cc-directory-input')?.click()}
              disabled={!selectedCabinet}
              fullWidth
            >
              Upload Folder
            </Button>
          </Box>

          {!selectedCabinet && (
            <Typography variant="caption" color="text.secondary" sx={{ textAlign: 'center', mt: 0.5 }}>
              Select a cabinet first to enable uploads
            </Typography>
          )}

          {selectedCabinet && !isDirectoryPickerSupported() && (
            <Typography variant="caption" color="warning.main" sx={{ textAlign: 'center', mt: 0.5 }}>
              ⚠️ Folder uploads may have limited support in this browser
            </Typography>
          )}
        </Box>

        <Menu
          anchorEl={menuAnchor?.el ?? null}
          open={!!menuAnchor}
          onClose={closeMenu}
          anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
          transformOrigin={{ vertical: 'top', horizontal: 'right' }}
        >
          <MenuItem onClick={() => { if (menuAnchor) { handleGenerateInitial(menuAnchor.fileId); closeMenu(); } }}>Generate initial artefacts</MenuItem>
          <MenuItem onClick={goToAIContent}>Open AI content</MenuItem>
        </Menu>

        {artefacts.length > 0 && (
          <>
            <Divider />
            <List dense sx={{
              border: '1px solid var(--color-divider)',
              borderRadius: '4px',
              overflow: 'auto',
              maxHeight: 160,
              // Hide scrollbar while keeping scroll functionality
              scrollbarWidth: 'none', // Firefox
              '&::-webkit-scrollbar': {
                display: 'none' // WebKit browsers (Chrome, Safari, Edge)
              }
            }}>
              {artefacts.map(a => (
                <ListItem key={a.id}>
                  <ListItemText primary={a.type} secondary={a.rel_path} />
                </ListItem>
              ))}
            </List>
          </>
        )}

        {/* Directory Upload Dialog */}
        <Dialog
          open={showDirectoryDialog}
          onClose={() => !isDirectoryUploading && setShowDirectoryDialog(false)}
          maxWidth="md"
          fullWidth
        >
          <DialogTitle>
            <Box display="flex" alignItems="center" gap={1}>
              <FolderOpenIcon />
              Directory Upload
              {isDirectoryUploading && <LinearProgress sx={{ flexGrow: 1, ml: 2 }} />}
            </Box>
          </DialogTitle>

          <DialogContent>
            {directoryStats && (
              <Alert severity="info" sx={{ mb: 2 }}>
                <Typography variant="body2">
                  <strong>{directoryStats.fileCount} files</strong> in{' '}
                  <strong>{directoryStats.directoryCount} folders</strong><br />
                  Total size: <strong>{directoryStats.formattedSize}</strong>
                </Typography>
              </Alert>
            )}

            <Paper variant="outlined" sx={{
              p: 2,
              maxHeight: 200,
              overflow: 'auto',
              // Hide scrollbar while keeping scroll functionality
              scrollbarWidth: 'none', // Firefox
              '&::-webkit-scrollbar': {
                display: 'none' // WebKit browsers (Chrome, Safari, Edge)
              }
            }}>
              <Typography variant="body2" color="textSecondary" gutterBottom>
                Files to upload:
              </Typography>
              {selectedFiles.map((file, i) => (
                <Box key={i} sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', py: 0.5 }}>
                  <Typography variant="body2" sx={{ flex: 1, mr: 2 }} noWrap>
                    {file.relativePath}
                  </Typography>
                  <Typography variant="caption" color="textSecondary">
                    {formatFileSize(file.size)}
                  </Typography>
                </Box>
              ))}
            </Paper>
          </DialogContent>

          <DialogActions>
            <Button onClick={() => setShowDirectoryDialog(false)} disabled={isDirectoryUploading}>
              Cancel
            </Button>
            <Button
              onClick={startDirectoryUpload}
              variant="contained"
              disabled={isDirectoryUploading || selectedFiles.length === 0}
            >
              {isDirectoryUploading ? 'Uploading...' : 'Upload Directory'}
            </Button>
          </DialogActions>
        </Dialog>
      </Container>
    </ThemeProvider>
  );
};


