"use client";

import { useEffect } from "react";

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

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

import {
  CurrencyInput,
  FormPageHeader,
  FormPanel,
  FormSaveBar,
  FormSelect,
} from "@/app/dashboard/_components/form";
import { FormField } from "@/components/form/form-field";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { cn } from "@/lib/utils";

import type { FormSelectOption } from "@/app/dashboard/_components/form";
import { ActiveInactiveBadge } from "@/components/shared/status-pill";
import type { CountryRow } from "../schema";
import { COUNTRY_STATUS_FORM_OPTIONS } from "./constants";
import { countryFormDefaults, countryFormSchema, type CountryFormValues } from "./schema";

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

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

function rowToFormValues(row: CountryRow): CountryFormValues {
  return {
    name: row.name,
    other_name: row.otherName ?? "",
    code: row.code,
    status: row.status,
    currency: row.currencyId,
    shipping: row.shipping > 0 ? String(row.shipping) : "",
    e_s: row.enableShipping,
    e_l: row.enableListing,
  };
}

function CountryPreview({
  values,
  currencyOptions,
}: {
  values: CountryFormValues;
  currencyOptions: FormSelectOption[];
}) {
  const currencyLabel =
    currencyOptions.find((c) => c.value === values.currency)?.label ?? "—";

  return (
    <div className="overflow-hidden rounded-xl border bg-card shadow-sm">
      <div className="border-b bg-linear-to-br from-sky-500/10 via-primary/5 to-card px-4 py-3">
        <div className="flex items-center justify-between gap-2">
          <Globe 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() || "Country name"}
          </div>
          {values.other_name ? (
            <p className="text-muted-foreground text-sm">{values.other_name}</p>
          ) : null}
        </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">Currency</dt>
            <dd className="font-medium text-right">{currencyLabel}</dd>
          </div>
          <div className="flex justify-between gap-2">
            <dt className="text-muted-foreground">Shipping</dt>
            <dd className="font-medium">
              {values.e_s ? (values.shipping ? `${values.shipping} AED` : "Enabled") : "Off"}
            </dd>
          </div>
        </dl>
      </div>
    </div>
  );
}

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

  const form = useForm<CountryFormValues>({
    resolver: zodResolver(countryFormSchema),
    defaultValues: initial ? rowToFormValues(initial) : countryFormDefaults,
  });

  const watchValues = form.watch();
  const enableShipping = form.watch("e_s");

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

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

  const onSubmit = form.handleSubmit(submit);

  return (
    <form onSubmit={onSubmit} className="pb-4">
      <FormPageHeader
        backHref={LIST_HREF}
        breadcrumb={[
          { label: "Master" },
          { label: "Countries", href: LIST_HREF },
          { label: isUpdate ? "Update" : "Create new" },
        ]}
        titleIcon={<Globe className="size-5 text-primary" />}
        title={isUpdate ? `Update ${initial?.name ?? "country"}` : "Create country"}
        description="Country name, ISO code, currency, and shipping settings for checkout and listings."
      />

      <div className="grid gap-6 lg:grid-cols-[1fr_280px]">
        <div className="space-y-6">
          <FormPanel
            title="Identity"
            description="Primary country name and ISO code shown across the platform."
          >
            <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
                    description="Official country name (English)."
                    error={fieldState.error}
                    className="sm:col-span-2"
                  >
                    <Input id="name" placeholder="e.g. United Arab Emirates" {...field} />
                  </FormField>
                )}
              />

              <Controller
                name="other_name"
                control={form.control}
                render={({ field, fieldState }) => (
                  <FormField
                    label="Other name"
                    htmlFor="other_name"
                    description="Alternate or local name."
                    error={fieldState.error}
                  >
                    <Input id="other_name" placeholder="e.g. UAE" {...field} />
                  </FormField>
                )}
              />

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

          <FormPanel title="Commerce" description="Currency and shipping configuration.">
            <div className="grid gap-5 sm:grid-cols-2">
              <Controller
                name="currency"
                control={form.control}
                render={({ field, fieldState }) => (
                  <FormField
                    label="Currency"
                    htmlFor="currency"
                    error={fieldState.error}
                  >
                    <FormSelect
                      id="currency"
                      value={field.value}
                      onChange={field.onChange}
                      placeholder="Select currency"
                      options={currencyOptions}
                    />
                  </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={COUNTRY_STATUS_FORM_OPTIONS}
                    />
                  </FormField>
                )}
              />

              <Controller
                name="e_s"
                control={form.control}
                render={({ field }) => (
                  <FormField
                    label="Enable shipping"
                    htmlFor="e_s"
                    description="Allow shipping charges for this country at checkout."
                    className="sm:col-span-2"
                  >
                    <div className="flex items-center gap-3 rounded-lg border bg-muted/30 px-4 py-3">
                      <Switch
                        id="e_s"
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                      <div className="flex items-center gap-2 text-sm">
                        <Ship className="size-4 text-muted-foreground" />
                        <span>{field.value ? "Shipping enabled" : "Shipping disabled"}</span>
                      </div>
                    </div>
                  </FormField>
                )}
              />

              {enableShipping ? (
                <Controller
                  name="shipping"
                  control={form.control}
                  render={({ field, fieldState }) => (
                    <FormField
                      label="Shipping charge"
                      htmlFor="shipping"
                      description="Flat shipping fee (AED)."
                      error={fieldState.error}
                      className="sm:col-span-2"
                    >
                      <CurrencyInput
                        id="shipping"
                        currency="AED"
                        value={field.value ?? ""}
                        onChange={field.onChange}
                        placeholder="0.00"
                      />
                    </FormField>
                  )}
                />
              ) : null}
            </div>
          </FormPanel>

          <input type="hidden" {...form.register("e_l")} />
        </div>

        <aside className="space-y-4 lg:sticky lg:top-4 lg:self-start">
          <CountryPreview values={watchValues} currencyOptions={currencyOptions} />
          <p
            className={cn(
              "flex items-start gap-2 rounded-lg border border-dashed px-3 py-2 text-muted-foreground text-xs",
            )}
          >
            <Languages className="mt-0.5 size-3.5 shrink-0" />
            Arabic and Dutch translations can be bulk-updated from the countries list. Per-field
            translation links will connect when the API is ready.
          </p>
        </aside>
      </div>

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