// components/file-manager/personal-files-view.tsx
'use client';

import { useState, useCallback, useEffect, useMemo } from 'react';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import Container from '@mui/material/Container';
import Typography from '@mui/material/Typography';
import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import { Chip, Divider, Tooltip, CircularProgress } from '@mui/material';
import MenuItem from '@mui/material/MenuItem';

import { useBoolean } from '@/hooks/use-boolean';
import { useDocuments } from '@/hooks/use-list-document';
import { isAfter, isBetween } from '@/utils/format-time';
import { FILE_TYPE_OPTIONS } from '@/shared/_mock';

import Iconify from '@/shared/components/iconify';
import { useSnackbar } from '@/shared/components/snackbar';
import EmptyContent from '@/shared/components/empty-content';
import { fileFormat } from '@/shared/components/file-thumbnail';
import { ConfirmDialog } from '@/shared/components/custom-dialog';
import { useSettingsContext } from '@/shared/components/settings';
import { useTable, getComparator } from '@/shared/components/table';
import CustomPopover, { usePopover } from '@/shared/components/custom-popover';

import { IFile, IFileFilters, IFileFilterValue } from '@/shared/types/file';
import { AccessLevel, fileManagerApi } from '@/shared/api/file-manager';

import FileManagerTable from '../file-manager-table';
import FileManagerFilters from '../file-manager-filters';
import FileManagerGridView from '../file-manager-grid-view';
import FileManagerFiltersResult from '../file-manager-filters-result';
import FileManagerNewFolderDialog from '../file-manager-new-folder-dialog';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import FolderContentsView from './folder-content-view';

const defaultFilters: IFileFilters = {
  name: '',
  type: [],
  startDate: null,
  endDate: null,
};

