"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 { AccumulatorMasterDetails, AccumulatorMasterRow } from "../schema";
import { AccumulatorChildTable } from "./accumulator-child-table";
import { buildAccumulatorFormValues, getAccumulatorFormInitialValues } from "./defaults";
import { accumulatorFormSchema, type AccumulatorFormValues } from "./schema";

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

type Props = {
  recordId?: string;
  prefillIsin?: string;
  initialRecord?: { row: AccumulatorMasterRow; details?: AccumulatorMasterDetails };
  loadError?: string;
};

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

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

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

  const errors = form.formState.errors;

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

  return (
    <form onSubmit={form.handleSubmit(onSubmit)} className="m-8 flex flex-col">
      <FormPageHeader
        backHref={LIST_HREF}
        breadcrumb={[
          { label: "Master Table", href: LIST_HREF },
          { label: "Accumulator master", href: LIST_HREF },
          { label: isUpdate ? "Update" : "Create new" },
        ]}
        titleIcon={<Globe className="size-4 text-primary" />}
        title={isUpdate ? "Update accumulator master" : "Create new accumulator master"}
        description="Parent accumulator with child period schedule (accumulator_child)."
        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. ACU_CH_2026_001"
                {...form.register("isin")}
              />
            </FormField>
            <FormField label="Name" htmlFor="name" required error={errors.name}>
              <Input id="name" className="h-9" {...form.register("name")} />
            </FormField>
          </div>
        </FormSection>

        <FormSection title="Schedule">
          <div className="grid gap-4 md:grid-cols-3">
            <MasterTableDateField
              control={form.control}
              name="observationDates"
              label="Observation dates"
              htmlFor="observationDates"
            />
            <FormField label="Periods" htmlFor="periods" required error={errors.periods}>
              <Input id="periods" className="h-9" {...form.register("periods")} />
            </FormField>
            <FormField label="Frequency" htmlFor="frequency" required error={errors.frequency}>
              <Input
                id="frequency"
                className="h-9"
                placeholder="e.g. weekly, monthly"
                {...form.register("frequency")}
              />
            </FormField>
          </div>
          <div className="grid gap-4 md:grid-cols-2">
            <FormField
              label="Leverage factor"
              htmlFor="leverageFactor"
              error={errors.leverageFactor}
            >
              <Input id="leverageFactor" className="h-9" {...form.register("leverageFactor")} />
            </FormField>
            <FormField
              label="Shares per period"
              htmlFor="shsPerPeriod"
              error={errors.shsPerPeriod}
            >
              <Input id="shsPerPeriod" className="h-9" {...form.register("shsPerPeriod")} />
            </FormField>
          </div>
          <div className="grid gap-4 md:grid-cols-3">
            <MasterTableDateField
              control={form.control}
              name="start"
              label="Start date"
              htmlFor="start"
              required
            />
            <FormField label="Quantity" htmlFor="quantity" required error={errors.quantity}>
              <Input id="quantity" className="h-9" {...form.register("quantity")} />
            </FormField>
            <FormField label="Strike" htmlFor="strike" required error={errors.strike}>
              <Input id="strike" className="h-9" {...form.register("strike")} />
            </FormField>
          </div>
        </FormSection>

        <FormSection title="Pricing">
          <div className="grid gap-4 md:grid-cols-3">
            <FormField label="Spot" htmlFor="spot" error={errors.spot}>
              <Input id="spot" className="h-9" {...form.register("spot")} />
            </FormField>
            <FormField label="Profit taking" htmlFor="profitTaking" error={errors.profitTaking}>
              <Input id="profitTaking" className="h-9" {...form.register("profitTaking")} />
            </FormField>
            <FormField label="Knock" htmlFor="knock" error={errors.knock}>
              <Input id="knock" className="h-9" {...form.register("knock")} />
            </FormField>
          </div>
        </FormSection>

        <FormSection title="Underlying">
          <div className="grid gap-4 md:grid-cols-2">
            <FormField
              label="Underlying ISIN"
              htmlFor="underlyingIsin"
              required
              error={errors.underlyingIsin}
            >
              <Input
                id="underlyingIsin"
                className="h-9 font-mono"
                {...form.register("underlyingIsin")}
              />
            </FormField>
            <FormField
              label="Underlying name"
              htmlFor="underlyingName"
              required
              error={errors.underlyingName}
            >
              <Input id="underlyingName" className="h-9" {...form.register("underlyingName")} />
            </FormField>
          </div>
          <FormField label="TARF CCY ISIN" htmlFor="tarfCcyIsin" error={errors.tarfCcyIsin}>
            <Input id="tarfCcyIsin" className="h-9 max-w-sm" {...form.register("tarfCcyIsin")} />
          </FormField>
        </FormSection>

        <FormSection title="Child records">
          <AccumulatorChildTable control={form.control} register={form.register} />
        </FormSection>
      </div>

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