import { Controller, type UseFormReturn } from "react-hook-form";
import {
  Badge,
  Box,
  Button,
  Group,
  Paper,
  Stack,
  Text,
  Textarea,
} from "@mantine/core";
import {
  CheckCircle2,
  Circle,
  ClipboardCheck,
  Coins,
  FileText,
  MapPin,
  Package,
  RotateCcw,
  Route,
  Send,
  Truck,
} from "lucide-react";
import { hazardClassLabel, type Freight } from "@edr/types";
import {
  type ContractFormInputValues,
  type ContractFormValues,
} from "./schema";
import { NotFinalPriceNotice, StepHeader } from "./shared";
import { formatRateUnit } from "./unit-rates";

type ContractForm = UseFormReturn<
  ContractFormInputValues,
  any,
  ContractFormValues
>;

/**
 * A read-only detail tile: a soft icon chip, an uppercase label, and the value.
 * Used in the review grid — no edit affordance, this page is summary-only.
 */
function SummaryItem({
  icon,
  label,
  value,
}: {
  icon: React.ReactNode;
  label: string;
  value: React.ReactNode;
}) {
  return (
    <Group gap={12} align="flex-start" wrap="nowrap">
      <Box
        style={{
          width: 38,
          height: 38,
          flexShrink: 0,
          borderRadius: 11,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          background: "var(--mantine-color-edr-green-0)",
          color: "var(--mantine-color-edr-green-7)",
        }}
      >
        {icon}
      </Box>
      <Box style={{ minWidth: 0 }}>
        <Text
          fz={11}
          c="dimmed"
          fw={700}
          tt="uppercase"
          style={{ letterSpacing: "0.05em" }}
        >
          {label}
        </Text>
        <Text fz={14} fw={600} c="#10202F" mt={2} style={{ lineHeight: 1.4 }}>
          {value || "—"}
        </Text>
      </Box>
    </Group>
  );
}

function ReadinessItem({ done, label }: { done: boolean; label: string }) {
  return (
    <Group gap="sm" wrap="nowrap">
      {done ? (
        <CheckCircle2 size={18} className="shrink-0 text-emerald-600" />
      ) : (
        <Circle size={18} className="shrink-0 text-gray-300" />
      )}
      <Text size="sm" c={done ? "dark" : "dimmed"}>
        {label}
      </Text>
    </Group>
  );
}

/**
 * Read-only UNIT-RATE pricing panel (doc §9.1). Shows per-container / per-ton /
 * per-item rates with NO total — quantities are unknown at the contract stage.
 */
function UnitRatePanel({
  currency,
  lineItems,
}: {
  currency: string;
  lineItems: Freight.ContractUnitRateLineItem[];
}) {
  return (
    <Paper
      radius={20}
      p="lg"
      withBorder
      style={{
        borderColor: "var(--mantine-color-edr-border-0)",
        background: "linear-gradient(135deg, #F4FBF7 0%, #FFFFFF 70%)",
      }}
    >
      <Text
        size="xs"
        fw={700}
        tt="uppercase"
        c="edr-green"
        mb="md"
        style={{ letterSpacing: "0.06em" }}
      >
        Pricing schedule
      </Text>
      <Box mb="md">
        <NotFinalPriceNotice />
      </Box>
      <Stack gap={10}>
        {lineItems.map((item) => (
          <Group
            key={item.code}
            justify="space-between"
            align="flex-start"
            wrap="nowrap"
            gap="sm"
          >
            <Box style={{ minWidth: 0 }}>
              <Text size="sm" c="#10202F" fw={500}>
                {item.label}
              </Text>
              {item.containerSize && (
                <Text size="xs" c="dimmed">
                  {item.containerSize}
                </Text>
              )}
            </Box>
            <Text
              size="sm"
              fw={700}
              c="#10202F"
              style={{ whiteSpace: "nowrap" }}
            >
              {item.unitPrice.toLocaleString()} {currency}{" "}
              <Text span fz={12} fw={600} c="edr-muted">
                / {formatRateUnit(item.unit)}
              </Text>
            </Text>
          </Group>
        ))}
        {lineItems.length === 0 && (
          <Text size="sm" c="dimmed">
            No unit rates returned. Generate the quotation to see your pricing
            schedule.
          </Text>
        )}
      </Stack>
    </Paper>
  );
}

