import Box from '@mui/material/Box';
import Table from '@mui/material/Table';
import Tooltip from '@mui/material/Tooltip';
import { useTheme } from '@mui/material/styles';
import TableBody from '@mui/material/TableBody';
import IconButton from '@mui/material/IconButton';
import TableContainer from '@mui/material/TableContainer';
import TableCell, { tableCellClasses } from '@mui/material/TableCell';
import { tablePaginationClasses } from '@mui/material/TablePagination';

import Iconify from '@/shared/components/iconify';
import {
  TableProps,
  TableNoData,
  TableHeadCustom,
  TableSelectedAction,
  TablePaginationCustom,
} from '@/shared/components/table';

import { IFile } from '@/shared/types/file';

import FileManagerTableRow from './file-manager-table-row';
import { TableRow, Typography } from '@mui/material';

// ----------------------------------------------------------------------

const TABLE_HEAD = [
  { id: 'name', label: 'Name' },
  { id: 'size', label: 'Size', width: 120 },
  { id: 'type', label: 'Type', width: 120 },
  { id: 'createdAt', label: 'Created', width: 140 },
  { id: 'modifiedAt', label: 'Modified', width: 140 },
  { id: 'Owner', label: 'Owner', width: 160 },
  { id: '', width: 88 },
];

// ----------------------------------------------------------------------

type Props = {
  table: TableProps;
  notFound: boolean;
  section: 'PERSONAL' | 'SHARED' | 'SHARED_WITH_ME';
  dataFiltered: IFile[];
  onCopyLink?:(uniqueId :string)=>Promise<void>;
  onOpenConfirm: VoidFunction;
  onCreateCopy:(uniqueId: string, destinationPath: string) => Promise<void>;
  onDeleteRow: (id: string) => void;
  onToggleFavorite: (uniqueId: string, isFavorited: boolean) => Promise<boolean>;
  onRefresh?: VoidFunction;
  availableFolders?: Array<{ name: string; path: string }>;
  onOpenFolder? : (folderId: number, folderName: string) => void;
};

export default function FileManagerTable({
  table,
  notFound,
  onDeleteRow,
  dataFiltered,
  onOpenConfirm,
  onToggleFavorite,
  onRefresh,
  onCreateCopy,
  section,
  availableFolders,
  onOpenFolder,
}: Props) {
  const theme = useTheme();

  const {
    dense,
    page,
    order,
    orderBy,
    rowsPerPage,
    selected,
    onSelectRow,
    onSelectAllRows,
    onSort,
    onChangeDense,
    onChangePage,
    onChangeRowsPerPage,
  } = table;

  const handleConfirmDelete = () => {
    if (selected.length > 0) {
      onOpenConfirm?.();
    }
  };

  return (
    <>
      <Box sx={{ position: 'relative', m: theme.spacing(-2, -3, -3, -3) }}>
        <TableSelectedAction
          dense={dense}
          numSelected={selected.length}
          rowCount={dataFiltered.length}
          onSelectAllRows={(checked) =>
            onSelectAllRows(
              checked,
              dataFiltered.map((row) => row.id)
            )
          }
          action={
            <>
              <Tooltip title="Share">
                <IconButton color="primary">
                  <Iconify icon="solar:share-bold" sx={{ width: 20, height: 20 }} />
                </IconButton>
              </Tooltip>
              <Tooltip title="Download">
                <IconButton color="primary">
                  <Iconify icon="heroicons-outline:download" sx={{ width: 20, height: 20 }} />
                </IconButton>
              </Tooltip>
              <Tooltip title="Move">
                <IconButton color="primary">
                  <Iconify icon="material-symbols:drive-file-move-outline" sx={{ width: 20, height: 20 }} />
                </IconButton>
              </Tooltip>
              <Tooltip title="Delete">
                <IconButton color="primary" onClick={handleConfirmDelete}>
                  <Iconify icon="wpf:delete" sx={{ width: 20, height: 20 }} />
                </IconButton>
              </Tooltip>
            </>
          }
          sx={{
            pl: 1,
            pr: 2,
            top: 16,
            left: 24,
            right: 24,
            width: 'auto',
            borderRadius: 1.5,
          }}
        />

        <TableContainer sx={{ p: theme.spacing(0, 3, 3, 3) }}>
          <Table
            size={dense ? 'small' : 'medium'}
            sx={{
              minWidth: 960,
              borderCollapse: 'separate',
              borderSpacing: '0 16px',
            }}
          >
            <TableHeadCustom
              order={order}
              orderBy={orderBy}
              headLabel={TABLE_HEAD}
              rowCount={dataFiltered.length}
              numSelected={selected.length}
              onSort={onSort}
              onSelectAllRows={(checked) =>
                onSelectAllRows(
                  checked,
                  dataFiltered.map((row) => row.id)
                )
              }
              sx={{
                [`& .${tableCellClasses.head}`]: {
                  '&:first-of-type': {
                    borderTopLeftRadius: 12,
                    borderBottomLeftRadius: 12,
                  },
                  '&:last-of-type': {
                    borderTopRightRadius: 12,
                    borderBottomRightRadius: 12,
                  },
                },
              }}
            />

            <TableBody>
              {dataFiltered
                .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                .map((row) => (
                  <FileManagerTableRow
                  availableFolders={availableFolders}
                    section={section}
                    key={row.id}
                    row={row}
                    onCreateCopy={onCreateCopy}
                    selected={selected.includes(row.id)}
                    onSelectRow={() => onSelectRow(row.id)}
                    onDeleteRow={() => onDeleteRow(row.id)}
                    onToggleFavorite={onToggleFavorite}
                    onOpenFolder={onOpenFolder}
                    onRefresh={onRefresh}
                  />
                ))}

              
{notFound && (
                <TableRow>
                  <TableCell colSpan={TABLE_HEAD.length + 1}>
                    <TableNoData 
                      notFound={notFound}
                      sx={{
                        m: -2,
                        borderRadius: 1.5,
                        border: `dashed 1px ${theme.palette.divider}`,
                        p: 3,
                        textAlign: 'center',
                      }}
                    />
                    <Box sx={{ py: 3 }}>
                      <Box
                        component="img"
                        src="/assets/illustrations/illustration_empty_content.svg"
                        sx={{ 
                          height: 240,
                          mx: 'auto',
                          display: 'block',
                        }}
                      />
                      <Typography variant="h6" gutterBottom align="center">
                        No Data Found
                      </Typography>
                      <Typography variant="body2" align="center" sx={{ color: 'text.secondary' }}>
                        No records found. Try adjusting your search or filters.
                      </Typography>
                    </Box>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
      </Box>

      <TablePaginationCustom
        count={dataFiltered.length}
        page={page}
        rowsPerPage={rowsPerPage}
        onPageChange={onChangePage}
        onRowsPerPageChange={onChangeRowsPerPage}
        dense={dense}
        onChangeDense={onChangeDense}
        sx={{
          [`& .${tablePaginationClasses.toolbar}`]: {
            borderTopColor: 'transparent',
          },
          marginTop: 1,
        }}
      />
    </>
  );
}