import { useState } from 'react';
import { ConfirmDialog } from "@/components/custom-dialog";
import Label from "@/components/label";
import { useBoolean } from "@/hooks";
import CustomPopover, { usePopover } from "@/shared/components/custom-popover";
import Iconify from "@/shared/components/iconify/iconify";
import { ITransfer } from "@/shared/types/transfer";
import { fDate } from "@/utils/format-time";
import { 
    Avatar, 
    Button, 
    Checkbox, 
    IconButton, 
    ListItemText, 
    MenuItem, 
    TableCell, 
    TableRow, 
    Typography 
} from "@mui/material";
import { useSnackbar } from "@/components/snackbar";
import { transferApi } from "@/shared/api/transfer-file";
import UrlsDialog from './urls-dialog';

type Props = {
    row: ITransfer;
    selected: boolean;
    onSelectRow: VoidFunction;
    onDeleteRow: VoidFunction;
};

export default function TransferTableRow({
    row,
    selected,
    onSelectRow,
    onDeleteRow,
}: Props) {
    const { title, expirationDate, status } = row;
    const confirm = useBoolean();
    const popover = usePopover();
    const { enqueueSnackbar } = useSnackbar();

    const [openUrlsDialog, setOpenUrlsDialog] = useState(false);
    const [fileUrls, setFileUrls] = useState<Record<string, string>>({});
    const [isLoadingUrls, setIsLoadingUrls] = useState(false);

    const handleOpenUrlsDialog = async () => {
        try {
            setIsLoadingUrls(true);
            const urls = await transferApi.getTransferUrls(row.id);
            setFileUrls(urls);
            setOpenUrlsDialog(true);
            popover.onClose();
        } catch (error) {
            console.error('Error fetching URLs:', error);
            enqueueSnackbar('Failed to load file URLs', { variant: 'error' });
        } finally {
            setIsLoadingUrls(false);
        }
    };

    const handleCloseUrlsDialog = () => {
        setOpenUrlsDialog(false);
    };

    const handleDownload = async () => {
        try {
            setIsLoadingUrls(true);
            const urls = await transferApi.getTransferUrls(row.id);
            
            await Promise.all(
                Object.entries(urls).map(async ([fileName, url]) => {
                    const response = await fetch(url);
                    const blob = await response.blob();
                    const downloadUrl = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = downloadUrl;
                    a.download = fileName;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(downloadUrl);
                    document.body.removeChild(a);
                })
            );

            enqueueSnackbar('Files downloaded successfully!', { variant: 'success' });
        } catch (error) {
            console.error('Download error:', error);
            enqueueSnackbar('Failed to download files', { variant: 'error' });
        } finally {
            setIsLoadingUrls(false);
            popover.onClose();
        }
    };

    return (
        <>
            <TableRow hover selected={selected}>
                <TableCell padding="checkbox">
                    <Checkbox checked={selected} onClick={onSelectRow} />
                </TableCell>

                <TableCell sx={{ display: 'flex', alignItems: 'center' }}>
                    <Avatar alt={title} sx={{ mr: 2 }}>
                        {title.charAt(0).toUpperCase()}
                    </Avatar>

                    <ListItemText
                        disableTypography
                        primary={
                            <Typography variant="body2" noWrap>
                                {title}
                            </Typography>
                        }
                    />
                </TableCell>

                <TableCell>
                    <ListItemText
                        primary={fDate(expirationDate)}
                        primaryTypographyProps={{ typography: 'body2', noWrap: true }}
                        secondaryTypographyProps={{
                            mt: 0.5,
                            component: 'span',
                            typography: 'caption',
                        }}
                    />
                </TableCell>

                <TableCell>
                    <Label
                        variant="soft"
                        color={
                            (status === 'valid' && 'success') ||
                            (status === 'expired' && 'error') ||
                            'default'
                        }
                    >
                        {status}
                    </Label>
                </TableCell>

                <TableCell align="right" sx={{ px: 1 }}>
                    <IconButton 
                        color={popover.open ? 'inherit' : 'default'} 
                        onClick={popover.onOpen}
                    >
                        <Iconify icon="eva:more-vertical-fill" />
                    </IconButton>
                </TableCell>
            </TableRow>

            <CustomPopover
                open={popover.open}
                onClose={popover.onClose}
                arrow="right-top"
                sx={{ width: 160 }}
            >
                <MenuItem
                    onClick={handleOpenUrlsDialog}
                    disabled={isLoadingUrls}
                >
                    <Iconify icon="eva:link-2-fill" />
                    Link transfer
                </MenuItem>

                <MenuItem onClick={handleDownload} disabled={isLoadingUrls}>
                    <Iconify icon="eva:cloud-download-fill" />
                    {isLoadingUrls ? 'Downloading...' : 'Download'}
                </MenuItem>

                <MenuItem
                    onClick={() => {
                        confirm.onTrue();
                        popover.onClose();
                    }}
                    sx={{ color: 'error.main' }}
                >
                    <Iconify icon="solar:trash-bin-trash-bold" />
                    Delete
                </MenuItem>
            </CustomPopover>

            <ConfirmDialog
                open={confirm.value}
                onClose={confirm.onFalse}
                title="Delete"
                content="Are you sure want to delete?"
                action={
                    <Button variant="contained" color="error" onClick={onDeleteRow}>
                        Delete
                    </Button>
                }
            />

            <UrlsDialog 
                open={openUrlsDialog} 
                onClose={handleCloseUrlsDialog} 
                urls={fileUrls}
                isLoading={isLoadingUrls}
            />
        </>
    );
}