'use client';

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

import { useBoolean } from '@/hooks/use-boolean';
import { useDocuments } from '@/hooks/use-list-document';
import { useSettingsContext } from '@/shared/components/settings';
import { useTable, getComparator } from '@/shared/components/table';
import { useSnackbar } from '@/shared/components/snackbar';

import Iconify from '@/shared/components/iconify';
import EmptyContent from '@/shared/components/empty-content';
import { ConfirmDialog } from '@/shared/components/custom-dialog';
import { fileFormat } from '@/shared/components/file-thumbnail';

import { IFile, IFileFilters, IFileFilterValue } from '@/shared/types/file';
import { fileManagerApi } from '@/shared/api/file-manager';
import FileManagerTable from '../file-manager-table';
import FolderContentsView from './folder-content-view';
import FileManagerGridView from '../file-manager-grid-view';
import FileManagerFilters from '../file-manager-filters';



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

export default function FileManagerSharedWithMeView() {
  const { enqueueSnackbar } = useSnackbar();
  const settings = useSettingsContext();
  const table = useTable({ defaultRowsPerPage: 10 });
  const confirm = useBoolean();
  const [view, setView] = useState('list');
  const [filters, setFilters] = useState(defaultFilters);
  const [currentFolder, setCurrentFolder] = useState<{id: number; name: string} | null>(null);

  const { documents, loading, error, refetch, toggleFavorite, notFound } = useDocuments('SHARED_WITH_ME');
  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.isFavorited || false,
        shared: doc.shared || null,
        createdAt: doc.createdAt || null,
        modifiedAt: doc.modifiedAt || doc.updatedAt || new Date().toISOString(),
        visibility: doc.visibility || 'SHARED_WITH_ME',
        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 dataFiltered = applyFilter({
    inputData: tableData,
    comparator: getComparator(table.order, table.orderBy),
    filters,
  });

  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 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');
        refetch();
      } catch (error) {
        console.error(error);
        enqueueSnackbar('Error deleting document', { variant: 'error' });
      }
    },
    [dataFiltered, enqueueSnackbar, refetch]
  );

  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 renderContent = () => {
    if (loading) {
      return (
        <Stack alignItems="center" justifyContent="center" sx={{ py: 10 }}>
          <CircularProgress />
        </Stack>
      );
    }

    if (error) {
      return (
        <EmptyContent
          title="Error loading documents"
          description="There was an error loading the shared documents"
          filled
          sx={{ py: 10 }}
        />
      );
    }

    if (!tableData || tableData.length === 0) {
      return (
        <EmptyContent
          title="No shared documents"
          description="No documents have been shared with you yet"
          filled
          sx={{ py: 10 }}
        />
      );
    }

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

  return (
    <Container maxWidth={settings.themeStretch ? false : 'lg'}>
      {currentFolder ? (
        <FolderContentsView
          folderId={currentFolder.id}
          folderName={currentFolder.name}
          onBack={handleBackToRoot}
          onOpenFolder={handleOpenFolder}
          section="SHARED_WITH_ME"
        />
      ) : (
        <>
          <Stack 
            direction="row" 
            alignItems="center" 
            justifyContent="space-between"
            sx={{ mb: 3 }}
          >
            <Typography variant="h4">Shared With Me</Typography>

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

          <Stack spacing={2.5}>
           
            {renderContent()}
          </Stack>

          <ConfirmDialog
            open={confirm.value}
            onClose={confirm.onFalse}
            title="Delete"
            content="Are you sure you want to delete this item?"
            action={
              <Button
                variant="contained"
                color="error"
                onClick={() => {
                  handleDeleteItem(table.selected[0]);
                  confirm.onFalse();
                }}
              >
                Delete
              </Button>
            }
          />
        </>
      )}
    </Container>
  );
}

function applyFilter({
  inputData,
  comparator,
  filters,
}: {
  inputData: IFile[];
  comparator: (a: any, b: any) => number;
  filters: IFileFilters;
}) {
  const { name, type } = 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) => type.includes(fileFormat(file.name)));
  }

  return inputData;
}