"use client";

import { useEffect } from "react";

import { zodResolver } from "@hookform/resolvers/zod";
import { Globe, Percent, Receipt } from "lucide-react";
import { Controller, useForm } from "react-hook-form";
import { toast } from "sonner";

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 { ActiveInactiveBadge } from "@/components/shared/status-pill";
import { Input } from "@/components/ui/input";
import {
  InputGroup,
  InputGroupAddon,
  InputGroupInput,
  InputGroupText,
} from "@/components/ui/input-group";
import { cn } from "@/lib/utils";
import { FRONTEND_ROUTES } from "@/config/frontend-routes";

import { TaxGlobalBadge } from "../status-badge";
import type { TaxRow } from "../schema";
import { TAX_GLOBAL_FORM_OPTIONS, TAX_STATUS_FORM_OPTIONS } from "./constants";
import { taxFormDefaults, taxFormSchema, type TaxFormValues } from "./schema";

const LIST_HREF = "/dashboard/plans-orders/taxes";

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

function rowToFormValues(row: TaxRow): TaxFormValues {
  return {
    name: row.name,
    percent: String(row.percent),
    is_global: row.isGlobal,
    status: row.status,
    country_id: "",
    zone_id: "",
  };
}

function TaxPreview({ values }: { values: TaxFormValues }) {
  const percentLabel = values.percent ? `${values.percent}%` : "—";

  return (
    <div className="overflow-hidden rounded-xl border bg-card shadow-sm">
      <div className="border-b bg-linear-to-br from-primary/10 via-primary/5 to-card px-4 py-3">
        <div className="flex items-center justify-between gap-2">
          <span className="font-medium text-muted-foreground text-xs uppercase tracking-wide">
            Preview
          </span>
          <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() || "Tax name"}
        </div>
        <div className="font-bold text-3xl tabular-nums tracking-tight">{percentLabel}</div>
        <div className="flex flex-wrap gap-2">
          <TaxGlobalBadge
            value={values.is_global}
            label={values.is_global === "yes" ? "Yes" : "No"}
          />
          {values.is_global === "yes" ? (
            <span className="inline-flex items-center gap-1 text-muted-foreground text-xs">
              <Globe className="size-3" />
              Applies when no regional tax matches
            </span>
          ) : null}
        </div>
      </div>
    </div>
  );
}

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

  const form = useForm<TaxFormValues>({
    resolver: zodResolver(taxFormSchema),
    defaultValues: initial ? rowToFormValues(initial) : taxFormDefaults,
  });

  const watchValues = form.watch();
  const watchGlobal = form.watch("is_global");

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

  const { isSaving, submit } = useDashboardFormSubmit<TaxFormValues>({
    mode: isUpdate ? "update" : "create",
    id: initial?.id,
    createUrl: FRONTEND_ROUTES.plansOrders.taxes.createSubmit,
    updateUrl: FRONTEND_ROUTES.plansOrders.taxes.updateSubmit,
    listHref: LIST_HREF,
    saveFailMessage: "Tax could not be saved.",
    messages: {
      createFail: "Tax could not be created.",
      updateFail: "Tax could not be updated.",
      createSuccess: "Tax created.",
      updateSuccess: "Tax updated.",
    },
    resolveSuccessMessage: (values, serverMessage, submitMode) => {
      if (values.is_global === "yes") {
        return (
          serverMessage ||
          (submitMode === "update"
            ? "Tax updated. Other taxes were set to non-global."
            : "Tax created. Other taxes were set to non-global.")
        );
      }

      return serverMessage || (submitMode === "update" ? "Tax updated." : "Tax created.");
    },
  });

  const onSubmit = form.handleSubmit(async (values) => {
    if (isUpdate && !initial?.id) {
      toast.error("A valid tax id is required.");
      return;
    }

    await submit(values);
  });

  return (
    <form onSubmit={onSubmit} className="pb-4">
      <FormPageHeader
        backHref={LIST_HREF}
        breadcrumb={[
          { label: "Plans & Orders" },
          { label: "Taxes", href: LIST_HREF },
          { label: isUpdate ? "Update" : "Create new" },
        ]}
        titleIcon={<Receipt className="size-5 text-primary" />}
        title={isUpdate ? `Update ${initial?.name ?? "tax"}` : "Create tax"}
        description="Configure tax name, rate, global fallback behaviour, and visibility at checkout."
      />

      <div className="grid gap-6 lg:grid-cols-[1fr_280px]">
        <div className="space-y-6">
          <FormPanel title="Tax details" description="Name and percentage applied to order totals.">
            <div className="grid gap-5 sm:grid-cols-2">
              <Controller
                name="name"
                control={form.control}
                render={({ field, fieldState }) => (
                  <FormField
                    label="Name"
                    htmlFor="name"
                    required
                    description="Display name for this tax (e.g. VAT, GST, Sales tax)."
                    error={fieldState.error}
                  >
                    <Input id="name" placeholder="e.g. VAT (Standard)" {...field} />
                  </FormField>
                )}
              />

              <Controller
                name="percent"
                control={form.control}
                render={({ field, fieldState }) => (
                  <FormField
                    label="Percent"
                    htmlFor="percent"
                    required
                    description="Share of the order total this tax represents (use a number, e.g. 20 for 20%)."
                    error={fieldState.error}
                  >
                    <InputGroup>
                      <InputGroupInput
                        id="percent"
                        type="number"
                        min={0}
                        step="0.01"
                        placeholder="e.g. 20"
                        {...field}
                      />
                      <InputGroupAddon align="inline-end">
                        <InputGroupText>
                          <Percent className="size-3.5" />
                        </InputGroupText>
                      </InputGroupAddon>
                    </InputGroup>
                  </FormField>
                )}
              />
            </div>
          </FormPanel>

          <FormPanel title="Scope & status">
            <div className="grid gap-5 sm:grid-cols-2">
              <Controller
                name="is_global"
                control={form.control}
                render={({ field, fieldState }) => (
                  <FormField
                    label="Is global"
                    htmlFor="is_global"
                    required
                    description="Global taxes apply to customers that don't match a regional tax. Only one global tax should be active."
                    error={fieldState.error}
                  >
                    <FormSelect
                      id="is_global"
                      value={field.value}
                      onChange={field.onChange}
                      placeholder="Select"
                      options={TAX_GLOBAL_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={TAX_STATUS_FORM_OPTIONS}
                    />
                  </FormField>
                )}
              />
            </div>

            {watchGlobal === "yes" ? (
              <p className="mt-4 rounded-lg border border-indigo-200 bg-indigo-50/60 px-3 py-2 text-indigo-900 text-xs">
                Saving a global tax will mark all other taxes as non-global, matching legacy behaviour.
              </p>
            ) : null}
          </FormPanel>

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

        <aside className="space-y-4 lg:sticky lg:top-4 lg:self-start">
          <TaxPreview values={watchValues} />
          <p
            className={cn(
              "rounded-lg border border-dashed px-3 py-2 text-muted-foreground text-xs",
              watchGlobal === "yes"
                ? "border-indigo-200 bg-indigo-50/50"
                : "border-muted bg-muted/30",
            )}
          >
            Country and zone targeting is configured in the legacy backend but hidden in the default
            form. Regional rules can be added when the API is connected.
          </p>
        </aside>
      </div>

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