export default function PersonalFilesView() {
  const { enqueueSnackbar } = useSnackbar();
  const table = useTable({ defaultRowsPerPage: 10 });
  const settings = useSettingsContext();
  const openDateRange = useBoolean();
  const confirm = useBoolean();
  const upload = useBoolean();
  const newFolder = useBoolean();
  const [folderName, setFolderName] = useState('');
  const popover = usePopover();
  const [view, setView] = useState('list');
  const [filters, setFilters] = useState(defaultFilters);
  const [showFavorites, setShowFavorites] = useState(false);
  const [currentFolder, setCurrentFolder] = useState<{id: number; name: string} | null>(null);

  const { documents, loading, error, refetch, toggleFavorite, notFound } = useDocuments('PERSONAL');
  const [tableData, setTableData] = useState<IFile[]>([]);
  const availableFolders = useMemo(() => 
    tableData
      .filter(doc => 
        doc.type === 'folder'
      )
      .map(folder => ({ 
        name: folder.name.trim(), 
        path: folder.path?.trim() || '' 
      })), 
    [tableData]
  );
  useEffect(() => {
    if (documents) {
      const formattedData: IFile[] = documents.map((doc: any) => ({
        id: doc.id,
        name: doc.name,
        size: doc.size || null,
        type: doc.type || 'file',
        url: doc.url || '',
        tags: doc.tags || [],
        isFavorited: doc.favorited || false,
        shared: doc.shared || null,
        createdAt: doc.createdAt || null,
        modifiedAt: doc.modifiedAt || doc.updatedAt || new Date().toISOString(),
        visibility: doc.visibility || 'PRIVATE',
        permissions: doc.permissions || 'READ',
        path: doc.path || '',
        ownerFullName: doc.ownerFullName || 'Unknown User',
        userOwner: doc.userOwner || 0,
        uniqueId: doc.uniqueId || doc.id,
        agency: doc.agency || 0,
        childrenFiles: doc.childrenFiles || [],
        childrenFolders: doc.childrenFolders || [],
        parentFolder: doc.parentFolder || null,
        ...(doc.type === 'folder' && { totalFiles: doc.totalFiles || 0 }),
      }));
      setTableData(formattedData);
    }
  }, [documents]);

  const handleOpenFolder = useCallback((folderId: number, folderName: string) => {
    setCurrentFolder({ id: folderId, name: folderName });
  }, []);

  const handleBackToRoot = useCallback(() => {
    setCurrentFolder(null);
  }, []);

  const dateError = isAfter(filters.startDate, filters.endDate);

  const dataFiltered = applyFilter({
    inputData: tableData,
    comparator: getComparator(table.order, table.orderBy),
    filters,
    dateError,
  });

  const dataInPage = dataFiltered.slice(
    table.page * table.rowsPerPage,
    table.page * table.rowsPerPage + table.rowsPerPage
  );

  const canReset = !!filters.name || !!filters.type.length || (!!filters.startDate && !!filters.endDate);

  const handleToggleFavoriteItem = useCallback(async (uniqueId: string, isFavorited: boolean): Promise<boolean> => {
    try {
      await toggleFavorite(uniqueId, isFavorited);
      refetch(); 
      return true;
    } catch (error) {
      console.error('Error toggling favorite:', error);
      enqueueSnackbar('Error updating favorite status', { variant: 'error' });
      return false;
    }
  }, [toggleFavorite, refetch, enqueueSnackbar]);

  const handleFiltersFavorited = useCallback(() => {
    return showFavorites ? dataFiltered.filter((file) => file.isFavorited) : dataFiltered;
  }, [showFavorites, dataFiltered]);

  const handleChangeFolderName = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
    setFolderName(event.target.value);
  }, []);

  const handleChangeView = useCallback(
    (event: React.MouseEvent<HTMLElement>, newView: string | null) => {
      if (newView !== null) {
        setView(newView);
      }
    },
    []
  );

  const handleFilters = useCallback(
    (name: string, value: IFileFilterValue) => {
      table.onResetPage();
      setFilters((prevState) => ({
        ...prevState,
        [name]: value,
      }));
    },
    [table]
  );

  const handleToggleFavorite = useCallback(() => {
    setShowFavorites((prev) => !prev);
  }, []);

  const handleResetFilters = useCallback(() => {
    setFilters(defaultFilters);
  }, []);
  const handleDeleteItem = useCallback(
    async (id: string) => {
      try {
        const itemToDelete = dataFiltered.find(item => item.id === id);
        if (!itemToDelete?.path) {
          throw new Error('Document path is missing');
        }
        
        await fileManagerApi.deleteDocuments(itemToDelete.userOwner, [itemToDelete.path]);
        enqueueSnackbar('Document deleted successfully');
        table.onUpdatePageDeleteRow(dataInPage.length);
        refetch();
      } catch (error) {
        console.error(error);
        enqueueSnackbar('Error deleting document', { variant: 'error' });
      }
    },
    [dataFiltered, dataInPage.length, enqueueSnackbar, table, refetch]
  );

  const handleDeleteItems = useCallback(async () => {
    try {
      const itemsToDelete = dataFiltered.filter(item => table.selected.includes(item.id));
      const paths = itemsToDelete
        .filter(item => item.path)
        .map(item => item.path as string);
      
      if (paths.length === 0) {
        throw new Error('No valid paths to delete');
      }

      await fileManagerApi.deleteDocuments(itemsToDelete[0].userOwner, paths);
      enqueueSnackbar('Documents deleted successfully');
      table.onUpdatePageDeleteRows({
        totalRowsInPage: dataInPage.length,
        totalRowsFiltered: dataFiltered.length,
      });
      refetch();
      confirm.onFalse();
    } catch (error) {
      console.error(error);
      enqueueSnackbar('Error deleting documents', { variant: 'error' });
    }
  }, [dataFiltered, dataInPage.length, table, enqueueSnackbar, refetch, confirm]);

  const handleCreateFolder = useCallback(async () => {
    try {
      await fileManagerApi.createPrivateFolder(folderName);
      newFolder.onFalse();
      setFolderName('');
      refetch();
      enqueueSnackbar('Folder created successfully');
    } catch (error) {
      console.error(error);
      enqueueSnackbar('Error creating folder', { variant: 'error' });
    }
  }, [folderName, newFolder, refetch, enqueueSnackbar]);

  const handleCreateCopy = useCallback(async (uniqueId:string, destinationPath:string) => {
    try {
      await fileManagerApi.createCopy(uniqueId, destinationPath);
      enqueueSnackbar('Copy created successfully', { variant: 'success' });
      refetch(); 
    } catch (error) {
      console.error('Error creating copy:', error);
      enqueueSnackbar('Error creating copy', { variant: 'error' });
    }
  }, [enqueueSnackbar, refetch]);


  const renderMenuItems = popover.open ? (
    <CustomPopover
      open={popover.open}
      onClick={popover.onClose}
      onClose={popover.onClose}
      arrow="top-center"
      sx={{ width: 160, marginTop: 2 }}
    >
      <MenuItem onClick={newFolder.onTrue}>
        <Iconify icon="pajamas:folder-new" />
        New folder
      </MenuItem>

      <Divider sx={{ borderStyle: 'dashed' }} />

      <MenuItem onClick={upload.onTrue}>
        <Iconify icon="tabler:file-upload" />
        Upload file
      </MenuItem>
    </CustomPopover>
  ) : (
    <Stack sx={{ display: 'none' }}>
      <MenuItem disabled>No actions available</MenuItem>
    </Stack>
  );

  const renderFilters = (
    <Stack
      spacing={2}
      direction={{ xs: 'column', md: 'row' }}
      alignItems={{ xs: 'flex-end', md: 'center' }}
    >
      <FileManagerFilters
        openDateRange={openDateRange.value}
        onCloseDateRange={openDateRange.onFalse}
        onOpenDateRange={openDateRange.onTrue}
        filters={filters}
        onFilters={handleFilters}
        dateError={dateError}
        typeOptions={FILE_TYPE_OPTIONS}
      />

      <ToggleButtonGroup size="small" value={view} exclusive onChange={handleChangeView}>
        <Tooltip title="List view" arrow>
          <ToggleButton value="list">
            <Iconify icon="solar:list-bold" />
          </ToggleButton>
        </Tooltip>
        <Tooltip title="Grid view" arrow>
          <ToggleButton value="grid">
            <Iconify icon="mingcute:dot-grid-fill" />
          </ToggleButton>
        </Tooltip>
      </ToggleButtonGroup>
    </Stack>
  );

  const renderContent = () => {
    if (loading) {
      return (
        <Stack alignItems="center" justifyContent="center" sx={{ py: 10 }}>
          <CircularProgress />
        </Stack>
      );
    }

    if (error) {
      return (
        <EmptyContent
          description="No data available"
          filled
          sx={{ py: 10 }}
        />
      );
    }

    if (!tableData || tableData.length === 0) {
      return (
        <EmptyContent
          title="No documents found"
          description="Start by uploading a document or creating a new folder"
          filled
          sx={{ py: 10 }}
        />
      );
    }

    if (notFound) {
      return (
        <EmptyContent
          title="No matching documents"
          description="Try adjusting your search or filter to find what you're looking for"
          filled
          sx={{ py: 10 }}
        />
      );
    }

    return (
      <>
        {view === 'list' ? (
          <FileManagerTable
            availableFolders={availableFolders}
            table={table}
            dataFiltered={handleFiltersFavorited()}
            onDeleteRow={handleDeleteItem}
            onRefresh={refetch}
            notFound={notFound}
            onOpenConfirm={confirm.onTrue}
            onToggleFavorite={toggleFavorite}
            onOpenFolder={handleOpenFolder}
            onCreateCopy={handleCreateCopy} 
            section={'PERSONAL'}          />
        ) : (
          <FileManagerGridView
            table={table}
            dataFiltered={handleFiltersFavorited()}
            onDeleteItem={handleDeleteItem}
            onRefresh={refetch}
            availableFolders={availableFolders}
            onToggleFavorite={toggleFavorite}
            onOpenConfirm={confirm.onTrue}
            notFound={notFound}
            onOpenFolder={handleOpenFolder}
          />
        )}
      </>
    );
  };

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <Container maxWidth={settings.themeStretch ? false : 'lg'}>
        {currentFolder ? (
          <FolderContentsView
            folderId={currentFolder.id}
            folderName={currentFolder.name}
            onBack={handleBackToRoot}
            onOpenFolder={handleOpenFolder}
            section="PERSONAL"
          />
        ) : (
          <>
            <Stack direction="row" alignItems="center" justifyContent="space-between">
              <Typography variant="h4">File Manager</Typography>

              <Stack direction="row" spacing={1} justifyContent="flex-end">
                <Chip
                  label="New"
                  sx={{
                    backgroundColor: '#144dd5',
                    '&:hover': {
                      backgroundColor: '#144dd5',
                    },
                
                    textTransform: 'none',
                    px: 2,
                    marginLeft: 2,
                  }}
                  icon={<Iconify icon="typcn:plus" sx={{ width: 25, height: 25 }} />}
                  onClick={popover.onOpen}
                />
                <Divider orientation="vertical" flexItem />
                <Tooltip title="Favorites" arrow>
                  <Iconify
                    icon={showFavorites ? 'mdi:favorite-box' : 'mdi:favorite-box-outline'}
                    color={'#FFAB00'}
                    sx={{ width: 35, height: 35 }}
                    onClick={handleToggleFavorite}
                  />
                </Tooltip>
              </Stack>
              {renderMenuItems}
            </Stack>

            <Stack
              spacing={2.5}
              sx={{
                my: { xs: 3, md: 5 },
              }}
            >
             {renderFilters}
             {canReset && (
  <FileManagerFiltersResult
    filters={filters}
    onResetFilters={handleResetFilters}
    canReset={canReset}
    onFilters={handleFilters}
    results={dataFiltered.length}
  />
) || null}
            </Stack>

            {renderContent()}

            <FileManagerNewFolderDialog 
              open={upload.value} 
              onRefresh={refetch} 
              onClose={upload.onFalse} 
            />

            <FileManagerNewFolderDialog
              open={newFolder.value}
              onClose={newFolder.onFalse}
              title="New Folder"
              onCreate={handleCreateFolder}
              folderName={folderName}
              section="personal"
              onChangeFolderName={handleChangeFolderName}
            />

            <ConfirmDialog
              open={confirm.value}
              onClose={confirm.onFalse}
              title="Delete"
              content={
                <>
                  Are you sure want to delete <strong> {table.selected.length} </strong> items?
                </>
              }
              action={
                <Button
                  variant="contained"
                  color="error"
                  onClick={handleDeleteItems}
                >
                  Delete
                </Button>
              }
            />
          </>
        )}
      </Container>
    </LocalizationProvider>
  );
}
function applyFilter({
  inputData,
  comparator,
  filters,
  dateError,
}: {
  inputData: IFile[];
  comparator: (a: any, b: any) => number;
  filters: IFileFilters;
  dateError: boolean;
}) {
  const { name, type, startDate, endDate } = filters;

  const stabilizedThis = inputData.map((el, index) => [el, index] as const);

  stabilizedThis.sort((a, b) => {
    const order = comparator(a[0], b[0]);
    if (order !== 0) return order;
    return a[1] - b[1];
  });

  inputData = stabilizedThis.map((el) => el[0]);

  if (name) {
    inputData = inputData.filter(
      (file) => file.name.toLowerCase().indexOf(name.toLowerCase()) !== -1
    );
  }

  if (type.length) {
    inputData = inputData.filter((file) => {
      // Gestion spéciale pour les dossiers
      if (file.type === 'folder') {
        return type.includes('folder');
      }

      // Pour les fichiers, utiliser fileFormat pour obtenir le type
      const fileType = fileFormat(file.name);
      
      // Mapper les types pour correspondre aux options de filtre
      const typeMap: { [key: string]: string } = {
        txt: 'text',
        zip: 'archive',
        audio: 'audio',
        image: 'image',
        video: 'video',
        word: 'word',
        excel: 'excel',
        powerpoint: 'powerpoint',
        pdf: 'pdf',
        photoshop: 'photoshop',
        illustrator: 'illustrator'
      };

      const normalizedType = typeMap[fileType] || 'other';
      return type.includes(normalizedType.toLowerCase());
    });
  }

  if (!dateError) {
    if (startDate && endDate) {
      inputData = inputData.filter((file) => {
        const fileDate = file.createdAt ? new Date(file.createdAt) : null;
        return fileDate ? isBetween(fileDate, startDate, endDate) : false;
      });
    }
  }

  return inputData;
}

 