"use client";

import { useEffect, useState } from "react";

import { zodResolver } from "@hookform/resolvers/zod";
import { Gem } 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 { Input } from "@/components/ui/input";
import { ImagePreview } from "@/components/ui/image-preview";

import { ActiveReviewBadge } from "@/components/shared/status-pill";
import type { CommodityNameRow } from "../schema";
import { COMMODITY_NAME_STATUS_FORM_OPTIONS } from "./constants";
import { CommodityNameImageField } from "./image-field";
import {
  commodityNameFormDefaults,
  commodityNameFormSchema,
  type CommodityNameFormValues,
} from "./schema";

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

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

function rowToFormValues(row: CommodityNameRow): CommodityNameFormValues {
  return {
    master_name: row.masterName,
    status: row.status,
  };
}

function CommodityNamePreview({
  values,
  imageUrl,
}: {
  values: CommodityNameFormValues;
  imageUrl?: string | null;
}) {
  return (
    <div className="overflow-hidden rounded-xl border bg-card shadow-sm">
      <div className="border-b bg-linear-to-br from-amber-500/15 via-primary/5 to-card px-4 py-3">
        <div className="flex items-center justify-between gap-2">
          <Gem 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">
        {imageUrl ? (
          <div className="flex justify-center rounded-lg border bg-white p-3">
            <ImagePreview src={imageUrl} alt="" className="max-h-16" />
          </div>
        ) : null}
        <div className="font-semibold text-lg leading-tight">
          {values.master_name?.trim() || "Commodity name"}
        </div>
      </div>
    </div>
  );
}

export function CommodityNameForm({ mode, initial }: Props) {
  const [imageFile, setImageFile] = useState<File | null>(null);
  const [previewUrl, setPreviewUrl] = useState<string | null>(initial?.imageUrl ?? null);
  const isUpdate = mode === "update";

  const form = useForm<CommodityNameFormValues>({
    resolver: zodResolver(commodityNameFormSchema),
    defaultValues: initial ? rowToFormValues(initial) : commodityNameFormDefaults,
  });

  const watchValues = form.watch();

  useEffect(() => {
    if (initial) {
      form.reset(rowToFormValues(initial));
      setPreviewUrl(initial.imageUrl ?? null);
      setImageFile(null);
    }
  }, [initial, form]);

  useEffect(() => {
    if (!imageFile) return;
    const url = URL.createObjectURL(imageFile);
    setPreviewUrl(url);
    return () => URL.revokeObjectURL(url);
  }, [imageFile]);

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

  const onSubmit = form.handleSubmit(submit);

  return (
    <form onSubmit={onSubmit} className="pb-4">
      <FormPageHeader
        backHref={LIST_HREF}
        breadcrumb={[
          { label: "Master" },
          { label: "Commodity name", href: LIST_HREF },
          { label: isUpdate ? "Update" : "Create new" },
        ]}
        titleIcon={<Gem className="size-5 text-primary" />}
        title={
          isUpdate ? `Update ${initial?.masterName ?? "commodity name"}` : "Create commodity name"
        }
        description="Commodity name label, status, and optional gallery image for listings and reports."
      />

      <div className="grid gap-6 lg:grid-cols-[1fr_280px]">
        <FormPanel
          title="Commodity details"
          description="Matches the legacy master_commodity_name form fields."
        >
          <div className="grid gap-5 sm:grid-cols-2">
            <Controller
              name="master_name"
              control={form.control}
              render={({ field, fieldState }) => (
                <FormField
                  label="Commodity name"
                  htmlFor="master_name"
                  required
                  error={fieldState.error}
                  className="sm:col-span-2"
                >
                  <Input id="master_name" placeholder="e.g. Gold" {...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={COMMODITY_NAME_STATUS_FORM_OPTIONS}
                  />
                </FormField>
              )}
            />

            <div className="sm:col-span-2">
              <CommodityNameImageField
                id="file_name"
                label="Image"
                hint={initial?.fileName}
                value={imageFile}
                existingUrl={initial?.imageUrl}
                onChange={setImageFile}
              />
            </div>
          </div>
        </FormPanel>

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

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