'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 SharedFilesView() {
  const { enqueueSnackbar } = useSnackbar();
  const table = useTable({ defaultRowsPerPage: 10 });
  const settings = useSettingsContext();
  const openDateRange = useBoolean();
  const confirm = useBoolean();
  const popover = usePopover();
  const newFolder = useBoolean();
  const upload = useBoolean();
  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 [folderName, setFolderName] = useState('');

  const { documents, loading, error, refetch, toggleFavorite, notFound } = useDocuments('SHARED');
  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',
        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 handleChangeFolderName = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
    setFolderName(event.target.value);
  }, []);

  const handleCreateFolder = useCallback(async ( folderName: string) => {
    try {
      await fileManagerApi.createSharedFolder(
        folderName,
        currentFolder?.id || null,
    
      );
      newFolder.onFalse();
      setFolderName('');
      refetch();
      enqueueSnackbar('Shared folder created successfully');
    } catch (error) {
      console.error(error);
      enqueueSnackbar('Error creating shared folder', { variant: 'error' });
    }
  }, [folderName, currentFolder, newFolder, refetch, enqueueSnackbar]);

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

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

  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 dateError = isAfter(filters.startDate, filters.endDate);

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

  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 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 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 shared files"
          description="You haven't shared any files yet"
          filled
          sx={{ py: 10 }}
        />
      );
    }

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

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

  const renderMenuItems = (
    <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" />
       create folder
      </MenuItem>

      <MenuItem onClick={upload.onTrue}>
        <Iconify icon="tabler:file-upload" />
      upload File
      </MenuItem>
    </CustomPopover>
  );

  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>
  );

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <Container maxWidth={settings.themeStretch ? false : 'lg'}>
        {currentFolder ? (
          <FolderContentsView
            folderId={currentFolder.id}
            folderName={currentFolder.name}
            onBack={handleBackToRoot}
            onOpenFolder={handleOpenFolder}
            section="SHARED"
          />
        ) : (
          <>
            <Stack direction="row" alignItems="center" justifyContent="space-between">
              <Typography variant="h4">Shared Files</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 || null}
            </Stack>

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

            {renderContent()}

            <FileManagerNewFolderDialog 
              open={upload.value} 
              onRefresh={refetch} 
              section='shared'
              onClose={upload.onFalse} 
            />
            <FileManagerNewFolderDialog
              open={newFolder.value}
              onClose={newFolder.onFalse}
              title="New Shared Folder"
              onCreate={handleCreateFolder}
              folderName={folderName}
              section="shared"
              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,
}: {
  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;
}