"use client";

import { useEffect } from "react";

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

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

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

import {
  USER_WIDGET_STATUS_FORM_OPTIONS,
} from "../constants";
import { ActiveReviewBadge } from "@/components/shared/status-pill";
import type { UserWidgetRow } from "../schema";
import { MULTI_ISIN_WIDGET_IDS, SINGLE_ISIN_WIDGET_IDS } from "../schema";
import { IsinMultiSelect } from "./isin-multi-select";
import {
  userWidgetFormDefaults,
  userWidgetFormSchema,
  type UserWidgetFormValues,
} from "./schema";

const LIST_HREF = "/dashboard/master/user-widgets";
const CREATE_SUBMIT_HREF = "/dashboard/master/user-widgets/create/submit";
const UPDATE_SUBMIT_HREF = "/dashboard/master/user-widgets/update";

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

function rowToFormValues(row: UserWidgetRow): UserWidgetFormValues {
  return {
    name: row.name,
    category_id: row.categoryId,
    short_description: row.shortDescription ?? "",
    file_path: row.filePath,
    status: row.status,
    isin: row.isin ?? "",
    suggested_isin_list: row.suggestedIsinList ?? [],
  };
}

function usesSingleIsin(widgetId?: number) {
  return widgetId !== undefined && (SINGLE_ISIN_WIDGET_IDS as readonly number[]).includes(widgetId);
}

function usesMultiIsin(widgetId?: number) {
  return widgetId !== undefined && (MULTI_ISIN_WIDGET_IDS as readonly number[]).includes(widgetId);
}

function UserWidgetPreview({
  values,
  categoryOptions,
}: {
  values: UserWidgetFormValues;
  categoryOptions: FormSelectOption[];
}) {
  const categoryLabel =
    categoryOptions.find((option) => option.value === values.category_id)?.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">
          <LayoutGrid className="size-5 text-primary" />
          <ActiveReviewBadge
            status={values.status}
            label={values.status === "A" ? "Active" : "Inactive"}
          />
        </div>
      </div>
      <div className="space-y-3 p-4">
        <div className="font-semibold text-lg leading-tight">
          {values.name?.trim() || "Widget name"}
        </div>
        <span className="inline-block font-mono text-muted-foreground text-xs">
          {values.file_path?.trim() || "file_path"}
        </span>
        <dl className="space-y-1.5 text-xs">
          <div className="flex justify-between gap-2">
            <dt className="text-muted-foreground">Category</dt>
            <dd className="font-medium text-right">{categoryLabel}</dd>
          </div>
        </dl>
        {values.short_description?.trim() ? (
          <p className="line-clamp-3 text-muted-foreground text-xs leading-relaxed">
            {values.short_description}
          </p>
        ) : null}
      </div>
    </div>
  );
}

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

  const form = useForm<UserWidgetFormValues>({
    resolver: zodResolver(userWidgetFormSchema),
    defaultValues: initial ? rowToFormValues(initial) : userWidgetFormDefaults,
  });

  const watchValues = form.watch();
  const showSingleIsin = usesSingleIsin(initial?.id);
  const showMultiIsin = usesMultiIsin(initial?.id);

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

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

  const onSubmit = form.handleSubmit(submit);

  return (
    <form onSubmit={onSubmit} className="pb-4">
      <FormPageHeader
        backHref={LIST_HREF}
        breadcrumb={[
          { label: "Master" },
          { label: "User widgets", href: LIST_HREF },
          { label: isUpdate ? "Update" : "Create new" },
        ]}
        titleIcon={<LayoutGrid className="size-5 text-primary" />}
        title={isUpdate ? `Update ${initial?.name ?? "widget"}` : "Create user widget"}
        description="Dashboard widget definition: category, file path, optional ISIN bindings, and status."
      />

      <div className="grid gap-6 lg:grid-cols-[1fr_280px]">
        <div className="space-y-6">
          <FormPanel title="Widget details">
            <div className="grid gap-5 sm:grid-cols-2">
              <Controller
                name="name"
                control={form.control}
                render={({ field, fieldState }) => (
                  <FormField
                    label="Name"
                    htmlFor="name"
                    required
                    error={fieldState.error}
                  >
                    <Input id="name" placeholder="Widget display name" autoFocus {...field} />
                  </FormField>
                )}
              />

              <Controller
                name="category_id"
                control={form.control}
                render={({ field, fieldState }) => (
                  <FormField
                    label="Category"
                    htmlFor="category_id"
                    required
                    error={fieldState.error}
                  >
                    <FormSelect
                      id="category_id"
                      value={field.value}
                      onChange={field.onChange}
                      placeholder="Please select"
                      options={categoryOptions}
                    />
                  </FormField>
                )}
              />

              <Controller
                name="short_description"
                control={form.control}
                render={({ field, fieldState }) => (
                  <FormField
                    label="Short description"
                    htmlFor="short_description"
                    error={fieldState.error}
                    className="sm:col-span-2"
                  >
                    <Textarea id="short_description" rows={3} {...field} />
                  </FormField>
                )}
              />
            </div>
          </FormPanel>

          {(showSingleIsin || showMultiIsin) && (
            <FormPanel
              title="ISIN configuration"
              description="Shown for market widget types (legacy widget IDs 7–12)."
            >
              {showSingleIsin ? (
                <Controller
                  name="isin"
                  control={form.control}
                  render={({ field, fieldState }) => (
                    <FormField
                      label="ISIN"
                      htmlFor="isin"
                      error={fieldState.error}
                      className="max-w-lg"
                    >
                      <Input
                        id="isin"
                        className="font-mono text-sm"
                        placeholder="e.g. US0378331005"
                        {...field}
                      />
                    </FormField>
                  )}
                />
              ) : null}

              {showMultiIsin ? (
                <Controller
                  name="suggested_isin_list"
                  control={form.control}
                  render={({ field, fieldState }) => (
                    <FormField
                      label="Suggested ISIN list"
                      htmlFor="suggested_isin_list"
                      error={fieldState.error}
                    >
                      <IsinMultiSelect
                        id="suggested_isin_list"
                        value={field.value ?? []}
                        onChange={field.onChange}
                      />
                    </FormField>
                  )}
                />
              ) : null}
            </FormPanel>
          )}

          <FormPanel title="Implementation">
            <div className="grid gap-5 sm:grid-cols-2">
              <Controller
                name="file_path"
                control={form.control}
                render={({ field, fieldState }) => (
                  <FormField
                    label="File path"
                    htmlFor="file_path"
                    required
                    description="View slug under member/widget (e.g. consolidated_holdings)."
                    error={fieldState.error}
                    className="sm:col-span-2"
                  >
                    <Input
                      id="file_path"
                      className="font-mono text-sm"
                      placeholder="e.g. cash_balance_liquidity"
                      {...field}
                    />
                  </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={USER_WIDGET_STATUS_FORM_OPTIONS}
                    />
                  </FormField>
                )}
              />
            </div>
          </FormPanel>
        </div>

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

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