"use client";

import { useEffect } from "react";

import { zodResolver } from "@hookform/resolvers/zod";
import { CircleDollarSign } 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,
} from "@/app/dashboard/_components/form";
import { FormField } from "@/components/form/form-field";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

import { ActiveInactiveBadge } from "@/components/shared/status-pill";
import { YesNoBadge } from "../status-badge";
import type { CurrencyRow } from "../schema";
import { CURRENCY_STATUS_FORM_OPTIONS, YES_NO_FORM_OPTIONS } from "./constants";
import {
  currencyFormDefaults,
  currencyFormSchema,
  type CurrencyFormValues,
} from "./schema";

const LIST_HREF = "/dashboard/master/currencies";
const CREATE_SUBMIT_HREF = "/dashboard/master/currencies/create/submit";
const UPDATE_SUBMIT_HREF = "/dashboard/master/currencies/update";

type Props = {
  mode: "create" | "update";
  initial?: CurrencyRow;
};

function rowToFormValues(row: CurrencyRow): CurrencyFormValues {
  return {
    name: row.name,
    code: row.code,
    priority: row.priority,
    dufault_p: row.defaultOnPortfolio,
    is_default: row.isDefault,
    status: row.status,
  };
}

function CurrencyPreview({ values }: { values: CurrencyFormValues }) {
  return (
    <div className="overflow-hidden rounded-xl border bg-card shadow-sm">
      <div className="border-b bg-linear-to-br from-amber-500/10 via-primary/5 to-card px-4 py-3">
        <div className="flex items-center justify-between gap-2">
          <CircleDollarSign className="size-5 text-primary" />
          <ActiveInactiveBadge
            status={values.status}
            label={values.status === "active" ? "Active" : "Inactive"}
          />
        </div>
      </div>
      <div className="space-y-3 p-4">
        <div>
          <div className="font-semibold text-lg leading-tight">
            {values.name?.trim() || "Currency name"}
          </div>
        </div>
        <span className="inline-flex rounded-md border bg-muted px-2.5 py-1 font-mono font-bold text-sm uppercase tracking-widest">
          {values.code?.trim() || "—"}
        </span>
        <dl className="space-y-2 text-xs">
          <div className="flex justify-between gap-2">
            <dt className="text-muted-foreground">Is default</dt>
            <dd>
              <YesNoBadge
                value={values.is_default}
                label={values.is_default === "yes" ? "Yes" : "No"}
              />
            </dd>
          </div>
          <div className="flex justify-between gap-2">
            <dt className="text-muted-foreground">User portfolio</dt>
            <dd className="font-medium">{values.dufault_p ? "Yes" : "No"}</dd>
          </div>
          <div className="flex justify-between gap-2">
            <dt className="text-muted-foreground">Priority</dt>
            <dd className="font-medium tabular-nums">{values.priority}</dd>
          </div>
        </dl>
      </div>
    </div>
  );
}

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

  const form = useForm<CurrencyFormValues>({
    resolver: zodResolver(currencyFormSchema),
    defaultValues: initial ? rowToFormValues(initial) : currencyFormDefaults,
  });

  const watchValues = form.watch();

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

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

  const onSubmit = form.handleSubmit(submit);

  return (
    <form onSubmit={onSubmit} className="pb-4">
      <FormPageHeader
        backHref={LIST_HREF}
        breadcrumb={[
          { label: "Master" },
          { label: "Currencies", href: LIST_HREF },
          { label: isUpdate ? "Update" : "Create new" },
        ]}
        titleIcon={<CircleDollarSign className="size-5 text-primary" />}
        title={isUpdate ? `Update ${initial?.name ?? "currency"}` : "Create currency"}
        description="Currency name, ISO code, default flags, and status for pricing and checkout."
      />

      <div className="grid gap-6 lg:grid-cols-[1fr_280px]">
        <FormPanel
          title="Currency details"
          description="Matches the legacy currencies form: name, code, portfolio default, system default, and status."
        >
          <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"
                  required
                  error={fieldState.error}
                  className="sm:col-span-2"
                >
                  <Input id="name" placeholder="e.g. UAE Dirham" {...field} />
                </FormField>
              )}
            />

            <Controller
              name="code"
              control={form.control}
              render={({ field, fieldState }) => (
                <FormField
                  label="Code"
                  htmlFor="code"
                  required
                  description="3-letter ISO currency code."
                  error={fieldState.error}
                >
                  <Input
                    id="code"
                    placeholder="AED"
                    maxLength={3}
                    className="font-mono uppercase"
                    {...field}
                    onChange={(e) => field.onChange(e.target.value.toUpperCase())}
                  />
                </FormField>
              )}
            />

            <Controller
              name="priority"
              control={form.control}
              render={({ field, fieldState }) => (
                <FormField
                  label="Priority"
                  htmlFor="priority"
                  required
                  description="Display order for currency lists."
                  error={fieldState.error}
                >
                  <Input
                    id="priority"
                    type="number"
                    min={0}
                    className="tabular-nums"
                    value={field.value}
                    onChange={(event) => {
                      const parsed = Number(event.target.value);
                      field.onChange(Number.isFinite(parsed) ? parsed : 0);
                    }}
                  />
                </FormField>
              )}
            />

            <Controller
              name="dufault_p"
              control={form.control}
              render={({ field }) => (
                <FormField
                  label="Default on user portfolio"
                  htmlFor="dufault_p"
                  description="Show as default currency on customer portfolios."
                  className="sm:col-span-3"
                >
                  <div className="flex items-center gap-2 rounded-lg border bg-muted/30 px-4 py-3">
                    <Checkbox
                      id="dufault_p"
                      checked={field.value}
                      onCheckedChange={(checked) => field.onChange(checked === true)}
                    />
                    <Label htmlFor="dufault_p" className="font-normal text-sm">
                      Enable portfolio default
                    </Label>
                  </div>
                </FormField>
              )}
            />

            <Controller
              name="is_default"
              control={form.control}
              render={({ field, fieldState }) => (
                <FormField
                  label="Is default"
                  htmlFor="is_default"
                  required
                  description="System-wide default currency for the application."
                  error={fieldState.error}
                >
                  <FormSelect
                    id="is_default"
                    value={field.value}
                    onChange={field.onChange}
                    placeholder="Select"
                    options={YES_NO_FORM_OPTIONS}
                  />
                </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={CURRENCY_STATUS_FORM_OPTIONS}
                  />
                </FormField>
              )}
            />
          </div>
        </FormPanel>

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

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