"use client";

import { useEffect } from "react";

import { zodResolver } from "@hookform/resolvers/zod";
import {
  Calendar as CalendarIcon,
  Check,
  CheckCircle2,
  Copy,
  CreditCard,
  Info,
  Receipt,
  Tag,
  User,
} from "lucide-react";
import { Controller, useForm, useWatch } from "react-hook-form";
import { toast } from "sonner";

import { useDashboardFormSubmit } from "@/app/dashboard/_components/use-dashboard-form-submit";
import {
  CurrencyInput,
  FormPanel,
  FormSelect,
  FormPageHeader,
  FormSaveBar,
} from "@/app/dashboard/_components/form";
import { FormField } from "@/components/form/form-field";
import { ErrorBanner } from "@/components/shared/error-banner";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  InputGroup,
  InputGroupAddon,
  InputGroupInput,
  InputGroupText,
} from "@/components/ui/input-group";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { cn, formatCurrency, getInitials } from "@/lib/utils";
import { FRONTEND_ROUTES } from "@/config/frontend-routes";

import { OrderStatusBadge } from "../status-badge";
import type { OrderStatus } from "../schema";
import {
  COUNTRY_OPTIONS,
  CURRENCY_OPTIONS,
  CUSTOMER_OPTIONS,
  ORDER_STATUS_FORM_OPTIONS,
  PAYMENT_METHOD_OPTIONS,
  PAYMENT_TYPE_OPTIONS,
  PLAN_OPTIONS,
  TAX_OPTIONS,
} from "./constants";
import { orderCreateDefaults, orderCreateSchema, type OrderCreateFormValues } from "./schema";
import type { OrderDetail } from "../../_lib/orders-server-api";

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

type OrderCreateFormProps = {
  mode?: "create" | "update";
  initial?: OrderDetail;
  initialErrorMessage?: string | null;
};

/* -------------------------------------------------- *
 * Local primitives
 * -------------------------------------------------- */

function ChipGroup<T extends string>({
  value,
  onChange,
  options,
  ariaLabel,
  activeClass,
}: {
  value: T;
  onChange: (v: T) => void;
  options: readonly { value: T; label: string }[];
  ariaLabel: string;
  activeClass?: (v: T) => string;
}) {
  return (
    <div role="radiogroup" aria-label={ariaLabel} className="flex flex-wrap gap-1.5">
      {options.map((opt) => {
        const active = value === opt.value;
        return (
          <button
            type="button"
            key={opt.value}
            role="radio"
            aria-checked={active}
            onClick={() => onChange(opt.value)}
            className={cn(
              "inline-flex items-center gap-1.5 rounded-full border bg-background px-3 py-1 text-xs font-medium transition-colors",
              "hover:bg-muted",
              active && "shadow-sm",
              active && (activeClass?.(opt.value) ?? "border-primary bg-primary text-primary-foreground"),
            )}
          >
            {active ? <Check className="size-3" /> : null}
            {opt.label}
          </button>
        );
      })}
    </div>
  );
}

function Row({
  label,
  value,
  bold,
  valueClass,
}: {
  label: string;
  value: string;
  bold?: boolean;
  valueClass?: string;
}) {
  return (
    <div className="flex items-center justify-between gap-3">
      <dt className={cn("text-muted-foreground text-xs", bold && "text-foreground font-semibold text-sm")}>
        {label}
      </dt>
      <dd className={cn("tabular-nums text-sm", bold && "font-bold text-base", valueClass)}>{value}</dd>
    </div>
  );
}

const statusActiveStyles: Record<OrderStatus, string> = {
  incomplete: "border-slate-500 bg-slate-200 text-slate-800",
  complete: "border-emerald-500 bg-emerald-100 text-emerald-900",
  pending: "border-amber-500 bg-amber-100 text-amber-900",
  due: "border-orange-500 bg-orange-100 text-orange-900",
  failed: "border-rose-500 bg-rose-100 text-rose-900",
  refunded: "border-violet-500 bg-violet-100 text-violet-900",
  c_request: "border-sky-500 bg-sky-100 text-sky-900",
  P_ORDER: "border-indigo-500 bg-indigo-100 text-indigo-900",
};

