import { useState } from "react";
import {
  Button,
  Group,
  NumberInput,
  Select,
  Stack,
  Text,
  TextInput,
} from "@mantine/core";
import { Receipt } from "lucide-react";
import type { Freight } from "@edr/types";

import { useAdviseDuty } from "@/hooks/contracts/useContracts";
import { ActionShell } from "./ActionShell";

export function AdviseDutyCard({
  bookingId,
  milestone,
}: {
  bookingId: string;
  milestone: Freight.IClearanceMilestone;
}) {
  const advise = useAdviseDuty(bookingId);
  const [amount, setAmount] = useState<number | string>("");
  const [currency, setCurrency] = useState("ETB");
  const [serial, setSerial] = useState("");

  const done = milestone.status === "COMPLETED";
  const meta = milestone.metadata;

  return (
    <ActionShell
      icon={Receipt}
      title="Duty & tax"
      subtitle="Advise the duty/tax amount and declaration serial."
      done={done}
      doneLabel={
        meta?.dutyAmount != null
          ? `${meta.dutyAmount.toLocaleString()} ${meta.dutyCurrency ?? ""}`
          : "Advised"
      }
    >
      <Stack gap="sm">
        <Group grow>
          <NumberInput
            label="Amount"
            placeholder="0.00"
            value={amount}
            onChange={setAmount}
            min={0}
            thousandSeparator=","
            size="sm"
          />
          <Select
            label="Currency"
            data={["ETB", "USD"]}
            value={currency}
            onChange={(v) => setCurrency(v ?? "ETB")}
            size="sm"
            allowDeselect={false}
          />
        </Group>
        <TextInput
          label="Declaration serial"
          placeholder="e.g. IM4-2026-00123"
          value={serial}
          onChange={(e) => setSerial(e.currentTarget.value)}
          size="sm"
        />
        <Group justify="space-between">
          <Text size="xs" c="dimmed">
            Customer uploads the payment slip after being advised.
          </Text>
          <Button
            size="compact-sm"
            color="edr-green"
            loading={advise.isPending}
            disabled={!amount || Number(amount) <= 0}
            onClick={() =>
              advise.mutate({
                amount: Number(amount),
                currency,
                declarationSerial: serial.trim() || undefined,
              })
            }
          >
            Advise customer
          </Button>
        </Group>
      </Stack>
    </ActionShell>
  );
}
