"use client";

import { isApiSuccess } from "@/lib/api-messages";
import Link from "next/link";
import { useMemo, useState } from "react";

import { useRouter } from "next/navigation";
import { zodResolver } from "@hookform/resolvers/zod";
import { Globe, Plus } from "lucide-react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";

import { FormPageHeader, FormSaveBar } from "@/app/dashboard/_components/form";
import { FormField } from "@/components/form/form-field";
import { FormSection } from "@/app/dashboard/customers/_components/customer-form/form-section";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ErrorBanner } from "@/components/shared/error-banner";
import { requestDashboardApi } from "@/lib/dashboard-api-client";

import { MasterTableDateField } from "../../../_components/master-table-date-field";
import type { StructureMasterDetails, StructureMasterRow } from "../schema";
import { buildStructureFormValues, getStructureFormInitialValues } from "./defaults";
import { StructureCouponTable, StructureObservationTable } from "./structure-child-tables";
import { structureFormSchema, type StructureFormValues } from "./schema";

const LIST_HREF = "/dashboard/master-table/structure-master";
const CREATE_HREF = "/dashboard/master-table/structure-master/create";
const UPDATE_HREF = "/dashboard/master-table/structure-master/update";

type Props = {
  recordId?: number;
  prefillIsin?: string;
  initialRecord?: { row: StructureMasterRow; details?: StructureMasterDetails };
  loadError?: string;
};

