"use client";

import { useEffect, useMemo, useState } from "react";

import { zodResolver } from "@hookform/resolvers/zod";
import { Ticket } 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 { CommodityTicketRow } from "../schema";
import { COMMODITY_TICKET_STATUS_FORM_OPTIONS } from "./constants";
import { QuickAddCommodityNameButton } from "./quick-add-commodity-name-button";
import {
  commodityTicketFormDefaults,
  commodityTicketFormSchema,
  type CommodityTicketFormValues,
} from "./schema";

const LIST_HREF = "/dashboard/master/commodity-ticket";
const CREATE_SUBMIT_HREF = "/dashboard/master/commodity-ticket/create/submit";
const UPDATE_SUBMIT_HREF = "/dashboard/master/commodity-ticket/update";

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

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

function CommodityTicketPreview({
  values,
  commodityNameOptions,
}: {
  values: CommodityTicketFormValues;
  commodityNameOptions: FormSelectOption[];
}) {
  const parentLabel =
    commodityNameOptions.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-orange-500/10 via-primary/5 to-card px-4 py-3">
        <div className="flex items-center justify-between gap-2">
          <Ticket 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">Commodity name</dt>
            <dd className="font-medium text-right">{parentLabel}</dd>
          </div>
        </dl>
      </div>
    </div>
  );
}

export function CommodityTicketForm({ mode, initial, commodityNameOptions }: Props) {
  const isUpdate = mode === "update";
  const [extraParentOptions, setExtraParentOptions] = useState<FormSelectOption[]>([]);

  const form = useForm<CommodityTicketFormValues>({
    resolver: zodResolver(commodityTicketFormSchema),
    defaultValues: initial ? rowToFormValues(initial) : commodityTicketFormDefaults,
  });

  const watchValues = form.watch();

  const parentOptions = useMemo(() => {
    const merged = new Map<string, FormSelectOption>();

    for (const option of commodityNameOptions) {
      merged.set(option.value, option);
    }

    if (initial?.parentMasterId && initial.parentName) {
      const value = String(initial.parentMasterId);
      if (!merged.has(value)) {
        merged.set(value, { value, label: initial.parentName });
      }
    }

    for (const option of extraParentOptions) {
      merged.set(option.value, option);
    }

    return [...merged.values()].sort((a, b) => a.label.localeCompare(b.label));
  }, [commodityNameOptions, extraParentOptions, initial]);

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

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

  const onSubmit = form.handleSubmit(submit);

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

      <div className="grid gap-6 lg:grid-cols-[1fr_280px]">
        <FormPanel
          title="Ticker details"
          description="Parent commodity 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="Commodity name"
                  htmlFor="parent_master"
                  required
                  description="Parent record from Commodity Name master (category 25)."
                  error={fieldState.error}
                  className="sm:col-span-2"
                  labelAction={
                    <QuickAddCommodityNameButton
                      onCreated={(option) => {
                        setExtraParentOptions((current) => {
                          if (current.some((item) => item.value === option.value)) {
                            return current;
                          }
                          return [...current, option];
                        });
                        field.onChange(option.value);
                      }}
                    />
                  }
                >
                  <FormSelect
                    id="parent_master"
                    value={field.value}
                    onChange={field.onChange}
                    placeholder="Please select"
                    options={parentOptions}
                  />
                </FormField>
              )}
            />

            <Controller
              name="master_name"
              control={form.control}
              render={({ field, fieldState }) => (
                <FormField
                  label="Commodity ticker"
                  htmlFor="master_name"
                  required
                  error={fieldState.error}
                >
                  <Input
                    id="master_name"
                    placeholder="e.g. XAUUSD"
                    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={COMMODITY_TICKET_STATUS_FORM_OPTIONS}
                  />
                </FormField>
              )}
            />
          </div>
        </FormPanel>

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

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