import { useState, useCallback, useEffect } from 'react';
import Box from '@mui/material/Box';
import Chip from '@mui/material/Chip';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import Divider from '@mui/material/Divider';
import Checkbox from '@mui/material/Checkbox';
import TextField from '@mui/material/TextField';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import Autocomplete from '@mui/material/Autocomplete';
import Drawer, { DrawerProps } from '@mui/material/Drawer';

import { useBoolean } from '@/hooks/use-boolean';
import { fData } from '@/utils/format-number';
import { fDateTime } from '@/utils/format-time';

import Iconify from '@/shared/components/iconify';
import Scrollbar from '@/shared/components/scrollbar';
import FileThumbnail, { fileFormat } from '@/shared/components/file-thumbnail';

import { IFile } from '@/shared/types/file';
import FileManagerShareDialog from './file-manager-share-dialog';
import FileManagerInvitedItem from './file-manager-invited-item';
import { AccessLevel, fileManagerApi } from '@/shared/api/file-manager';
import { enqueueSnackbar } from '@/shared/components/snackbar';

type Props = DrawerProps & {
  item: IFile;
  favorited?: boolean;
  onFavorite: (uniqueId: string, isFavorited: boolean) => Promise<boolean>;
  onCopyLink: VoidFunction;
  
  onClose: VoidFunction;
  onDelete: (id: string) => void;
  onRefresh?: VoidFunction; 
};

