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

import { BORDER, GREEN, INK } from "@/pages/contracts/contract-ui";

type TabValue = Freight.ClearanceWorkflowFileCategory;

type TabConfig = {
  value: TabValue;
  label: string;
  icon: typeof FileText;
  emptyHint: string;
};

function tabConfigForTradeDirection(tradeDirection: string): TabConfig[] {
  if (tradeDirection === "EXPORT") {
    return [
      {
        value: "declaration",
        label: "Declaration",
        icon: FileText,
        emptyHint:
          "Global Logistics will upload your customs declaration documents here once they are ready.",
      },
      {
        value: "djibouti",
        label: "Release order",
        icon: Ship,
        emptyHint: "The release order will appear here once Global Logistics Djibouti uploads it.",
      },
      {
        value: "transit",
        label: "Transit Permit",
        icon: Truck,
        emptyHint:
          "The transit permit will appear here after your booking is created and wagons are allocated.",
      },
    ];
  }

  return [
    {
      value: "declaration",
      label: "Declaration",
      icon: FileText,
      emptyHint:
        "Global Logistics will upload your customs declaration documents here once they are ready.",
    },
    {
      value: "duty",
      label: "Duty notice",
      icon: Receipt,
      emptyHint: "Your duty/tax notice and payment slip will appear here when available.",
    },
    {
      value: "transit",
      label: "Transit Permit",
      icon: Truck,
      emptyHint: "The transit permit will appear here once Global Logistics uploads it.",
    },
  ];
}

function defaultSubtitle(tradeDirection: string): string {
  return tradeDirection === "EXPORT"
    ? "Declaration, release order, and transit permit shared during your clearance."
    : "Declaration, duty notice, and transit permit shared during your clearance.";
}

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

function fileTypeChip(name: string): { ext: string; color: string } {
  const dot = name.lastIndexOf(".");
  const ext = dot >= 0 ? name.slice(dot + 1).toUpperCase() : "FILE";
  const color =
    ext === "PDF"
      ? "#D64545"
      : ["PNG", "JPG", "JPEG", "GIF", "WEBP", "SVG"].includes(ext)
        ? "#2F9E6E"
        : "#6B7C8E";
  return { ext: ext.slice(0, 4), color };
}

export interface ClearanceUploadedDocumentsPanelProps {
  files: Freight.ClearanceWorkflowFile[];
  tradeDirection?: string;
  onView: (file: { name: string; url: string; mimeType?: string }) => void;
  onDownload?: (file: { id: string; name: string }) => void;
  title?: string;
  subtitle?: string;
  embedded?: boolean;
}

