import {
  Badge,
  Box,
  Button,
  Group,
  Paper,
  Stack,
  Text,
  ThemeIcon,
  Tooltip,
} from "@mantine/core";
import { Download, Eye, FileText } from "lucide-react";
import type { Freight } from "@edr/types";
import { isViewable } from "@edr/ui-common";

import { SectionCard } from "@/components/bookings/detail/SectionCard";
import { fetchViewableFile } from "@/services/files.service";

const CATEGORY_LABELS: Record<
  Freight.ClearanceWorkflowFileCategory,
  string
> = {
  declaration: "Declaration",
  duty: "Duty & taxes",
  transit: "Transit",
  djibouti: "Djibouti",
};

const CATEGORY_ORDER: Freight.ClearanceWorkflowFileCategory[] = [
  "declaration",
  "duty",
  "transit",
  "djibouti",
];

const OWNER_LABELS: Record<Freight.ClearanceWorkflowFileOwner, string> = {
  customer: "Customer",
  gl_et: "GL Ethiopia",
  gl_dj: "GL Djibouti",
};

export interface ClearanceWorkflowFilesPanelProps {
  files: Freight.ClearanceWorkflowFile[];
  onView: (file: { name: string; url: string }) => void;
  onDownload?: (file: { id: string; name: string }) => void;
  title?: string;
}

export function ClearanceWorkflowFilesPanel({
  files,
  onView,
  onDownload,
  title = "Customs workflow documents",
}: ClearanceWorkflowFilesPanelProps) {
  if (files.length === 0) return null;

  const grouped = CATEGORY_ORDER.map((category) => ({
    category,
    label: CATEGORY_LABELS[category],
    items: files.filter((f) => f.category === category),
  })).filter((g) => g.items.length > 0);

  return (
    <SectionCard icon={FileText} title={title} accent="edr-green">
      <Stack gap="md">
        {grouped.map((group) => (
          <Box key={group.category}>
            <Text size="xs" fw={700} c="dimmed" tt="uppercase" mb={8}>
              {group.label}
            </Text>
            <Stack gap={8}>
              {group.items.map((item) => (
                <WorkflowFileRow
                  key={item.code}
                  item={item}
                  onView={onView}
                  onDownload={onDownload}
                />
              ))}
            </Stack>
          </Box>
        ))}
      </Stack>
    </SectionCard>
  );
}

function WorkflowFileRow({
  item,
  onView,
  onDownload,
}: {
  item: Freight.ClearanceWorkflowFile;
  onView: (file: { name: string; url: string }) => void;
  onDownload?: (file: { id: string; name: string }) => void;
}) {
  const file = item.file;
  if (!file) return null;

  const canPreview = isViewable({ name: file.name, url: "" });

  return (
    <Paper withBorder radius="md" p="sm">
      <Group justify="space-between" wrap="nowrap" align="center">
        <Group gap={10} wrap="nowrap" style={{ minWidth: 0 }}>
          <ThemeIcon variant="light" color="edr-green" radius="md" size={36}>
            <FileText size={17} />
          </ThemeIcon>
          <Box style={{ minWidth: 0 }}>
            <Text size="sm" fw={600} truncate>
              {item.label}
            </Text>
            <Group gap={6} wrap="nowrap" mt={2}>
              <Badge size="xs" variant="light" color="gray" radius="sm" tt="none">
                {OWNER_LABELS[item.uploadedBy]}
              </Badge>
              <Text size="xs" c="dimmed" truncate>
                {file.name}
              </Text>
            </Group>
          </Box>
        </Group>
        <Group gap={6} wrap="nowrap">
          {canPreview ? (
            <Tooltip label="Preview">
              <Button
                size="compact-xs"
                variant="default"
                radius="md"
                leftSection={<Eye size={13} />}
                onClick={() =>
                  void fetchViewableFile(file.id, file.name).then(onView)
                }
              >
                View
              </Button>
            </Tooltip>
          ) : null}
          {onDownload ? (
            <Tooltip label="Download">
              <Button
                size="compact-xs"
                variant="light"
                radius="md"
                leftSection={<Download size={13} />}
                onClick={() => onDownload({ id: file.id, name: file.name })}
              >
                Download
              </Button>
            </Tooltip>
          ) : null}
        </Group>
      </Group>
    </Paper>
  );
}
