"use client";

import { useEffect } from "react";

import { zodResolver } from "@hookform/resolvers/zod";
import { Hash } from "lucide-react";
import { Controller, useForm } from "react-hook-form";

import { useDashboardFormSubmit } from "@/app/dashboard/_components/use-dashboard-form-submit";

import {
  FormPageHeader,
  FormPanel,
  FormSaveBar,
  FormSelect,
  type FormSelectOption,
} from "@/app/dashboard/_components/form";
import { FormField } from "@/components/form/form-field";
import { Input } from "@/components/ui/input";

import { ActiveReviewBadge } from "@/components/shared/status-pill";
import type { SecurityTickerRow } from "../schema";
import {
  SECURITY_TICKER_STATUS_FORM_OPTIONS,
} from "./constants";
import {
  securityTickerFormDefaults,
  securityTickerFormSchema,
  type SecurityTickerFormValues,
} from "./schema";

const LIST_HREF = "/dashboard/master/security-ticker";
const CREATE_SUBMIT_HREF = "/dashboard/master/security-ticker/create/submit";
const UPDATE_SUBMIT_HREF = "/dashboard/master/security-ticker/update";

type Props = {
  mode: "create" | "update";
  initial?: SecurityTickerRow;
  securityNameOptions: FormSelectOption[];
};

function rowToFormValues(row: SecurityTickerRow): SecurityTickerFormValues {
  return {
    parent_master: row.parentMasterId == null ? "" : String(row.parentMasterId),
    master_name: row.masterName,
    status: row.status,
  };
}

function SecurityTickerPreview({
  values,
  securityNameOptions,
}: {
  values: SecurityTickerFormValues;
  securityNameOptions: FormSelectOption[];
}) {
  const parentLabel =
    securityNameOptions.find((option) => option.value === values.parent_master)?.label ??
    "—";

  return (
    <div className="overflow-hidden rounded-xl border bg-card shadow-sm">
      <div className="border-b bg-linear-to-br from-indigo-500/10 via-primary/5 to-card px-4 py-3">
        <div className="flex items-center justify-between gap-2">
          <Hash className="size-5 text-primary" />
          <ActiveReviewBadge
            status={values.status}
            label={
              values.status === "A"
                ? "Active"
                : values.status === "I"
                  ? "Inactive"
                  : "Under review"
            }
          />
        </div>
      </div>
      <div className="space-y-3 p-4">
        <span className="inline-flex rounded-md border bg-muted px-2.5 py-1 font-mono font-bold text-lg uppercase tracking-widest">
          {values.master_name?.trim() || "—"}
        </span>
        <dl className="space-y-2 text-xs">
          <div className="flex justify-between gap-2">
            <dt className="text-muted-foreground">Security name</dt>
            <dd className="font-medium text-right">{parentLabel}</dd>
          </div>
        </dl>
      </div>
    </div>
  );
}

export function SecurityTickerForm({ mode, initial, securityNameOptions }: Props) {
  const isUpdate = mode === "update";

  const form = useForm<SecurityTickerFormValues>({
    resolver: zodResolver(securityTickerFormSchema),
    defaultValues: initial ? rowToFormValues(initial) : securityTickerFormDefaults,
  });

  const watchValues = form.watch();

  useEffect(() => {
    if (initial) {
      form.reset(rowToFormValues(initial));
    }
  }, [initial, form]);

  const { isSaving, submit } = useDashboardFormSubmit<SecurityTickerFormValues>({
    mode: isUpdate ? "update" : "create",
    id: initial?.id,
    createUrl: CREATE_SUBMIT_HREF,
    updateUrl: UPDATE_SUBMIT_HREF,
    listHref: LIST_HREF,
    saveFailMessage: "Security ticker could not be saved.",
    messages: {
      createFail: "Security ticker could not be created.",
      updateFail: "Security ticker could not be updated.",
      createSuccess: "Security ticker created",
      updateSuccess: "Security ticker updated",
    },
  });

  const onSubmit = form.handleSubmit(submit);

  return (
    <form onSubmit={onSubmit} className="pb-4">
      <FormPageHeader
        backHref={LIST_HREF}
        breadcrumb={[
          { label: "Master" },
          { label: "Security ticker", href: LIST_HREF },
          { label: isUpdate ? "Update" : "Create new" },
        ]}
        titleIcon={<Hash className="size-5 text-primary" />}
        title={
          isUpdate
            ? `Update ${initial?.masterName ?? "security ticker"}`
            : "Create security ticker"
        }
        description="Link a ticker symbol to a security name. Matches the legacy security_ticker form."
      />

      <div className="grid gap-6 lg:grid-cols-[1fr_280px]">
        <FormPanel
          title="Ticker details"
          description="Parent security name, ticker symbol, and status."
        >
          <div className="grid gap-5 sm:grid-cols-2">
            <Controller
              name="parent_master"
              control={form.control}
              render={({ field, fieldState }) => (
                <FormField
                  label="Security name"
                  htmlFor="parent_master"
                  required
                  description="Parent record from Security Name master (category 21)."
                  error={fieldState.error}
                  className="sm:col-span-2"
                >
                  <FormSelect
                    id="parent_master"
                    value={field.value}
                    onChange={field.onChange}
                    placeholder="Please select"
                    options={securityNameOptions}
                  />
                </FormField>
              )}
            />

            <Controller
              name="master_name"
              control={form.control}
              render={({ field, fieldState }) => (
                <FormField
                  label="Security ticker"
                  htmlFor="master_name"
                  required
                  error={fieldState.error}
                >
                  <Input
                    id="master_name"
                    placeholder="e.g. AAPL"
                    className="font-mono uppercase"
                    {...field}
                    onChange={(e) => field.onChange(e.target.value.toUpperCase())}
                  />
                </FormField>
              )}
            />

            <Controller
              name="status"
              control={form.control}
              render={({ field, fieldState }) => (
                <FormField
                  label="Status"
                  htmlFor="status"
                  required
                  error={fieldState.error}
                >
                  <FormSelect
                    id="status"
                    value={field.value}
                    onChange={field.onChange}
                    placeholder="Select status"
                    options={SECURITY_TICKER_STATUS_FORM_OPTIONS}
                  />
                </FormField>
              )}
            />
          </div>
        </FormPanel>

        <aside className="lg:sticky lg:top-4 lg:self-start">
          <SecurityTickerPreview values={watchValues} securityNameOptions={securityNameOptions} />
        </aside>
      </div>

      <FormSaveBar
        cancelHref={LIST_HREF}
        isSaving={isSaving}
        saveLabel="Save changes"
        onReset={() =>
          form.reset(initial ? rowToFormValues(initial) : securityTickerFormDefaults)
        }
      />
    </form>
  );
}
