"use client";

import { useEffect } from "react";

import { zodResolver } from "@hookform/resolvers/zod";
import { Languages, Map, MapPin } 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,
  type FormSelectOption,
} 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 { ActiveInactiveBadge } from "@/components/shared/status-pill";
import type { ZoneRow } from "../schema";
import { ZONE_STATUS_FORM_OPTIONS } from "./constants";
import { zoneFormDefaults, zoneFormSchema, type ZoneFormValues } from "./schema";

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

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

function rowToFormValues(row: ZoneRow): ZoneFormValues {
  return {
    name: row.name,
    code: row.code,
    country_id: String(row.countryId),
    lat: row.lat ?? "",
    lng: row.lng ?? "",
    e_l: row.enableListing,
    shipping: row.shipping > 0 ? String(row.shipping) : "",
    status: row.status,
  };
}

function ZonePreview({
  values,
  countryOptions,
}: {
  values: ZoneFormValues;
  countryOptions: FormSelectOption[];
}) {
  const countryLabel =
    countryOptions.find((c) => c.value === values.country_id)?.label ?? "—";

  return (
    <div className="overflow-hidden rounded-xl border bg-card shadow-sm">
      <div className="border-b bg-linear-to-br from-violet-500/10 via-primary/5 to-card px-4 py-3">
        <div className="flex items-center justify-between gap-2">
          <Map 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 className="font-semibold text-lg leading-tight">
          {values.name?.trim() || "Zone name"}
        </div>
        <span className="inline-flex rounded-md border bg-muted px-2 py-0.5 font-mono text-xs uppercase">
          {values.code?.trim() || "—"}
        </span>
        <p className="text-muted-foreground text-sm">{countryLabel}</p>
        {values.e_l && values.lat && values.lng ? (
          <p className="flex items-center gap-1 text-muted-foreground text-xs">
            <MapPin className="size-3.5" />
            {values.lat}, {values.lng}
          </p>
        ) : null}
        {values.shipping ? (
          <p className="font-medium text-sm tabular-nums">{values.shipping} AED shipping</p>
        ) : null}
      </div>
    </div>
  );
}

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

  const form = useForm<ZoneFormValues>({
    resolver: zodResolver(zoneFormSchema),
    defaultValues: initial ? rowToFormValues(initial) : zoneFormDefaults,
  });

  const watchValues = form.watch();
  const enableListing = form.watch("e_l");

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

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

  const onSubmit = form.handleSubmit(submit);

  return (
    <form onSubmit={onSubmit} className="pb-4">
      <FormPageHeader
        backHref={LIST_HREF}
        breadcrumb={[
          { label: "Master" },
          { label: "Zones", href: LIST_HREF },
          { label: isUpdate ? "Update" : "Create new" },
        ]}
        titleIcon={<Map className="size-5 text-primary" />}
        title={isUpdate ? `Update ${initial?.name ?? "zone"}` : "Create zone"}
        description="State, region, or city zone linked to a country with optional map coordinates."
      />

      <div className="grid gap-6 lg:grid-cols-[1fr_280px]">
        <div className="space-y-6">
          <FormPanel title="Zone identity">
            <div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-4">
              <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. Dubai" {...field} />
                  </FormField>
                )}
              />

              <Controller
                name="lat"
                control={form.control}
                render={({ field, fieldState }) => (
                  <FormField
                    label="Latitude"
                    htmlFor="lat"
                    required={enableListing}
                    error={fieldState.error}
                  >
                    <Input id="lat" placeholder="25.2048" {...field} />
                  </FormField>
                )}
              />

              <Controller
                name="lng"
                control={form.control}
                render={({ field, fieldState }) => (
                  <FormField
                    label="Longitude"
                    htmlFor="lng"
                    required={enableListing}
                    error={fieldState.error}
                  >
                    <Input id="lng" placeholder="55.2708" {...field} />
                  </FormField>
                )}
              />

              <Controller
                name="e_l"
                control={form.control}
                render={({ field }) => (
                  <FormField
                    label="Enable listing"
                    htmlFor="e_l"
                    description="Requires latitude and longitude for map display."
                    className="sm:col-span-2 lg:col-span-4"
                  >
                    <div className="flex items-center gap-3 rounded-lg border bg-muted/30 px-4 py-3">
                      <Switch id="e_l" checked={field.value} onCheckedChange={field.onChange} />
                      <span className="text-sm">
                        {field.value ? "Visible in listings" : "Hidden from listings"}
                      </span>
                    </div>
                  </FormField>
                )}
              />
            </div>
          </FormPanel>

          <FormPanel title="Region & commerce">
            <div className="grid gap-5 sm:grid-cols-2">
              <Controller
                name="code"
                control={form.control}
                render={({ field, fieldState }) => (
                  <FormField
                    label="Code"
                    htmlFor="code"
                    required
                    error={fieldState.error}
                  >
                    <Input
                      id="code"
                      placeholder="DXB"
                      className="font-mono uppercase"
                      {...field}
                      onChange={(e) => field.onChange(e.target.value.toUpperCase())}
                    />
                  </FormField>
                )}
              />

              <Controller
                name="country_id"
                control={form.control}
                render={({ field, fieldState }) => (
                  <FormField
                    label="Country"
                    htmlFor="country_id"
                    required
                    error={fieldState.error}
                  >
                    <FormSelect
                      id="country_id"
                      value={field.value}
                      onChange={field.onChange}
                      placeholder="Select country"
                      options={countryOptions}
                    />
                  </FormField>
                )}
              />

              <Controller
                name="shipping"
                control={form.control}
                render={({ field, fieldState }) => (
                  <FormField
                    label="Shipping charge"
                    htmlFor="shipping"
                    description="Zone-level shipping fee (AED)."
                    error={fieldState.error}
                  >
                    <CurrencyInput
                      id="shipping"
                      currency="AED"
                      value={field.value ?? ""}
                      onChange={field.onChange}
                    />
                  </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={ZONE_STATUS_FORM_OPTIONS}
                    />
                  </FormField>
                )}
              />
            </div>
          </FormPanel>
        </div>

        <aside className="space-y-4 lg:sticky lg:top-4 lg:self-start">
          <ZonePreview values={watchValues} countryOptions={countryOptions} />
          <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 translations can be bulk-updated from the zones list when the API is
            connected.
          </p>
        </aside>
      </div>

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