export function ClearanceUploadedDocumentsPanel({
  files,
  tradeDirection = "IMPORT",
  onView,
  onDownload,
  title = "Customs documents",
  subtitle,
  embedded = false,
}: ClearanceUploadedDocumentsPanelProps) {
  const tabConfig = useMemo(
    () => tabConfigForTradeDirection(tradeDirection),
    [tradeDirection],
  );
  const isExport = tradeDirection === "EXPORT";
  const visibleFiles = useMemo(
    () => (isExport ? files.filter((f) => f.category !== "duty") : files),
    [files, isExport],
  );
  const uploadedCount = visibleFiles.filter((f) => f.file).length;

  const defaultTab =
    tabConfig.find((tab) =>
      visibleFiles.some((f) => f.category === tab.value && f.file),
    )?.value ?? tabConfig[0]?.value ?? "declaration";

  const resolvedSubtitle = subtitle ?? defaultSubtitle(tradeDirection);

  const content = (
    <Tabs defaultValue={defaultTab} keepMounted={false}>
      <Tabs.List mb="md" style={{ flexWrap: "wrap", gap: 6 }}>
        {tabConfig.map((tab) => {
          const count = visibleFiles.filter(
            (f) => f.category === tab.value && f.file,
          ).length;
          const Icon = tab.icon;
          return (
            <Tabs.Tab
              key={tab.value}
              value={tab.value}
              leftSection={<Icon size={14} />}
              rightSection={
                count > 0 ? (
                  <Badge size="xs" variant="light" color="edr-green" circle>
                    {count}
                  </Badge>
                ) : undefined
              }
              styles={{
                tab: { borderRadius: 10, fontWeight: 600, padding: "8px 14px" },
              }}
            >
              {tab.label}
            </Tabs.Tab>
          );
        })}
      </Tabs.List>

      {tabConfig.map((tab) => {
        const items = visibleFiles.filter(
          (f) => f.category === tab.value && f.file,
        );
        const Icon = tab.icon;

        return (
          <Tabs.Panel key={tab.value} value={tab.value}>
            {items.length > 0 ? (
              <Stack gap={10}>
                {items.map((item) => (
                  <WorkflowFileRow
                    key={item.code}
                    item={item}
                    onView={onView}
                    onDownload={onDownload}
                  />
                ))}
              </Stack>
            ) : (
              <EmptyTabState icon={Icon} hint={tab.emptyHint} />
            )}
          </Tabs.Panel>
        );
      })}
    </Tabs>
  );

  if (embedded) return content;

  return (
    <Paper
      withBorder
      radius="lg"
      p="lg"
      style={{
        borderColor: "#CDEBDD",
        background: "linear-gradient(160deg, #F6FBF8 0%, #FFFFFF 55%)",
        boxShadow: "0 4px 18px rgba(14,163,113,0.06)",
      }}
    >
      <Group gap={10} mb={4} wrap="nowrap">
        <Box
          style={{
            width: 36,
            height: 36,
            borderRadius: 10,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            background: `${GREEN}18`,
            color: GREEN,
          }}
        >
          <FileText size={18} />
        </Box>
        <Box>
          <Group gap={8} wrap="nowrap">
            <Text fw={700} fz={15} style={{ color: INK }}>
              {title}
            </Text>
            {uploadedCount > 0 ? (
              <Badge size="sm" variant="light" color="edr-green" radius="sm">
                {uploadedCount} file{uploadedCount === 1 ? "" : "s"}
              </Badge>
            ) : null}
          </Group>
          <Text fz={12} c="dimmed" mt={2}>
            {resolvedSubtitle}
          </Text>
        </Box>
      </Group>
      <Box mt="md">{content}</Box>
    </Paper>
  );
}

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

  const { ext, color } = fileTypeChip(file.name);
  const canPreview = isViewable({ name: file.name, url: file.url });

  return (
    <Group
      justify="space-between"
      wrap="nowrap"
      p="sm"
      style={{
        borderRadius: 14,
        border: `1px solid ${GREEN}44`,
        background: "linear-gradient(135deg, #F2FBF6 0%, #FFFFFF 72%)",
      }}
    >
      <Group gap={12} wrap="nowrap" style={{ minWidth: 0 }}>
        <Box
          style={{
            width: 44,
            height: 44,
            flexShrink: 0,
            borderRadius: 10,
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            justifyContent: "center",
            background: `${color}14`,
            color,
          }}
        >
          <FileText size={16} />
          <Text fz={8} fw={800} mt={1} style={{ letterSpacing: "0.04em" }}>
            {ext}
          </Text>
        </Box>
        <Box style={{ minWidth: 0 }}>
          <Text fz={14} fw={600} style={{ color: INK }} truncate>
            {item.label}
          </Text>
          <Group gap={6} wrap="nowrap" mt={3}>
            <Badge size="xs" variant="light" color="edr-green" radius="sm">
              Uploaded
            </Badge>
            <Badge size="xs" variant="light" color="gray" radius="sm" tt="none">
              {OWNER_LABELS[item.uploadedBy]}
            </Badge>
          </Group>
          <Text fz={12} c="dimmed" truncate mt={2}>
            {file.name}
          </Text>
        </Box>
      </Group>
      <Group gap={6} wrap="nowrap">
        {canPreview ? (
          <Tooltip label="Preview">
            <Button
              size="compact-xs"
              variant="light"
              color="edr-green"
              radius="md"
              leftSection={<Eye size={13} />}
              onClick={() => onView({ name: file.name, url: file.url })}
            >
              View
            </Button>
          </Tooltip>
        ) : null}
        {onDownload ? (
          <Tooltip label="Download">
            <Button
              size="compact-xs"
              variant="default"
              radius="md"
              leftSection={<Download size={13} />}
              onClick={() => onDownload({ id: file.id, name: file.name })}
            >
              Download
            </Button>
          </Tooltip>
        ) : null}
      </Group>
    </Group>
  );
}

function EmptyTabState({
  icon: Icon,
  hint,
}: {
  icon: typeof FileText;
  hint: string;
}) {
  return (
    <Box
      py={36}
      px="md"
      style={{
        borderRadius: 14,
        border: `1px dashed ${BORDER}`,
        background: "#FAFCFE",
        textAlign: "center",
      }}
    >
      <Stack gap={8} align="center">
        <ThemeIcon variant="light" color="gray" radius="xl" size={44}>
          <Icon size={20} />
        </ThemeIcon>
        <Text fz={13} c="dimmed" maw={360}>
          {hint}
        </Text>
      </Stack>
    </Box>
  );
}

/** @deprecated Use ClearanceUploadedDocumentsPanel for phased customs UI. */
export function ClearanceWorkflowFilesSection({
  files,
  onView,
  onDownload,
  title,
}: {
  files: Freight.ClearanceWorkflowFile[];
  onView: (file: { name: string; url: string; mimeType?: string }) => void;
  onDownload?: (file: { id: string; name: string }) => void;
  title?: string;
}) {
  if (files.length === 0) return null;
  return (
    <ClearanceUploadedDocumentsPanel
      files={files}
      onView={onView}
      onDownload={onDownload}
      title={title}
    />
  );
}
