"use client";

import { isApiSuccess } from "@/lib/api-messages";
import { toastApiError } from "@/lib/toast-api-error";
import { useEffect, useMemo, useState } from "react";

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

import {
  FormPageHeader,
  FormPanel,
  FormSaveBar,
  FormSelect,
} from "@/app/dashboard/_components/form";
import { FormField } from "@/components/form/form-field";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Input } from "@/components/ui/input";
import { Separator } from "@/components/ui/separator";
import { requestDashboardApi } from "@/lib/dashboard-api-client";

import { LIST_HREF } from "../constants";
import { MasterTableDateField } from "../../../_components/master-table-date-field";
import {
  marketPriceFormDefaults,
  marketPriceFormSchema,
  type MarketPriceFormValues,
} from "./schema";

const BASE_ASSET_CLASS_OPTIONS = [
  { value: "Stock", label: "Stock" },
  { value: "Bond", label: "Bond" },
  { value: "BondFund", label: "Bond Fund" },
  { value: "Commodity", label: "Commodity" },
];

const SUBMIT_HREF = "/dashboard/master-table/missing-market-price-isin/create/submit";

type Props = {
  initialIsin?: string;
  initialBaseAssetClass?: MarketPriceFormValues["BaseAssetClass"];
  fTypeLabel?: string;
};

function todayIso() {
  return new Date().toISOString().slice(0, 10);
}

function buildDefaults(
  initialIsin?: string,
  initialBaseAssetClass?: MarketPriceFormValues["BaseAssetClass"],
): MarketPriceFormValues {
  return {
    ...marketPriceFormDefaults,
    ISIN: initialIsin ?? "",
    BaseAssetClass: initialBaseAssetClass ?? "Stock",
    marketPriceDate: todayIso(),
    dataUpdateDate: todayIso(),
  };
}