/* -------------------------------------------------- *
 * Main form
 * -------------------------------------------------- */

export function OrderCreateForm({
  mode = "create",
  initial,
  initialErrorMessage = null,
}: OrderCreateFormProps) {
  const isUpdate = mode === "update";

  const form = useForm<OrderCreateFormValues>({
    resolver: zodResolver(orderCreateSchema),
    defaultValues: initial?.values ?? orderCreateDefaults,
  });

  const errors = form.formState.errors;
  const [
    planId,
    taxId,
    subtotal,
    discount,
    shippingCharge,
    taxPercent,
    taxValue,
    total,
    customerId,
    status,
    dateStart,
    promoCode,
    paymentType,
  ] = useWatch({
    control: form.control,
    name: [
      "plan_id",
      "tax_id",
      "subtotal",
      "discount",
      "shipping_charge",
      "tax_percent",
      "tax_value",
      "total",
      "customer_id",
      "status",
      "date_start",
      "promo_code",
      "payment_type",
    ],
  });

  // Plan → subtotal/total auto-fill
  useEffect(() => {
    if (!planId) return;
    const plan = PLAN_OPTIONS.find((p) => p.value === planId);
    if (!plan) return;
    const current = form.getValues();
    if (!current.subtotal || current.subtotal === "0") {
      form.setValue("subtotal", String(plan.price), { shouldDirty: true });
    }
    if (!current.total || current.total === "0") {
      form.setValue("total", String(plan.price), { shouldDirty: true });
    }
  }, [planId, form]);

  // Tax preset → percent auto-fill
  useEffect(() => {
    if (!taxId) return;
    const tax = TAX_OPTIONS.find((t) => t.value === taxId);
    if (!tax) return;
    form.setValue("tax_percent", String(tax.percent), { shouldDirty: true });
  }, [taxId, form]);

  // Live recompute tax_value and total
  const subtotalNum = Number(subtotal || 0);
  const discountNum = Number(discount || 0);
  const shippingNum = Number(shippingCharge || 0);
  const taxPercentNum = Number(taxPercent || 0);
  const taxableBase = Math.max(subtotalNum - discountNum, 0);
  const computedTax = +(taxableBase * (taxPercentNum / 100)).toFixed(2);
  const computedTotal = +(taxableBase + computedTax + shippingNum).toFixed(2);

  useEffect(() => {
    const currentTax = Number(taxValue || 0);
    if (currentTax !== computedTax) {
      form.setValue("tax_value", String(computedTax), { shouldDirty: true });
    }
    const currentTotal = Number(total || 0);
    if (currentTotal !== computedTotal) {
      form.setValue("total", String(computedTotal), { shouldDirty: true });
    }
  }, [computedTax, computedTotal, form, taxValue, total]);

  const customer = CUSTOMER_OPTIONS.find((c) => c.value === customerId);
  const plan = PLAN_OPTIONS.find((p) => p.value === planId);
  const [customerName, customerEmail] = customer?.label.split(" — ") ?? [];

  const handleCopyFromCustomer = () => {
    if (!customer) {
      toast.error("Pick a customer first");
      return;
    }
    const [firstName, ...rest] = (customerName ?? "").split(" ");
    form.setValue("first_name", firstName ?? "", { shouldDirty: true });
    form.setValue("last_name", rest.join(" "), { shouldDirty: true });
    if (customerEmail) {
      form.setValue("email", customerEmail, { shouldDirty: true });
    }
    toast.success("Billing details copied from customer");
  };

  const { isSaving, submit } = useDashboardFormSubmit({
    mode: isUpdate ? "update" : "create",
    id: initial?.id,
    createUrl: FRONTEND_ROUTES.plansOrders.orders.createSubmit,
    updateUrl: FRONTEND_ROUTES.plansOrders.orders.updateSubmit,
    listHref: LIST_HREF,
    saveFailMessage: "Order could not be saved.",
    messages: {
      createFail: "Order could not be created.",
      updateFail: "Order could not be updated.",
      createSuccess: "Order created.",
      updateSuccess: "Order updated.",
    },
  });

  const onSubmit = form.handleSubmit(async (values) => {
    await submit(values);
  });

  const statusLabel =
    ORDER_STATUS_FORM_OPTIONS.find((s) => s.value === status)?.label ?? status;

  return (
    <form onSubmit={onSubmit} className="m-8 flex flex-col">
      <ErrorBanner message={initialErrorMessage} className="mb-4" />

      <FormPageHeader
        backHref={LIST_HREF}
        parentLabel="Orders"
        titleIcon={<Receipt className="size-4 text-primary" />}
        title={isUpdate ? `Update order ${initial?.orderUid || `#${initial?.id}`}` : "New order"}
        meta={
          <span className="hidden items-center gap-2 rounded-full border bg-muted/40 px-3 py-1 text-xs sm:inline-flex">
            <span className="text-muted-foreground">Total</span>
            <span className="font-semibold tabular-nums">{formatCurrency(computedTotal)}</span>
          </span>
        }
      />

      <div className="grid gap-6 lg:grid-cols-[1fr_360px]">
        <div className="space-y-6">
          <div className="flex items-start gap-2 rounded-lg border border-amber-200 bg-amber-50/60 px-3 py-2 text-xs text-amber-900">
            <Info className="mt-0.5 size-3.5 shrink-0" />
            <span>
              Manual entry — orders here skip the payment gateway. Setting status to{" "}
              <strong>Complete</strong> assigns the plan to the customer.
            </span>
          </div>

          <FormPanel
            title="Customer & plan"
            description="Who is this order for and which plan are they buying?"
          >
            <div className="grid gap-4 md:grid-cols-2">
              <div className="space-y-1.5">
                <Label className="flex items-center gap-1.5 text-xs">
                  <User className="size-3.5 text-muted-foreground" />
                  Customer <span className="text-destructive">*</span>
                </Label>
                <Controller
                  name="customer_id"
                  control={form.control}
                  render={({ field }) => (
                    <FormSelect
                      id="customer_id"
                      value={field.value}
                      onChange={field.onChange}
                      placeholder="Search customer…"
                      options={CUSTOMER_OPTIONS}
                    />
                  )}
                />
                {customer ? (
                  <div className="mt-2 flex items-center gap-2.5 rounded-lg border bg-muted/30 px-2.5 py-2">
                    <Avatar className="size-8">
                      <AvatarFallback className="bg-primary/10 text-[11px] font-medium text-primary">
                        {getInitials(customerName)}
                      </AvatarFallback>
                    </Avatar>
                    <div className="min-w-0 flex-1 leading-tight">
                      <p className="truncate text-sm font-medium">{customerName}</p>
                      <p className="truncate text-muted-foreground text-xs">{customerEmail}</p>
                    </div>
                  </div>
                ) : (
                  <p className="text-muted-foreground text-[11px]">No customer selected.</p>
                )}
                {errors.customer_id ? (
                  <p className="text-destructive text-xs">{errors.customer_id.message}</p>
                ) : null}
              </div>

              <div className="space-y-1.5">
                <Label className="flex items-center gap-1.5 text-xs">
                  <CreditCard className="size-3.5 text-muted-foreground" />
                  Plan <span className="text-destructive">*</span>
                </Label>
                <Controller
                  name="plan_id"
                  control={form.control}
                  render={({ field }) => (
                    <FormSelect
                      id="plan_id"
                      value={field.value}
                      onChange={field.onChange}
                      placeholder="Select plan"
                      options={PLAN_OPTIONS}
                    />
                  )}
                />
                {plan ? (
                  <div className="mt-2 flex items-center justify-between gap-2 rounded-lg border bg-muted/30 px-2.5 py-2">
                    <div className="min-w-0 leading-tight">
                      <p className="truncate text-sm font-medium">{plan.label.split(" — ")[0]}</p>
                      <p className="truncate text-muted-foreground text-xs">{plan.label.split(" — ")[1]}</p>
                    </div>
                    <span className="font-semibold tabular-nums text-sm">{formatCurrency(plan.price)}</span>
                  </div>
                ) : (
                  <p className="text-muted-foreground text-[11px]">No plan selected.</p>
                )}
                {errors.plan_id ? (
                  <p className="text-destructive text-xs">{errors.plan_id.message}</p>
                ) : null}
              </div>

              <FormField label="Start date" htmlFor="date_start" required error={errors.date_start}>
                <div className="relative">
                  <CalendarIcon className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
                  <Input
                    id="date_start"
                    type="date"
                    className="h-9 pl-8"
                    aria-invalid={!!errors.date_start}
                    {...form.register("date_start")}
                  />
                </div>
              </FormField>
              <FormField
                label="Promo code"
                htmlFor="promo_code"
                description="Optional — code applies a discount automatically in production."
              >
                <div className="relative">
                  <Tag className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
                  <Input
                    id="promo_code"
                    className="h-9 pl-8 uppercase tracking-wide"
                    placeholder="WELCOME10"
                    {...form.register("promo_code")}
                  />
                </div>
              </FormField>
            </div>
          </FormPanel>

          <FormPanel
            title="Amounts"
            description="Subtotal, discounts and tax — the total recalculates automatically."
          >
            <div className="grid gap-4 md:grid-cols-3">
              <FormField label="Subtotal" htmlFor="subtotal" required error={errors.subtotal}>
                <CurrencyInput id="subtotal" invalid={!!errors.subtotal} {...form.register("subtotal")} />
              </FormField>
              <FormField label="Discount" htmlFor="discount" error={errors.discount}>
                <CurrencyInput id="discount" {...form.register("discount")} />
              </FormField>
              <FormField label="Shipping" htmlFor="shipping_charge" error={errors.shipping_charge}>
                <CurrencyInput id="shipping_charge" {...form.register("shipping_charge")} />
              </FormField>
              <FormField label="Tax preset" htmlFor="tax_id" error={errors.tax_id}>
                <Controller
                  name="tax_id"
                  control={form.control}
                  render={({ field }) => (
                    <FormSelect
                      id="tax_id"
                      value={field.value ?? ""}
                      onChange={field.onChange}
                      placeholder="No tax"
                      options={TAX_OPTIONS}
                    />
                  )}
                />
              </FormField>
              <FormField label="Tax %" htmlFor="tax_percent" error={errors.tax_percent}>
                <InputGroup className="h-9">
                  <InputGroupInput
                    id="tax_percent"
                    type="number"
                    step="0.01"
                    inputMode="decimal"
                    placeholder="0"
                    {...form.register("tax_percent")}
                  />
                  <InputGroupAddon align="inline-end" className="border-l bg-muted/40 px-2.5">
                    <InputGroupText className="text-muted-foreground text-xs">%</InputGroupText>
                  </InputGroupAddon>
                </InputGroup>
              </FormField>
              <FormField
                label="Tax value"
                htmlFor="tax_value"
                description="Auto-calculated."
                error={errors.tax_value}
              >
                <CurrencyInput id="tax_value" {...form.register("tax_value")} />
              </FormField>
            </div>

            <div className="mt-5 flex flex-wrap items-center justify-between gap-3 rounded-lg border bg-linear-to-br from-primary/8 via-card to-card px-4 py-3">
              <div className="space-y-0.5">
                <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Order total</p>
                <p className="font-bold text-2xl tabular-nums leading-none">{formatCurrency(computedTotal)}</p>
              </div>
              <div className="text-right text-[11px] text-muted-foreground">
                <p>
                  Subtotal {formatCurrency(subtotalNum)}
                  {discountNum > 0 ? ` − ${formatCurrency(discountNum)} discount` : ""}
                </p>
                <p>
                  + {formatCurrency(computedTax)} tax ({taxPercentNum}%)
                  {shippingNum > 0 ? ` + ${formatCurrency(shippingNum)} shipping` : ""}
                </p>
              </div>
            </div>
          </FormPanel>

          <FormPanel title="Status & payment" description="Click a chip to choose.">
            <div className="space-y-4">
              <div className="space-y-1.5">
                <Label className="text-xs">Status</Label>
                <Controller
                  name="status"
                  control={form.control}
                  render={({ field }) => (
                    <ChipGroup
                      ariaLabel="Order status"
                      value={field.value as OrderStatus}
                      onChange={field.onChange}
                      options={ORDER_STATUS_FORM_OPTIONS}
                      activeClass={(v) => statusActiveStyles[v as OrderStatus]}
                    />
                  )}
                />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs">Payment type</Label>
                <Controller
                  name="payment_type"
                  control={form.control}
                  render={({ field }) => (
                    <ChipGroup
                      ariaLabel="Payment type"
                      value={field.value}
                      onChange={field.onChange}
                      options={PAYMENT_TYPE_OPTIONS}
                    />
                  )}
                />
              </div>
              <div className="grid gap-4 md:grid-cols-2">
                <FormField label="Currency" htmlFor="currency_id" required error={errors.currency_id}>
                  <Controller
                    name="currency_id"
                    control={form.control}
                    render={({ field }) => (
                      <FormSelect
                        id="currency_id"
                        value={field.value}
                        onChange={field.onChange}
                        placeholder="Select currency"
                        options={CURRENCY_OPTIONS}
                      />
                    )}
                  />
                </FormField>
                <FormField
                  label="Payment method"
                  htmlFor="payment_method"
                  required
                  description="Gateway or manual payment method id."
                  error={errors.payment_method}
                >
                  <Controller
                    name="payment_method"
                    control={form.control}
                    render={({ field }) => (
                      <FormSelect
                        id="payment_method"
                        value={field.value}
                        onChange={field.onChange}
                        placeholder="Select method"
                        options={PAYMENT_METHOD_OPTIONS}
                      />
                    )}
                  />
                </FormField>
              </div>
            </div>
          </FormPanel>

          <FormPanel
            title="Billing details"
            description="Where should the invoice be addressed?"
            action={
              <Button
                type="button"
                variant="ghost"
                size="sm"
                className="h-7 gap-1.5 text-xs"
                onClick={handleCopyFromCustomer}
                disabled={!customer}
              >
                <Copy className="size-3.5" />
                Copy from customer
              </Button>
            }
          >
            <div className="space-y-4">
              <div className="grid gap-4 md:grid-cols-2">
                <FormField label="First name" htmlFor="first_name" required error={errors.first_name}>
                  <Input id="first_name" className="h-9" {...form.register("first_name")} />
                </FormField>
                <FormField label="Last name" htmlFor="last_name" required error={errors.last_name}>
                  <Input id="last_name" className="h-9" {...form.register("last_name")} />
                </FormField>
              </div>
              <FormField label="Address" htmlFor="address" required error={errors.address}>
                <Input
                  id="address"
                  className="h-9"
                  placeholder="Street, building, unit"
                  {...form.register("address")}
                />
              </FormField>
              <div className="grid gap-4 md:grid-cols-2">
                <FormField label="City" htmlFor="city" required error={errors.city}>
                  <Input id="city" className="h-9" {...form.register("city")} />
                </FormField>
                <FormField label="Country" htmlFor="country_id" required error={errors.country_id}>
                  <Controller
                    name="country_id"
                    control={form.control}
                    render={({ field }) => (
                      <FormSelect
                        id="country_id"
                        value={field.value}
                        onChange={field.onChange}
                        placeholder="Please select"
                        options={COUNTRY_OPTIONS}
                      />
                    )}
                  />
                </FormField>
              </div>
              <div className="grid gap-4 md:grid-cols-2">
                <FormField label="Phone" htmlFor="phone" required error={errors.phone}>
                  <Input id="phone" className="h-9" placeholder="+971 …" {...form.register("phone")} />
                </FormField>
                <FormField label="Email" htmlFor="email" required error={errors.email}>
                  <Input
                    id="email"
                    type="email"
                    className="h-9"
                    autoComplete="email"
                    {...form.register("email")}
                  />
                </FormField>
              </div>
            </div>
          </FormPanel>

          <FormPanel title="Internal note" description="Only visible to your team.">
            <Textarea id="note" rows={3} placeholder="Add an internal note…" {...form.register("note")} />
          </FormPanel>
        </div>

        <aside className="space-y-4 lg:sticky lg:top-24 lg:self-start">
          <div className="overflow-hidden rounded-2xl border bg-card shadow-sm">
            <div className="bg-linear-to-br from-primary via-primary/95 to-primary/80 px-5 py-5 text-primary-foreground">
              <p className="text-[11px] uppercase tracking-wide opacity-80">Order total</p>
              <p className="mt-1 font-bold text-3xl tabular-nums leading-none">{formatCurrency(computedTotal)}</p>
              <div className="mt-3 flex items-center justify-between">
                <OrderStatusBadge status={status as OrderStatus} label={statusLabel} />
                <span className="text-[11px] opacity-90 tabular-nums">{dateStart}</span>
              </div>
            </div>

            <div className="space-y-3 border-b px-5 py-4">
              <div className="flex items-center gap-3">
                <Avatar className="size-9">
                  <AvatarFallback className="bg-muted text-[11px] font-medium">
                    {getInitials(customerName)}
                  </AvatarFallback>
                </Avatar>
                <div className="min-w-0 leading-tight">
                  <p
                    className={cn(
                      "truncate text-sm font-semibold",
                      !customer && "text-muted-foreground italic",
                    )}
                  >
                    {customerName ?? "Select a customer"}
                  </p>
                  <p className="truncate text-muted-foreground text-xs">{customerEmail ?? "—"}</p>
                </div>
              </div>
              <div className="flex items-center justify-between gap-2 rounded-lg border bg-muted/30 px-2.5 py-1.5">
                <span className={cn("text-xs", !plan && "text-muted-foreground italic")}>
                  {plan?.label.split(" — ")[0] ?? "Select a plan"}
                </span>
                <span className="font-medium tabular-nums text-xs">
                  {plan ? formatCurrency(plan.price) : "—"}
                </span>
              </div>
              {promoCode ? (
                <div className="flex items-center gap-1.5 text-xs text-emerald-700">
                  <CheckCircle2 className="size-3.5" />
                  Promo <span className="font-mono uppercase">{promoCode}</span> applied
                </div>
              ) : null}
            </div>

            <dl className="space-y-2 px-5 py-4 text-sm">
              <Row label="Subtotal" value={formatCurrency(subtotalNum)} />
              {discountNum > 0 ? (
                <Row label="Discount" value={`−${formatCurrency(discountNum)}`} valueClass="text-emerald-700" />
              ) : null}
              {shippingNum > 0 ? <Row label="Shipping" value={formatCurrency(shippingNum)} /> : null}
              <Row label={`Tax (${taxPercentNum}%)`} value={formatCurrency(computedTax)} />
              <div className="my-1 border-t" />
              <Row label="Total" value={formatCurrency(computedTotal)} bold />
            </dl>
          </div>

          <div className="rounded-lg border bg-muted/20 px-3 py-2.5 text-xs">
            <p className="text-muted-foreground">Payment method</p>
            <p className="mt-0.5 font-medium">
              {PAYMENT_TYPE_OPTIONS.find((p) => p.value === paymentType)?.label ?? paymentType}
            </p>
          </div>
        </aside>
      </div>

      <FormSaveBar
        cancelHref={LIST_HREF}
        isSaving={isSaving}
        saveLabel={isUpdate ? "Save changes" : "Save order"}
        onReset={
          isUpdate && initial ? () => form.reset(initial.values) : undefined
        }
      />
    </form>
  );
}
