"use client";

import { useEffect } from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { CalendarDays } from "lucide-react";
import { useForm } from "react-hook-form";

import { useDashboardFormSubmit } from "@/app/dashboard/_components/use-dashboard-form-submit";
import {
  FormPageHeader,
  FormPanel,
  FormSaveBar,
} from "@/app/dashboard/_components/form";
import { FormField } from "@/components/form/form-field";
import { Input } from "@/components/ui/input";

import type { BankHolidayRow } from "../schema";
import {
  bankHolidayFormDefaults,
  bankHolidayFormSchema,
  type BankHolidayFormValues,
} from "./schema";

const LIST_HREF = "/dashboard/master/bank-holidays";
const CREATE_SUBMIT_HREF = "/dashboard/master/bank-holidays/create/submit";
const UPDATE_SUBMIT_HREF = "/dashboard/master/bank-holidays/update";

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

function rowToFormValues(row: BankHolidayRow): BankHolidayFormValues {
  return {
    holiday_date: row.holidayDate,
    name: row.name ?? "",
  };
}

export function BankHolidayForm({ mode, initial }: Props) {
  const isUpdate = mode === "update";
  const form = useForm<BankHolidayFormValues>({
    resolver: zodResolver(bankHolidayFormSchema),
    defaultValues: initial ? rowToFormValues(initial) : bankHolidayFormDefaults,
  });

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

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

  const onSubmit = form.handleSubmit(submit);

  return (
    <form onSubmit={onSubmit} className="pb-4">
      <FormPageHeader
        backHref={LIST_HREF}
        breadcrumb={[
          { label: "Master" },
          { label: "Bank holidays", href: LIST_HREF },
          { label: isUpdate ? "Update" : "Create new" },
        ]}
        titleIcon={<CalendarDays className="size-5 text-primary" />}
        title={
          isUpdate
            ? `Update ${initial?.name || initial?.holidayDate || "bank holiday"}`
            : "Create bank holiday"
        }
        description="Global calendar dates used by Stock Accumulator Advance view to skip non-business days."
      />

      <FormPanel title="Holiday details">
        <div className="grid gap-4 sm:grid-cols-2">
          <FormField
            label="Holiday date"
            htmlFor="holiday_date"
            error={form.formState.errors.holiday_date}
            required
          >
            <Input id="holiday_date" type="date" {...form.register("holiday_date")} />
          </FormField>
          <FormField
            label="Name"
            htmlFor="name"
            error={form.formState.errors.name}
          >
            <Input
              id="name"
              placeholder="e.g. Christmas Day"
              {...form.register("name")}
            />
          </FormField>
        </div>
      </FormPanel>

      <FormSaveBar
        isSaving={isSaving}
        cancelHref={LIST_HREF}
        saveLabel={isUpdate ? "Save changes" : "Create holiday"}
      />
    </form>
  );
}