export function StructureCreateForm({ recordId, prefillIsin, initialRecord, loadError }: Props) {
  const router = useRouter();
  const isUpdate = Boolean(recordId);
  const [isSaving, setIsSaving] = useState(false);

  const initialValues = useMemo(
    () =>
      initialRecord
        ? buildStructureFormValues(initialRecord.row, initialRecord.details)
        : getStructureFormInitialValues(prefillIsin),
    [initialRecord, prefillIsin],
  );

  const form = useForm<StructureFormValues>({
    resolver: zodResolver(structureFormSchema),
    defaultValues: initialValues,
  });

  const errors = form.formState.errors;
  const values = form.watch();
  const observationDateValues = values.observationDates?.map((row) => row.date) ?? [];
  const couponDateValues = values.couponDates?.map((row) => row.date) ?? [];

  const onSubmit = async (submittedValues: StructureFormValues) => {
    setIsSaving(true);
    try {
      await requestDashboardApi<{ status?: string; message?: string }>({
        url: UPDATE_HREF,
        method: "POST",
        body: { recordId, values: submittedValues },
        fallbackError: isUpdate
          ? "Could not update structure master record."
          : "Could not create structure master record.",
        validate: (payload) => isApiSuccess(payload),
      });
      toast.success(isUpdate ? "Structure updated." : "Structure created.");
      router.push(LIST_HREF);
    } catch (error) {
      toast.error(
        error instanceof Error
          ? error.message
          : "Could not save structure master record.",
      );
    } finally {
      setIsSaving(false);
    }
  };

  const firstObservationLabel = values.firstObservationDate
    ? new Date(`${values.firstObservationDate}T12:00:00`).toLocaleDateString("en-GB", {
        day: "2-digit",
        month: "2-digit",
        year: "numeric",
      })
    : null;

  return (
    <form onSubmit={form.handleSubmit(onSubmit)} className="m-8 flex flex-col">
      <FormPageHeader
        backHref={LIST_HREF}
        breadcrumb={[
          { label: "Master Table", href: LIST_HREF },
          { label: "Structure master", href: LIST_HREF },
          { label: isUpdate ? "Update" : "Create new" },
        ]}
        titleIcon={<Globe className="size-4 text-primary" />}
        title={isUpdate ? "Update structure master" : "Create new structure master"}
        description="Structured product master with coupon and observation child dates."
        meta={
          isUpdate ? (
            <Button size="sm" className="gap-1.5" asChild>
              <Link href={CREATE_HREF}>
                <Plus className="size-4" />
                Create new
              </Link>
            </Button>
          ) : null
        }
      />

      <ErrorBanner message={loadError} className="mb-4" />

      <div className="space-y-6">
        <FormSection title="Identification">
          <div className="grid gap-4 md:grid-cols-2">
            <FormField label="ISIN" htmlFor="isin" required error={errors.isin}>
              <Input
                id="isin"
                className="h-9 font-mono"
                placeholder="e.g. XSCH12345678"
                {...form.register("isin")}
              />
            </FormField>
            <FormField label="Name" htmlFor="name" error={errors.name}>
              <Input id="name" className="h-9" {...form.register("name")} />
            </FormField>
          </div>
        </FormSection>

        <FormSection title="Terms">
          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
            <FormField label="Coupon" htmlFor="coupon" error={errors.coupon}>
              <Input id="coupon" className="h-9" placeholder="e.g. 8.50%" {...form.register("coupon")} />
            </FormField>
            <MasterTableDateField
              control={form.control}
              name="expiry"
              label="Expiry"
              htmlFor="expiry"
            />
            <div className="space-y-1.5">
              {firstObservationLabel ? (
                <p className="text-primary text-xs">
                  <strong>First observation:</strong> {firstObservationLabel}
                </p>
              ) : null}
              <MasterTableDateField
                control={form.control}
                name="observations"
                label="Observations"
                htmlFor="observations"
              />
            </div>
            <FormField label="KO barrier" htmlFor="koBarrier" error={errors.koBarrier}>
              <Input id="koBarrier" className="h-9" {...form.register("koBarrier")} />
            </FormField>
          </div>
        </FormSection>

        <FormSection title="Product">
          <div className="grid gap-4 md:grid-cols-2">
            <FormField label="Product type" htmlFor="productType" error={errors.productType}>
              <Input id="productType" className="h-9" {...form.register("productType")} />
            </FormField>
            <FormField label="Non call period" htmlFor="nonCallPeriod" error={errors.nonCallPeriod}>
              <Input id="nonCallPeriod" className="h-9" {...form.register("nonCallPeriod")} />
            </FormField>
          </div>
          <div className="grid gap-4 md:grid-cols-2">
            <FormField label="Strike" htmlFor="strike" error={errors.strike}>
              <Input id="strike" className="h-9" {...form.register("strike")} />
            </FormField>
            <FormField label="Issuer" htmlFor="issuer" error={errors.issuer}>
              <Input id="issuer" className="h-9" {...form.register("issuer")} />
            </FormField>
          </div>
        </FormSection>

        <FormSection title="Settlement & valuation dates">
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            <FormField
              label="Settlement date"
              htmlFor="settlementDate"
              error={errors.settlementDate}
            >
              <Input id="settlementDate" className="h-9" {...form.register("settlementDate")} />
            </FormField>
            <FormField label="Trade date" htmlFor="tradeDate" error={errors.tradeDate}>
              <Input id="tradeDate" className="h-9" {...form.register("tradeDate")} />
            </FormField>
            <FormField
              label="Final valuation date"
              htmlFor="finalValuationDate"
              error={errors.finalValuationDate}
            >
              <Input
                id="finalValuationDate"
                className="h-9"
                {...form.register("finalValuationDate")}
              />
            </FormField>
          </div>
        </FormSection>

        <FormSection title="Underlyings">
          <div className="space-y-4">
            {values.underlyings.map((_, index) => (
              <div
                key={index}
                className="grid gap-3 rounded-lg border border-dashed p-3 md:grid-cols-4"
              >
                <p className="col-span-full font-medium text-muted-foreground text-xs">
                  Underlying {index + 1}
                </p>
                <FormField
                  label="ISIN"
                  htmlFor={`underlying${index}_isin`}
                  error={errors.underlyings?.[index]?.isin}
                >
                  <Input
                    id={`underlying${index}_isin`}
                    className="h-9 font-mono text-xs"
                    {...form.register(`underlyings.${index}.isin`)}
                  />
                </FormField>
                <FormField
                  label="Name"
                  htmlFor={`underlying${index}_name`}
                  error={errors.underlyings?.[index]?.name}
                >
                  <Input
                    id={`underlying${index}_name`}
                    className="h-9"
                    {...form.register(`underlyings.${index}.name`)}
                  />
                </FormField>
                <FormField
                  label="Currency"
                  htmlFor={`underlying${index}_currency`}
                  error={errors.underlyings?.[index]?.currency}
                >
                  <Input
                    id={`underlying${index}_currency`}
                    className="h-9"
                    {...form.register(`underlyings.${index}.currency`)}
                  />
                </FormField>
                <FormField
                  label="Spot"
                  htmlFor={`underlying${index}_spot`}
                  error={errors.underlyings?.[index]?.spot}
                >
                  <Input
                    id={`underlying${index}_spot`}
                    className="h-9"
                    {...form.register(`underlyings.${index}.spot`)}
                  />
                </FormField>
              </div>
            ))}
          </div>
        </FormSection>

        <FormSection title="Child date tables">
          <div className="space-y-8">
            <StructureObservationTable
              control={form.control}
              register={form.register}
              dates={observationDateValues}
            />
            <StructureCouponTable
              control={form.control}
              register={form.register}
              dates={couponDateValues}
            />
          </div>
        </FormSection>
      </div>

      <FormSaveBar
        cancelHref={LIST_HREF}
        cancelLabel="Cancel"
        saveLabel="Save changes"
        isSaving={isSaving}
        onReset={() => form.reset(initialValues)}
      />
    </form>
  );
}
