import { useState } from "react";
import {
  Card,
  Stack,
  Text,
  Group,
  Badge,
  Button,
  Box,
  ActionIcon,
  Tooltip,
} from "@mantine/core";
import { useTranslation } from "react-i18next";
import StorageIcon from "@mui/icons-material/Storage";
import VisibilityIcon from "@mui/icons-material/Visibility";
import EditIcon from "@mui/icons-material/Edit";

import { StirlingFileStub } from "@app/types/fileContext";
import { getFileSize, getFileDate } from "@app/utils/fileUtils";
import { useFileThumbnail } from "@app/hooks/useFileThumbnail";
import DocumentThumbnail from "@app/components/shared/filePreview/DocumentThumbnail";

interface FileCardProps {
  file: File;
  fileStub?: StirlingFileStub;
  onRemove: () => void;
  onDoubleClick?: () => void;
  onView?: () => void;
  onEdit?: () => void;
  isSelected?: boolean;
  onSelect?: () => void;
  isSupported?: boolean; // Whether the file format is supported by the current tool
}

const FileCard = ({
  file,
  fileStub,
  onRemove,
  onDoubleClick,
  onView,
  onEdit,
  isSelected,
  onSelect,
  isSupported = true,
}: FileCardProps) => {
  const { t } = useTranslation();
  const {
    isEncrypted,
    thumbnail: thumb,
    isGenerating,
  } = useFileThumbnail(fileStub);
  const [isHovered, setIsHovered] = useState(false);

  const isPdf = file.type === "application/pdf";
  const isHydrating = isPdf && !isEncrypted && !thumb && !isGenerating;

  return (
    <Card
      shadow="xs"
      radius="md"
      withBorder
      p="xs"
      style={{
        width: 225,
        minWidth: 180,
        maxWidth: 260,
        cursor: onDoubleClick && isSupported ? "pointer" : undefined,
        position: "relative",
        border: isSelected
          ? "2px solid var(--mantine-color-blue-6)"
          : undefined,
        backgroundColor: isSelected ? "var(--mantine-color-blue-0)" : undefined,
        opacity: 1,
      }}
      onDoubleClick={onDoubleClick}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      onClick={onSelect}
      data-testid="file-card"
      data-tour="file-card-checkbox"
    >
      <Stack gap={6} align="center">
        <Box
          style={{
            border: "2px solid #e0e0e0",
            borderRadius: 8,
            width: 90,
            height: 120,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            margin: "0 auto",
            background: "#fafbfc",
            position: "relative",
          }}
        >
          {/* Hover action buttons */}
          {isHovered && (onView || onEdit) && (
            <div
              style={{
                position: "absolute",
                top: 4,
                right: 4,
                display: "flex",
                gap: 4,
                zIndex: 10,
                backgroundColor: "rgba(255, 255, 255, 0.9)",
                borderRadius: 4,
                padding: 2,
              }}
              onClick={(e) => e.stopPropagation()}
            >
              {onView && (
                <Tooltip label={t("fileCard.viewInViewer", "View in Viewer")}>
                  <ActionIcon
                    size="sm"
                    variant="subtle"
                    color="blue"
                    onClick={(e) => {
                      e.stopPropagation();
                      onView();
                    }}
                  >
                    <VisibilityIcon style={{ fontSize: 16 }} />
                  </ActionIcon>
                </Tooltip>
              )}
              {onEdit && (
                <Tooltip
                  label={t("fileCard.openInFileEditor", "Open in File Editor")}
                >
                  <ActionIcon
                    size="sm"
                    variant="subtle"
                    color="orange"
                    onClick={(e) => {
                      e.stopPropagation();
                      onEdit();
                    }}
                  >
                    <EditIcon style={{ fontSize: 16 }} />
                  </ActionIcon>
                </Tooltip>
              )}
            </div>
          )}
          <DocumentThumbnail
            file={file}
            thumbnail={thumb || undefined}
            isEncrypted={isEncrypted}
            isLoading={isGenerating || isHydrating}
            iconSize="3rem"
          />
        </Box>

        <Text fw={500} size="sm" lineClamp={1} ta="center">
          {file.name}
        </Text>

        <Group gap="xs" justify="center">
          <Badge color="red" variant="light" size="sm">
            {getFileSize(file)}
          </Badge>
          <Badge color="blue" variant="light" size="sm">
            {getFileDate(file)}
          </Badge>
          {fileStub?.id && (
            <Badge
              color="green"
              variant="light"
              size="sm"
              leftSection={<StorageIcon style={{ fontSize: 12 }} />}
            >
              DB
            </Badge>
          )}
          {!isSupported && (
            <Badge color="orange" variant="filled" size="sm">
              {t("fileManager.unsupported", "Unsupported")}
            </Badge>
          )}
        </Group>

        <Button
          color="red"
          size="xs"
          variant="light"
          onClick={(e) => {
            e.stopPropagation();
            onRemove();
          }}
          mt={4}
        >
          {t("delete", "Remove")}
        </Button>
      </Stack>
    </Card>
  );
};

export default FileCard;