export function Step8Review({
  form,
  direction,
  referenceData,
  pricing,
  onSaveDraft,
  onSubmit,
  saveDraftPending = false,
  submitPending = false,
  documentsEditor,
  isEdit = false,
}: {
  form: ContractForm;
  /** Retained for caller compatibility; the review page is read-only. */
  setStep?: (step: number) => void;
  direction: Freight.ScheduleTradeDirection;
  referenceData?: Freight.BookingReferenceData;
  /** Unit-rate quotation, if the customer has already generated price. */
  pricing?: { currency: string; lineItems: Freight.ContractUnitRateLineItem[] } | null;
  onSaveDraft?: () => void;
  onSubmit?: () => void;
  saveDraftPending?: boolean;
  submitPending?: boolean;
  /**
   * Document replace/upload block, shown only when editing an existing contract
   * (resubmit after CHANGES_REQUESTED). Omitted for fresh creation, where docs
   * come from the company profile automatically.
   */
  documentsEditor?: React.ReactNode;
  /** Editing an existing contract (resubmit) rather than creating a new one. */
  isEdit?: boolean;
}) {
  const values = form.watch();
  const serviceType = referenceData?.service.find(
    (s) => s.id === values.serviceTypeId,
  );

  const isGeneralContract = values.contractKind === "general_contract";
  const isIntercity = values.operationType === "intercity";

  // Customs is a property of the chosen service (bundled → Global Logistics),
  // not of the stored form flag — a stale draft flag must not misreport it.
  // Without bundling, the customer may still name their own clearing agent.
  const ownAgent = values.customsClearingAgent?.trim();
  const customsValue = isIntercity
    ? "Not applicable — domestic transport"
    : serviceType?.includesCustoms || values.customsClearingEnabled
      ? "Included — Global Logistics"
      : ownAgent
        ? `Own agent — ${ownAgent}`
        : "Not requested";

  // Mirror the step-2 gating: imports never truck the first mile, exports never
  // truck the last mile, and a service that doesn't bundle a mile can't have it.
  // A mile the customer didn't take is left off the summary entirely rather than
  // shown as an empty "not applicable" row.
  const firstMileValue =
    direction !== "IMPORT" &&
    (!serviceType || serviceType.includesFirstMile) &&
    values.firstMile.enabled
      ? `${values.firstMile.pickUpAddress || "Pinned"}${
          values.firstMile.exactLocation
            ? ` · ${values.firstMile.exactLocation}`
            : ""
        }`
      : null;
  const lastMileValue =
    direction !== "EXPORT" &&
    (!serviceType || serviceType.includesLastMile) &&
    values.lastMile.enabled
      ? `${values.lastMile.deliveryAddress || "Pinned"}${
          values.lastMile.exactLocation
            ? ` · ${values.lastMile.exactLocation}`
            : ""
        }`
      : null;

  const cargoValue = (() => {
    if (values.cargoType === "container") {
      const sizes = (values.enabledContainerSizes ?? []).join(", ");
      return sizes ? `Container — ${sizes}` : "Container freight";
    }
    if (!referenceData) return "";
    const path = values.cargoTypePath ?? [];
    const group = referenceData.cargo_type.find((g) => g.id === path[0]);
    if (!group) return "";
    const child = group.children?.find((c) => c.id === path[1]);
    return child ? `${group.name} — ${child.name}` : group.name;
  })();

  const originYardName =
    referenceData?.yard.find((y) => y.id === values.originYard)?.name ??
    values.originYard;
  const destinationYardName =
    referenceData?.yard.find((y) => y.id === values.destinationYard)?.name ??
    values.destinationYard;

  const directionLabel = direction
    ? direction.charAt(0) + direction.slice(1).toLowerCase()
    : "—";

  return (
    <Stack gap="lg">
      <StepHeader
        icon={<ClipboardCheck size={22} />}
        title="Review & Submit"
        description="Review your contract overview and unit-rate quotation before sending it for EDR staff review."
      />

      <div className="flex flex-col gap-6 lg:flex-row lg:items-start">
        {/* Left — one scannable summary card */}
        <Stack gap="md" className="min-w-0 flex-1">
          <Paper
            radius={18}
            withBorder
            style={{
              borderColor: "var(--mantine-color-edr-border-0)",
              overflow: "hidden",
            }}
          >
            {/* Header strip */}
            <Group
              justify="space-between"
              align="center"
              wrap="nowrap"
              px="lg"
              py="md"
              style={{
                background: "linear-gradient(135deg, #F4FBF7 0%, #FFFFFF 70%)",
                borderBottom: "1px solid var(--mantine-color-edr-border-0)",
              }}
            >
              <Box style={{ minWidth: 0 }}>
                <Text fw={800} fz={16} c="#10202F" truncate>
                  {isGeneralContract ? "General Contract" : "One-Time Contract"}
                </Text>
                <Text fz={12.5} c="dimmed" truncate>
                  {serviceType?.serviceName ?? "—"} · {originYardName} →{" "}
                  {destinationYardName}
                </Text>
              </Box>
              <Badge
                size="md"
                variant="light"
                color="edr-green"
                radius="md"
                style={{ flexShrink: 0 }}
              >
                {directionLabel}
              </Badge>
            </Group>

            {/* Detail grid — read-only, every field shown */}
            <Box p="lg" className="grid gap-x-6 gap-y-5 sm:grid-cols-2">
              <SummaryItem
                icon={<Package size={18} />}
                label="Contract kind"
                value={isGeneralContract ? "General Contract" : "One-Time"}
              />
              <SummaryItem
                icon={<FileText size={18} />}
                label="Contract type"
                value={
                  values.contractType === "new"
                    ? "New contract"
                    : values.previousContractRef
                      ? `Renewal · ${values.previousContractRef}`
                      : "Renewal"
                }
              />
              <SummaryItem
                icon={<Truck size={18} />}
                label="Service"
                value={serviceType?.serviceName ?? "—"}
              />
              <SummaryItem
                icon={<Coins size={18} />}
                label="Quotation currency"
                value={
                  <>
                    USD
                    <Text fz="sm" c="dimmed" mt={4}>
                      You choose the billing currency on each shipment.
                    </Text>
                  </>
                }
              />
              <SummaryItem
                icon={<Route size={18} />}
                label="Route"
                value={`${originYardName} → ${destinationYardName}`}
              />
              <SummaryItem
                icon={<MapPin size={18} />}
                label="Trade direction"
                value={directionLabel}
              />
              <SummaryItem
                icon={<Package size={18} />}
                label="Cargo scope"
                value={
                  <>
                    {cargoValue || "—"}
                    {values.cargoFreeText?.trim() && (
                      <Text fz="sm" c="dimmed" mt={4}>
                        {values.cargoFreeText}
                      </Text>
                    )}
                    {values.cargoType === "container" &&
                      (values.enabledContainerSizes ?? []).length > 0 && (
                        <Group gap={6} mt={6}>
                          {(values.enabledContainerSizes ?? []).map((s) => (
                            <Badge
                              key={s}
                              size="sm"
                              variant="light"
                              color="edr-green"
                              radius="sm"
                            >
                              {s}
                            </Badge>
                          ))}
                        </Group>
                      )}
                  </>
                }
              />
              {firstMileValue && (
                <SummaryItem
                  icon={<Truck size={18} />}
                  label="First mile — pick-up"
                  value={firstMileValue}
                />
              )}
              {lastMileValue && (
                <SummaryItem
                  icon={<Truck size={18} />}
                  label="Last mile — delivery"
                  value={lastMileValue}
                />
              )}
              <SummaryItem
                icon={<FileText size={18} />}
                label="Customs clearing"
                value={customsValue}
              />
              <SummaryItem
                icon={<Package size={18} />}
                label="Hazardous cargo"
                value={
                  values.isHazardous ? (
                    <>
                      Yes
                      <Group gap={6} mt={6}>
                        <Badge size="sm" variant="light" color="red" radius="sm">
                          {hazardClassLabel(values.hazardClass) ?? "Class —"}
                        </Badge>
                        <Badge size="sm" variant="light" color="red" radius="sm">
                          UN {values.unNumber || "—"}
                        </Badge>
                      </Group>
                    </>
                  ) : (
                    "No"
                  )
                }
              />
              <SummaryItem
                icon={<Package size={18} />}
                label="Refrigerated"
                value={values.isRefrigerated ? "Yes" : "No"}
              />
              {values.cargoType === "container" && (
                <SummaryItem
                  icon={<RotateCcw size={18} />}
                  label="Empty-container return"
                  value={
                    values.equipmentReturn === "with_return"
                      ? "With return"
                      : "Without return"
                  }
                />
              )}
            </Box>
          </Paper>

          {pricing && (
            <UnitRatePanel
              currency={pricing.currency}
              lineItems={pricing.lineItems}
            />
          )}

          {documentsEditor && (
            <Paper
              radius={18}
              p="lg"
              withBorder
              style={{ borderColor: "var(--mantine-color-edr-border-0)" }}
            >
              {documentsEditor}
            </Paper>
          )}

          <Controller
            name="notes"
            control={form.control}
            render={({ field }) => (
              <Textarea
                {...field}
                label="Additional notes"
                placeholder="Any special instructions for EDR operations…"
                rows={3}
                radius="md"
              />
            )}
          />
        </Stack>

        {/* Right — sticky actions */}
        <Box className="w-full shrink-0 lg:w-[340px] lg:sticky lg:top-24">
          <Stack gap="md">
            <Paper radius={20} p="lg" withBorder bg="white">
              <Text fw={800} size="sm" mb="md" c="#10202F">
                Submission readiness
              </Text>
              <Stack gap="sm">
                <ReadinessItem
                  done={Boolean(values.serviceTypeId)}
                  label="Service configured"
                />
                <ReadinessItem
                  done={Boolean(values.originYard && values.destinationYard)}
                  label="Route selected"
                />
                <ReadinessItem
                  done={
                    values.cargoType === "container"
                      ? (values.enabledContainerSizes ?? []).length > 0
                      : Boolean(values.cargoTypePath?.[1])
                  }
                  label="Cargo scope complete"
                />
              </Stack>
            </Paper>

            <Paper radius={20} p="lg" withBorder bg="white">
              <Text size="sm" c="dimmed" mb="md">
                {isEdit
                  ? pricing
                    ? "Review your updated unit-rate quotation. Approve to resubmit the contract for EDR staff review."
                    : "Ready to resubmit. You'll review the unit-rate quotation before final resubmission."
                  : pricing
                    ? "Review your unit-rate quotation. Approve to submit the contract for EDR staff review."
                    : "Ready to submit. You'll review the unit-rate quotation before final submission."}
              </Text>
              <Stack gap="sm">
                <Button
                  type="button"
                  color="edr-green"
                  radius="md"
                  fullWidth
                  size="md"
                  leftSection={<Send size={16} />}
                  onClick={onSubmit}
                  loading={submitPending}
                  disabled={submitPending}
                >
                  {isEdit
                    ? pricing
                      ? "Approve quotation & resubmit"
                      : "Resubmit"
                    : pricing
                      ? "Approve quotation & submit"
                      : "Submit"}
                </Button>
                {!isEdit && (
                  <Button
                    type="button"
                    variant="outline"
                    color="edr-green"
                    radius="md"
                    fullWidth
                    onClick={onSaveDraft}
                    loading={saveDraftPending}
                    disabled={submitPending}
                  >
                    Save as draft
                  </Button>
                )}
              </Stack>
            </Paper>
          </Stack>
        </Box>
      </div>
    </Stack>
  );
}