export function MarketPriceForm({
  initialIsin,
  initialBaseAssetClass,
  fTypeLabel,
}: Props) {
  const router = useRouter();
  const [isSaving, setIsSaving] = useState(false);

  const defaultValues = useMemo(
    () => buildDefaults(initialIsin, initialBaseAssetClass),
    [initialIsin, initialBaseAssetClass],
  );

  const form = useForm<MarketPriceFormValues>({
    resolver: zodResolver(marketPriceFormSchema),
    defaultValues,
  });

  useEffect(() => {
    form.reset(buildDefaults(initialIsin, initialBaseAssetClass));
  }, [initialIsin, initialBaseAssetClass, form]);

  const onSubmit = form.handleSubmit(async (values) => {
    setIsSaving(true);
    try {
      const data = await requestDashboardApi<{
        status?: string;
        message?: string;
      }>({
        url: SUBMIT_HREF,
        method: "POST",
        body: values,
        fallbackError: "Missing market price record could not be saved.",
        validate: (payload) => isApiSuccess(payload),
      });

      toast.success(data.message ?? "Record successfully saved");
      router.push(LIST_HREF);
    } catch (error) {
      toastApiError(error, "Missing market price record could not be saved.");
    } finally {
      setIsSaving(false);
    }
  });

  return (
    <form onSubmit={onSubmit} className="pb-4">
      <FormPageHeader
        backHref={LIST_HREF}
        breadcrumb={[
          { label: "Master Table" },
          { label: "Missing Market Price ISIN", href: LIST_HREF },
          { label: "Create asset market record" },
        ]}
        titleIcon={<ListOrdered className="size-5 text-primary" />}
        title="Create asset market record"
        description="Add market price for an ISIN missing from assetMasterUnique."
      />

      {initialIsin ? (
        <Alert className="mb-6 border-sky-200 bg-sky-50/80">
          <Info className="size-4 text-sky-700" />
          <AlertTitle className="text-sky-900">Missing market price</AlertTitle>
          <AlertDescription className="text-sky-900/90 text-sm">
            ISIN: <span className="font-mono font-medium">{initialIsin}</span>
            {fTypeLabel ? (
              <>
                {" "}
                · Type: <strong>{fTypeLabel}</strong>
              </>
            ) : null}
          </AlertDescription>
        </Alert>
      ) : null}

      <FormPanel title="Asset market record">
        <div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
          <Controller
            name="ISIN"
            control={form.control}
            render={({ field, fieldState }) => (
              <FormField label="ISIN" htmlFor="ISIN" required error={fieldState.error}>
                <Input
                  id="ISIN"
                  className="font-mono"
                  readOnly={Boolean(initialIsin)}
                  {...field}
                />
              </FormField>
            )}
          />

          <Controller
            name="BaseAssetClass"
            control={form.control}
            render={({ field, fieldState }) => (
              <FormField
                label="Base asset class"
                htmlFor="BaseAssetClass"
                required
                error={fieldState.error}
              >
                <FormSelect
                  id="BaseAssetClass"
                  value={field.value}
                  onChange={field.onChange}
                  placeholder="Select type"
                  options={BASE_ASSET_CLASS_OPTIONS}
                />
              </FormField>
            )}
          />
        </div>

        <div className="mt-5 grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
          <Controller
            name="MarketPrice"
            control={form.control}
            render={({ field, fieldState }) => (
              <FormField
                label="Market price"
                htmlFor="MarketPrice"
                required
                error={fieldState.error}
              >
                <Input id="MarketPrice" type="number" step="any" {...field} />
              </FormField>
            )}
          />

          <Controller
            name="marketPriceDate"
            control={form.control}
            render={({ field, fieldState }) => (
              <FormField
                label="Market price date"
                htmlFor="marketPriceDate"
                required
                description="YYYY-MM-DD"
                error={fieldState.error}
              >
                <Input
                  id="marketPriceDate"
                  placeholder="YYYY-MM-DD"
                  {...field}
                />
              </FormField>
            )}
          />

          <MasterTableDateField
            control={form.control}
            name="dataUpdateDate"
            label="Data update date"
            htmlFor="dataUpdateDate"
          />
        </div>

        <Separator className="my-8" />

        <h3 className="mb-5 font-semibold text-base">Only if not added</h3>

        <div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
          <Controller
            name="Name"
            control={form.control}
            render={({ field, fieldState }) => (
              <FormField label="Name" htmlFor="Name" error={fieldState.error}>
                <Input id="Name" {...field} />
              </FormField>
            )}
          />
          <Controller
            name="Sector"
            control={form.control}
            render={({ field, fieldState }) => (
              <FormField label="Sector" htmlFor="Sector" error={fieldState.error}>
                <Input id="Sector" {...field} />
              </FormField>
            )}
          />
          <Controller
            name="Industry"
            control={form.control}
            render={({ field, fieldState }) => (
              <FormField label="Industry" htmlFor="Industry" error={fieldState.error}>
                <Input id="Industry" {...field} />
              </FormField>
            )}
          />
        </div>

        <div className="mt-5 grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
          <Controller
            name="BondRating"
            control={form.control}
            render={({ field, fieldState }) => (
              <FormField
                label="Bond rating"
                htmlFor="BondRating"
                error={fieldState.error}
              >
                <Input id="BondRating" {...field} />
              </FormField>
            )}
          />
          <Controller
            name="Maturity"
            control={form.control}
            render={({ field, fieldState }) => (
              <FormField label="Maturity" htmlFor="Maturity" error={fieldState.error}>
                <Input id="Maturity" {...field} />
              </FormField>
            )}
          />
          <Controller
            name="marketPriceCurrency"
            control={form.control}
            render={({ field, fieldState }) => (
              <FormField
                label="Market price currency"
                htmlFor="marketPriceCurrency"
                error={fieldState.error}
              >
                <Input id="marketPriceCurrency" placeholder="e.g. USD" {...field} />
              </FormField>
            )}
          />
        </div>

        <div className="mt-5 grid gap-5 sm:grid-cols-2">
          <Controller
            name="DividendCoupon"
            control={form.control}
            render={({ field, fieldState }) => (
              <FormField
                label="Dividend / coupon"
                htmlFor="DividendCoupon"
                error={fieldState.error}
              >
                <Input id="DividendCoupon" {...field} />
              </FormField>
            )}
          />
          <Controller
            name="Country"
            control={form.control}
            render={({ field, fieldState }) => (
              <FormField label="Country" htmlFor="Country" error={fieldState.error}>
                <Input id="Country" {...field} />
              </FormField>
            )}
          />
        </div>
      </FormPanel>

      <FormSaveBar
        cancelHref={LIST_HREF}
        isSaving={isSaving}
        saveLabel="Save changes"
        onReset={() => form.reset(buildDefaults(initialIsin, initialBaseAssetClass))}
      />
    </form>
  );
}
