import { Controller, type UseFormReturn } from "react-hook-form";
import { Check } from "lucide-react";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  Field,
  FieldError,
  FieldLabel,
  Textarea,
} from "@edr/ui-common";
import {
  BookingFormInputValues,
  type BookingFormValues,
  type RouteDirection,
} from "./schema";
import { StepHeader } from "./shared";

type BookingForm = UseFormReturn<
  BookingFormInputValues,
  any,
  BookingFormValues
>;

export function Step8Review({
  form,
  setStep,
  direction,
}: {
  form: BookingForm;
  setStep: (step: number) => void;
  direction: RouteDirection;
}) {
  const values = form.watch();
  const errors = form.formState.errors;

  function Row({
    label,
    value,
    target,
  }: {
    label: string;
    value: string;
    target: number;
  }) {
    return (
      <div className="flex items-start justify-between gap-4 py-2">
        <div className="min-w-0">
          <p className="text-xs text-muted-foreground">{label}</p>
          <p className="mt-0.5 truncate text-sm font-medium">{value || "-"}</p>
        </div>
        <button
          type="button"
          onClick={() => setStep(target)}
          className="shrink-0 text-xs font-medium text-primary hover:underline"
        >
          Edit
        </button>
      </div>
    );
  }

  const containerSummary =
    values.cargoType === "container" && values.containers.length > 0
      ? values.containers
        .filter((c) => +c.qty > 0)
        .map((c) => `${c.qty} × ${c.type}`)
        .join(", ")
      : "";
  const totalVgm =
    values.cargoType === "container"
      ? values.containers.reduce(
        (sum, c) => sum + (+c.qty || 0) * (+c.vgm || 0),
        0,
      )
      : 0;

  const cargoValue =
    values.cargoType === "container"
      ? containerSummary
      : values.freightType === "bulk"
        ? `Bulk - ${values.bulkCommodity === "Others" ? values.bulkCommodityOther : values.bulkCommodity}`
        : values.freightType === "break_bulk"
          ? `Break-Bulk - ${values.breakBulkType === "Others" ? values.breakBulkTypeOther : values.breakBulkType}`
          : "";
  return (
    <div className="space-y-6">
      <StepHeader
        title="Review & Submit"
        description="Confirm your contract request before sending it for EDR staff review."
      />

      <div className="grid gap-4 md:grid-cols-2">
        <Card className="gap-0 overflow-hidden py-0">
          <CardHeader className="border-b px-5 py-3!">
            <CardTitle className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
              Contract & Service
            </CardTitle>
          </CardHeader>
          <CardContent className="divide-y divide-border px-5 pb-2 pt-0">
            <Row
              label="Type"
              value={values.contractType === "new" ? "New Contract" : "Renewal"}
              target={1}
            />
            <Row
              label="Service"
              value={
                values.serviceType === "rail"
                  ? "Rail Only"
                  : values.serviceType === "rail_forwarding"
                    ? "Rail + Forwarding"
                    : ""
              }
              target={2}
            />
          </CardContent>
        </Card>

        <Card className="gap-0 overflow-hidden py-0">
          <CardHeader className="border-b px-5 py-3!">
            <CardTitle className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
              First & Last Mile
            </CardTitle>
          </CardHeader>
          <CardContent className="divide-y divide-border px-5 pb-2 pt-0">
            <Row
              label="First Mile"
              value={
                values.firstMile.enabled
                  ? values.firstMile.pickUpAddress
                  : "Not requested"
              }
              target={2}
            />
            <Row
              label="Last Mile"
              value={
                values.lastMile.enabled
                  ? values.lastMile.deliveryAddress
                  : "Not requested"
              }
              target={2}
            />
            <Row
              label="Equipment Return"
              value={
                values.equipmentReturn === "with_return"
                  ? "With Return"
                  : "Without Return"
              }
              target={2}
            />
            <Row
              label="Customs Clearing"
              value={
                values.customsClearingEnabled ? "Enabled" : "Not requested"
              }
              target={2}
            />
          </CardContent>
        </Card>

        <Card className="gap-0 overflow-hidden py-0">
          <CardHeader className="border-b px-5 py-3!">
            <CardTitle className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
              Route & Cargo
            </CardTitle>
          </CardHeader>
          <CardContent className="divide-y divide-border px-5 pb-2 pt-0">
            <Row
              label="Route"
              value={`${values.originYard} -> ${values.destinationYard}`}
              target={3}
            />
            <Row
              label="Workflow"
              value={
                direction
                  ? direction.charAt(0).toUpperCase() + direction.slice(1)
                  : ""
              }
              target={3}
            />
            <Row
              label="Weight (VGM)"
              value={values.cargoWeight ? `${values.cargoWeight} tons` : ""}
              target={4}
            />
            <Row label="Cargo" value={cargoValue} target={4} />
            <Row
              label="Modifiers"
              value={
                [
                  values.isHazardous && "Hazardous",
                  values.isRefrigerated && "Refrigerated",
                ]
                  .filter(Boolean)
                  .join(", ") || "None"
              }
              target={3}
            />
          </CardContent>
        </Card>

        <Card className="gap-0 overflow-hidden py-0">
          <CardHeader className="border-b px-5 py-3!">
            <CardTitle className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
              Container & Wagons
            </CardTitle>
          </CardHeader>
          <CardContent className="divide-y divide-border px-5 pb-2 pt-0">
            <Row
              label="Containers"
              value={containerSummary || "-"}
              target={4}
            />
            <Row
              label="Total VGM"
              value={totalVgm > 0 ? `${totalVgm.toFixed(1)} tons` : ""}
              target={4}
            />
          </CardContent>
        </Card>
      </div>

      <Controller
        name="notes"
        control={form.control}
        render={({ field }) => (
          <Field>
            <FieldLabel htmlFor="notes">Additional Notes</FieldLabel>
            <Textarea
              {...field}
              id="notes"
              placeholder="Any special instructions or notes for EDR operations..."
              rows={3}
            />
          </Field>
        )}
      />

      <Controller
        name="termsAccepted"
        control={form.control}
        render={({ field, fieldState }) => (
          <Field data-invalid={fieldState.invalid}>
            <label className="flex cursor-pointer items-start gap-3">
              <button
                type="button"
                role="checkbox"
                aria-checked={field.value}
                aria-invalid={fieldState.invalid}
                onClick={() => field.onChange(!field.value)}
                className={`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded border-2 transition ${field.value ? "border-primary bg-primary" : "border-input"
                  }`}
              >
                {field.value && (
                  <Check className="h-3 w-3 text-primary-foreground" />
                )}
              </button>
              <span className="text-sm text-muted-foreground">
                I confirm the information is accurate and agree to EDR's{" "}
                <span className="text-primary">
                  freight contract terms and conditions
                </span>
                .
              </span>
            </label>
            <FieldError errors={[fieldState.error, errors.termsAccepted]} />
          </Field>
        )}
      />
    </div>
  );
}
