import { Anchor, Box, Divider, Group, Text } from "@mantine/core";
import { FileText, Link2 } from "lucide-react";
import type { ReactNode } from "react";
import { Link } from "react-router-dom";

import type { BookingDetail } from "../booking-detail-types";
import { fmtDate } from "../utils";
import { CardTitle, SectionCard } from "./layout";

function Field({ label, value }: { label: string; value: ReactNode }) {
  return (
    <Box miw={0} flex={1}>
      <Text fz="11.5px" fw={600} c="#9AA8B5">
        {label}
      </Text>
      <Text mt={4} fz="14px" fw={700} c="#10202F">
        {value}
      </Text>
    </Box>
  );
}

function Row({ children }: { children: ReactNode }) {
  return (
    <Group
      gap={24}
      align="flex-start"
      wrap="nowrap"
      py={13}
      style={{ borderBottom: "1px solid #F2F5F8" }}
    >
      {children}
    </Group>
  );
}

/**
 * Contract terms for this booking — validity window, financial terms,
 * customs/currency, renewal chain — none of which the detail page surfaced
 * before even though the booking always carries them.
 */
export function ContractInfoCard({ booking }: { booking: BookingDetail }) {
  const isGeneralContract = booking.bookingType === "GENERAL_CONTRACT";
  const hasValidity = booking.contractValidFrom || booking.contractValidUntil;

  return (
    <SectionCard>
      <Group justify="space-between" align="center" mb={4}>
        <CardTitle>Contract Information</CardTitle>
        {booking.contractId && (
          <Anchor
            component={Link}
            to={`/contracts/${booking.contractId}`}
            fz="12.5px"
            fw={700}
            underline="hover"
          >
            View full contract →
          </Anchor>
        )}
      </Group>

      <Box>
        <Row>
          <Field
            label="Contract reference"
            value={
              booking.contractId ? (
                <Anchor
                  component={Link}
                  to={`/contracts/${booking.contractId}`}
                  fz="14px"
                  fw={700}
                  underline="hover"
                >
                  {booking.contractReference ?? booking.reference}
                </Anchor>
              ) : (
                (booking.contractReference ?? booking.reference)
              )
            }
          />
          <Field
            label="Contract type"
            value={booking.contractType === "RENEWAL" ? "Renewal" : "New"}
          />
        </Row>

        <Row>
          <Field
            label="Order type"
            value={isGeneralContract ? "General Contract" : "One-Time Booking"}
          />
          <Field label="Payment currency" value={booking.paymentCurrency || "—"} />
        </Row>

        {hasValidity && (
          <Row>
            <Field label="Valid from" value={fmtDate(booking.contractValidFrom)} />
            <Field
              label={
                booking.contractValidityDays
                  ? `Valid until (${booking.contractValidityDays} days)`
                  : "Valid until"
              }
              value={fmtDate(booking.contractValidUntil)}
            />
          </Row>
        )}

        {isGeneralContract && (booking.startDate || booking.endDate) && (
          <Row>
            <Field label="Service start" value={fmtDate(booking.startDate)} />
            <Field label="Service end" value={fmtDate(booking.endDate)} />
          </Row>
        )}

        {isGeneralContract && booking.expiresAt && (
          <Row>
            <Field label="Ordering window closes" value={fmtDate(booking.expiresAt)} />
            <Field label="Version" value={`v${booking.versionNumber ?? 1}`} />
          </Row>
        )}

        {booking.customsClearingEnabled && (
          <Row>
            <Field label="Customs clearance" value="Enabled" />
            <Field
              label="Clearing agent"
              value={booking.customsClearingAgent || "Assigned by Global Logistics"}
            />
          </Row>
        )}

        {booking.previousContractId && (
          <Row>
            <Field
              label="Renewed from"
              value={
                <Anchor
                  component={Link}
                  to={`/contracts/${booking.previousContractId}`}
                  fz="14px"
                  fw={700}
                  underline="hover"
                >
                  <Group gap={4} wrap="nowrap">
                    <Link2 size={13} />
                    Previous contract
                  </Group>
                </Anchor>
              }
            />
            <Field
              label="Consolidation"
              value={
                booking.consolidationPartner
                  ? `Paired with ${booking.consolidationPartner.reference}`
                  : booking.consolidationPartnerId
                    ? "Paired"
                    : "Not consolidated"
              }
            />
          </Row>
        )}
      </Box>

      {booking.financialTerms && (
        <>
          <Divider my={10} color="#F2F5F8" />
          <Text fz="11.5px" fw={600} c="#9AA8B5" mb={6}>
            Financial terms
          </Text>
          <Text fz="13px" c="#10202F" style={{ whiteSpace: "pre-wrap" }}>
            {booking.financialTerms}
          </Text>
        </>
      )}

      {booking.contractSummary && (
        <>
          <Divider my={10} color="#F2F5F8" />
          <Group gap={6} align="center" mb={6}>
            <FileText size={13} color="#9AA8B5" />
            <Text fz="11.5px" fw={600} c="#9AA8B5">
              Contract summary
            </Text>
          </Group>
          <Text fz="13px" c="#10202F" style={{ whiteSpace: "pre-wrap" }}>
            {booking.contractSummary}
          </Text>
        </>
      )}
    </SectionCard>
  );
}