export default function FileManagerFileDetails({
  item,
  open,
  favorited,
  onFavorite,
  onCopyLink,
  onClose,
  onDelete,
  onRefresh,
  ...other
}: Props) {
  const { 
    name = '', 
    size = 0, 
    url = '', 
    type = '', 
    shared = [], 
    createdAt, 
    modifiedAt,
    tags = []
  } = item;

  const hasShared = shared && shared.length > 0;

  const toggleTags = useBoolean(true);
  const share = useBoolean();
  const properties = useBoolean(true);
  const favorite = useBoolean(favorited);
  const [inviteEmail, setInviteEmail] = useState('');
  const [currentTags, setCurrentTags] = useState<string[]>(tags.slice(0, 3));

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

  const handleChangeTags = useCallback((newValue: string[]) => {
    setCurrentTags(newValue);
  }, []);
  useEffect(() => {
    favorite.setValue(favorited || false);
  }, [favorited, favorite]);
  const handleShare = useCallback(async (email: string, accessLevel: AccessLevel) => {
    try {
      await fileManagerApi.shareDocument(item.uniqueId, email, accessLevel);
      enqueueSnackbar('Document shared successfully');
      share.onFalse();
      setInviteEmail('');
      if (onRefresh) {
        onRefresh();
      }
    } catch (error) {
      console.error('Error sharing document:', error);
      enqueueSnackbar('Error sharing document', { variant: 'error' });
    }
  }, [item.uniqueId, enqueueSnackbar, share, onRefresh]);

  const handleToggleFavorite = useCallback(async (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    try {
      const success = await onFavorite(item.uniqueId, favorite.value);
      if (success) {
        favorite.onToggle();
        if (onRefresh) {
          onRefresh();
        }
        enqueueSnackbar(
          favorite.value ? 'Removed from favorites' : 'Added to favorites',
          { variant: 'success' }
        );
      }
    } catch (error) {
      console.error('Error toggling favorite:', error);
      enqueueSnackbar('Error updating favorite status', { variant: 'error' });
    }
  }, [item.uniqueId, favorite.value, onFavorite, onRefresh, enqueueSnackbar, favorite]);

  const renderTags = (
    <Stack spacing={1.5}>
      <Stack
        direction="row"
        alignItems="center"
        justifyContent="space-between"
        sx={{ typography: 'subtitle2' }}
      >
        Tags
        <IconButton size="small" onClick={toggleTags.onToggle}>
          <Iconify
            icon={toggleTags.value ? 'eva:arrow-ios-upward-fill' : 'eva:arrow-ios-downward-fill'}
          />
        </IconButton>
      </Stack>

      {toggleTags.value && (
        <Autocomplete
          multiple
          freeSolo
          options={tags}
          getOptionLabel={(option) => option}
          defaultValue={tags.slice(0, 3)}
          value={currentTags}
          onChange={(event, newValue) => {
            handleChangeTags(newValue);
          }}
          renderOption={(props, option) => (
            <li {...props} key={option}>
              {option}
            </li>
          )}
          renderTags={(selected, getTagProps) =>
            selected.map((option, index) => (
              <Chip
                {...getTagProps({ index })}
                size="small"
                variant="soft"
                label={option}
                key={option}
              />
            ))
          }
          renderInput={(params) => <TextField {...params} placeholder="#Add a tags" />}
        />
      )}
    </Stack>
  );

  const renderProperties = (
    <Stack spacing={1.5}>
      <Stack
        direction="row"
        alignItems="center"
        justifyContent="space-between"
        sx={{ typography: 'subtitle2' }}
      >
        Properties
        <IconButton size="small" onClick={properties.onToggle}>
          <Iconify
            icon={properties.value ? 'eva:arrow-ios-upward-fill' : 'eva:arrow-ios-downward-fill'}
          />
        </IconButton>
      </Stack>

      {properties.value && (
        <>
          <Stack direction="row" sx={{ typography: 'caption', textTransform: 'capitalize' }}>
            <Box component="span" sx={{ width: 80, color: 'text.secondary', mr: 2 }}>
              Size
            </Box>
            {fData(size)}
          </Stack>

          <Stack direction="row" sx={{ typography: 'caption', textTransform: 'capitalize' }}>
            <Box component="span" sx={{ width: 80, color: 'text.secondary', mr: 2 }}>
              Created
            </Box>
            {createdAt ? fDateTime(createdAt) : 'N/A'}
          </Stack>

          <Stack direction="row" sx={{ typography: 'caption', textTransform: 'capitalize' }}>
            <Box component="span" sx={{ width: 80, color: 'text.secondary', mr: 2 }}>
              Modified
            </Box>
            {modifiedAt ? fDateTime(modifiedAt) : 'N/A'}
          </Stack>

          <Stack direction="row" sx={{ typography: 'caption', textTransform: 'capitalize' }}>
            <Box component="span" sx={{ width: 80, color: 'text.secondary', mr: 2 }}>
              Type
            </Box>
            {fileFormat(type)}
          </Stack>
        </>
      )}
    </Stack>
  );

  const renderShared = (
    <>
      <Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ p: 2.5 }}>
        <Typography variant="subtitle2"> File Share With </Typography>

        <IconButton
          size="small"
          color="primary"
          onClick={share.onTrue}
          sx={{
            width: 24,
            height: 24,
            bgcolor: 'primary.main',
            color: 'primary.contrastText',
            '&:hover': {
              bgcolor: 'primary.dark',
            },
          }}
        >
          <Iconify icon="mingcute:add-line" />
        </IconButton>
      </Stack>

      {hasShared && (
        <Box sx={{ pl: 2.5, pr: 1 }}>
          {shared.map((person) => (
            <FileManagerInvitedItem key={person.id} person={person} />
          ))}
        </Box>
      )}
    </>
  );

  const thumbnailUrl = type === 'folder' ? type : url || type;

  return (
    <>
      <Drawer
        open={open}
        onClose={onClose}
        anchor="right"
        slotProps={{
          backdrop: { invisible: true },
        }}
        PaperProps={{
          sx: { width: 320 },
        }}
        {...other}
      >
        <Scrollbar sx={{ height: 1 }}>
          <Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ p: 2.5 }}>
            <Typography variant="h6"> Info </Typography>

            <Checkbox
              color="warning"
              icon={<Iconify icon="eva:star-outline" />}
              checkedIcon={<Iconify icon="eva:star-fill" />}
              checked={favorited}
              onChange={handleToggleFavorite}
            />
          
          </Stack>

          <Stack
            spacing={2.5}
            justifyContent="center"
            sx={{
              p: 2.5,
              bgcolor: 'background.neutral',
            }}
          >
            <FileThumbnail
              imageView
              file={thumbnailUrl}
              sx={{ width: 64, height: 64 }}
              imgSx={{ borderRadius: 1 }}
            />

            <Typography variant="subtitle1" sx={{ wordBreak: 'break-all' }}>
              {name}
            </Typography>

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

            {renderTags}
            {renderProperties}
          </Stack>

          {renderShared}
        </Scrollbar>

        <Box sx={{ p: 2.5 }}>
          <Button
            fullWidth
            variant="soft"
            color="error"
            size="large"
            startIcon={<Iconify icon="solar:trash-bin-trash-bold" />}
            onClick={() => onDelete(item.id)}
          >
            Delete
          </Button>
        </Box>
      </Drawer>

      <FileManagerShareDialog
        open={share.value}
        shared={shared}
        inviteEmail={inviteEmail}
        onChangeInvite={handleChangeInvite}
        onCopyLink={onCopyLink}
        onClose={() => {
          share.onFalse();
          setInviteEmail('');
        }}
        uniqueId={item.uniqueId}
        onShare={handleShare}
      />
    </>
  );
}