'use client';

import { useCallback, useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { 
  Container, 
  Typography, 
  CircularProgress, 
  Stack, 
  Button,
  Card,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  IconButton,
  Tooltip,
  MenuItem,
  Divider,
  Box, 
  Breadcrumbs,
  Link
} from '@mui/material';

import { AccessLevel, fileManagerApi } from '@/shared/api/file-manager';
import { useSnackbar } from '@/shared/components/snackbar';
import EmptyContent from '@/shared/components/empty-content';
import { paths } from '@/routes/paths';
import Iconify from '@/shared/components/iconify';
import { useBoolean } from '@/hooks/use-boolean';
import { usePopover } from '@/shared/components/custom-popover';
import CustomPopover from '@/shared/components/custom-popover';
import FileThumbnail from '@/shared/components/file-thumbnail';

import ImagePlayer from '@/shared/components/players/image-player';
import VideoPlayer from '@/shared/components/players/video-player';
import AudioPlayer from '@/shared/components/players/audio-player';
import DocPlayer from '@/shared/components/players/doc-player';



import { IFile } from '@/shared/types/file';
import { getFileFormat, getFileThumb } from '@/utils/format-type';
import FileManagerFileDetails from '../file-manager-file-details';
import { fData } from '@/utils/format-number';
import { fDateTime } from '@/utils/format-time';
import { getUserByEmail } from '@/shared/api/user';
import FileManagerShareDialog from '../file-manager-share-dialog';
import { usePermissions } from '@/hooks/use-permissions';


export default function SharedDocumentView({ params }: { params: { uniqueId: string } }) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { enqueueSnackbar } = useSnackbar();
  const [selectedItem, setSelectedItem] = useState<IFile | null>(null);
  const [loading, setLoading] = useState(true);

  const [error, setError] = useState<string | null>(null);
  const [folderContents, setFolderContents] = useState<IFile[]>([]);
  const [document, setDocument] = useState<IFile | null>(null);
  const EXTENSIONS = ['mp4', 'webm', 'ogv', 'gif', 'jpg', 'jpeg', 'svg', 'png', 'mp3', 'wav', 'ogg', 'pdf'];
  const preview = useBoolean();
  const popover = usePopover();
  const details = useBoolean();
  const edit = useBoolean();
const share = useBoolean();
const confirm = useBoolean();
const handleToggleFavorite = async (uniqueId: string, isFavorited: boolean): Promise<boolean> => {
  try {
    if (isFavorited) {
      await fileManagerApi.unmarkAsFavorite(uniqueId);
    } else {
      await fileManagerApi.markAsFavorite(uniqueId);
    }
    
    const token = searchParams.get('token');
    if (token) {
      const updatedDoc = await fileManagerApi.getSharedDocument(params.uniqueId, token);
      setDocument(updatedDoc);
    }
    
    enqueueSnackbar(
      isFavorited ? 'Removed from favorites' : 'Added to favorites',
      { variant: 'success' }
    );
    return true;
  } catch (error) {
    console.error('Error toggling favorite:', error);
    enqueueSnackbar('Error updating favorite status', { variant: 'error' });
    return false;
  }
};
  useEffect(() => {
    const fetchSharedDocument = async () => {
      try {
        const token = searchParams.get('token');
        
        if (!token) {
          setError('Invalid sharing link: No access token provided');
          return;
        }

        const response = await fileManagerApi.getSharedDocument(params.uniqueId, token);
        setDocument(response);
      } catch (err: any) {
        console.error('Error fetching shared document:', err);
        setError(err.message || 'Error accessing shared document');
        enqueueSnackbar('Error accessing shared document', { variant: 'error' });
      } finally {
        setLoading(false);
      }
    };

    fetchSharedDocument();
  }, [params.uniqueId, searchParams, enqueueSnackbar]);

  const handleBackToFileManager = () => {
    router.push(paths.dashboard.filemanager.root);
  };
 
  const handleDownload = async (file: IFile) => {
    try {
      await fileManagerApi.downloadElement(file.uniqueId, file.name);
      enqueueSnackbar('Download started successfully', { variant: 'success' });
    } catch (error) {
      console.error('Error downloading file:', error);
      enqueueSnackbar('Error downloading file', { variant: 'error' });
    }
  };
  const [currentFolder, setCurrentFolder] = useState<{id: number; name: string} | null>(null);

  const handleOpenFolder = useCallback(async (folderId: number, folderName: string) => {
    try {
      setLoading(true);
      const folderContents = await fileManagerApi.getFolderContents(folderId);
      setDocument(folderContents); 
      setFolderContents(folderContents);
      setCurrentFolder({ id: folderId, name: folderName });
    } catch (error) {
      console.error('Error opening folder:', error);
      enqueueSnackbar('Error opening folder', { variant: 'error' });
    } finally {
      setLoading(false);
    }
  }, [enqueueSnackbar]);

  const handleRename = async (newName: string) => {
    try {
      await fileManagerApi.renameDocument(document?.uniqueId || '', newName);
      enqueueSnackbar('Document renamed successfully', { variant: 'success' });
      // Rafraîchir les données
      window.location.reload();
    } catch (error) {
      console.error('Error renaming document:', error);
      enqueueSnackbar('Error renaming document', { variant: 'error' });
    }
  };

  const handleCreateCopy = async () => {
    try {
      if (!document) return;
      const email = localStorage.getItem('email');
      if (!email) throw new Error('No email found');
      const userData = await getUserByEmail(email);
      const agencyId = localStorage.getItem('selectedAgency');
      if (!agencyId) throw new Error('No agency selected');

      await fileManagerApi.createCopy(
        document.uniqueId,
        document.path || '',
      
      );
      enqueueSnackbar('Copy created successfully', { variant: 'success' });
    } catch (error) {
      console.error('Error creating copy:', error);
      enqueueSnackbar('Error creating copy', { variant: 'error' });
    }
  };

  const handleShare = async (email: string, accessLevel: AccessLevel) => {
    try {
      if (!document) return;
      await fileManagerApi.shareDocument(document.uniqueId, email, accessLevel);
      enqueueSnackbar('Document shared successfully', { variant: 'success' });
    } catch (error) {
      console.error('Error sharing document:', error);
      enqueueSnackbar('Error sharing document', { variant: 'error' });
    }
  };

  const renderDocumentRow = (document: IFile) => (
    <TableRow>
      <TableCell sx={{ display: 'flex', alignItems: 'center' }}>
        <FileThumbnail 
          file={document.type === 'folder' ? 'folder' : getFileFormat(document.name)} 
          sx={{ width: 36, height: 36 }} 
        />
        
        <Stack spacing={0.5} sx={{ ml: 2 }}>
          <Typography variant="subtitle2">{document.name}</Typography>
          <Typography variant="body2" sx={{ color: 'text.secondary' }}>
            {document.type === 'folder' ? `${document.size || 0} files` : fData(document.size || 0)}
          </Typography>
        </Stack>
      </TableCell>

      <TableCell>{document.ownerFullName}</TableCell>
      <TableCell>{document.type==='folder' ? 'folder' : getFileFormat(document.name)} </TableCell>
      <TableCell>{fDateTime(document.modifiedAt)}</TableCell>

      <TableCell align="right">
      <IconButton onClick={(event) => {
        setSelectedItem(document);  
        popover.onOpen(event);
      }}>
          <Iconify icon="eva:more-vertical-fill" />
        </IconButton>
      </TableCell>
    </TableRow>
  );

  if (loading) {
    return (
      <Container>
        <Stack alignItems="center" justifyContent="center" sx={{ height: '60vh' }}>
          <CircularProgress />
        </Stack>
      </Container>
    );
  }

  if (error || !document) {
    return (
      <Container>
        <EmptyContent
          title="Access Error"
          description={error || 'Unable to access this document'}
          sx={{ height: '60vh' }}
        >
          <Button
            variant="contained"
            onClick={handleBackToFileManager}
            startIcon={<Iconify icon="eva:arrow-back-fill" />}
          >
            Back to File Manager
          </Button>
        </EmptyContent>
      </Container>
    );
  }



  return (
    <Container maxWidth="lg">
      {currentFolder ? (
         <Stack spacing={2.5}>
         {/* Navigation Breadcrumbs */}
         <Stack 
           direction="row" 
           alignItems="center" 
           spacing={2}
           sx={{ mb: 3 }}
         >
           <Button
             variant="text"
             color="inherit"
             startIcon={<Iconify icon="eva:arrow-ios-back-fill" />}
             onClick={handleBackToFileManager}
           >
             Back
           </Button>
           <Breadcrumbs separator={<Iconify icon="eva:arrow-ios-forward-fill" />}>
             <Link
               component="button"
               variant="subtitle2"
               onClick={handleBackToFileManager}
               sx={{ 
                 color: 'text.primary',
                 '&:hover': { textDecoration: 'underline' }
               }}
             >
               File Manager
             </Link>
             <Typography variant="subtitle2" color="primary">
               {currentFolder ? currentFolder.name : document?.name}
             </Typography>
           </Breadcrumbs>
         </Stack>
   
         {/* Titre de la section */}
         <Typography variant="h4" sx={{ mb: 3 }}>
           Folder Contents
         </Typography>
  
          {loading ? (
            <Stack alignItems="center" justifyContent="center" sx={{ height: '60vh' }}>
              <CircularProgress />
            </Stack>
          ) : (
            <Card>
              <TableContainer>
                <Table>
                  <TableHead>
                    <TableRow>
                      <TableCell>Name</TableCell>
                      <TableCell>Owner</TableCell>
                      <TableCell>Type</TableCell>
                      <TableCell>Modified</TableCell>
                      <TableCell align="right">Actions</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {folderContents.map((file) => renderDocumentRow(file))}
                    {!folderContents.length && (
                      <TableRow>
                        <TableCell colSpan={5}>
                          <EmptyContent
                            title="No Data"
                            description="No files or folders found in this location"
                            sx={{ py: 3 }}
                          />
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </TableContainer>
            </Card>
          )}
        </Stack>
      ) : (
        <Stack spacing={3}>
          <Stack
            direction="row"
            alignItems="center"
            spacing={1}
            sx={{ mb: 3 }}
          >
            <Button
              color="inherit"
              onClick={handleBackToFileManager}
              startIcon={<Iconify icon="eva:arrow-back-fill" />}
            >
              Back
            </Button>
            <Box sx={{ flexGrow: 1 }} />
          </Stack>
  
          <Card>
            <TableContainer>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>Name</TableCell>
                    <TableCell>Owner</TableCell>
                    <TableCell>Type</TableCell>
                    <TableCell>Modified</TableCell>
                    <TableCell align="right">Actions</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {document ? (
                    <>
                      {renderDocumentRow(document)}
                      {document.type === 'folder' && document.childrenFiles?.map((file) => (
                        file ? renderDocumentRow(file) : null
                      ))}
                    </>
                  ) : (
                    <TableRow>
                      <TableCell colSpan={5}>
                        <Box sx={{ textAlign: 'center', py: 3 }}>
                          <Typography variant="body2">No document available</Typography>
                        </Box>
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </TableContainer>
          </Card>
        </Stack>
      )}
  
  <CustomPopover
  open={popover.open}
  onClose={popover.onClose}
  arrow="right-top"
  sx={{ width: 160 }}
>
  {selectedItem && selectedItem.type === 'folder' ? (
    <MenuItem onClick={() => {
      popover.onClose();
      if (selectedItem.id) {
        handleOpenFolder(Number(selectedItem.id), selectedItem.name);
      }
    }}>
      <Iconify icon="ph:folder-open" />
      Open folder
    </MenuItem>
  ) : selectedItem ? (

    <>
      <MenuItem onClick={() => handleDownload(selectedItem)}>
        <Iconify icon="material-symbols:download" />
        Download
      </MenuItem>

      <MenuItem onClick={() => {
        popover.onClose();
        details.onTrue();
      }}>
        <Iconify icon="bi:info-circle" />
        Details
      </MenuItem>
    </>
  ) : (
   
    <MenuItem disabled>
      <Iconify icon="bi:info-circle" />
      No item selected
    </MenuItem>
  )}
</CustomPopover>
  
      <FileManagerFileDetails
        item={selectedItem || document}
        favorited={false}
        onFavorite={handleToggleFavorite}
        open={details.value}
        onClose={details.onFalse}
        onDelete={() => {}}
        onCopyLink={() => {}}
      />
  
      <FileManagerShareDialog
        open={share.value}
        shared={selectedItem?.shared || document?.shared}
        inviteEmail=""
        onChangeInvite={() => {}}
        onCopyLink={() => {}}
        onClose={() => share.onFalse()}
        uniqueId={selectedItem?.uniqueId || document?.uniqueId}
        onShare={handleShare}
      />
  
      {/* Players */}
      <ImagePlayer 
        open={preview.value} 
        onClose={preview.onFalse} 
        type={selectedItem?.type || ''} 
        url={selectedItem?.url || ''} 
        title={selectedItem?.name || ''} 
      />
      
      <DocPlayer 
        open={preview.value} 
        onClose={preview.onFalse} 
        type={selectedItem?.type || ''} 
        url={selectedItem?.url || ''} 
      />
      
      <VideoPlayer 
        open={preview.value} 
        onClose={preview.onFalse} 
        type={selectedItem?.type || ''} 
        url={selectedItem?.url || ''} 
      />
      
      <AudioPlayer 
        open={preview.value} 
        onClose={preview.onFalse} 
        type={selectedItem?.type || ''} 
        url={selectedItem?.url || ''} 
      />
    </Container>
  );
}