"use client";

import { useActionState, useEffect, useMemo, useState, useTransition } from "react";
import { useFormStatus } from "react-dom";
import { useRouter } from "next/navigation";
import { Home, Loader2, MapPin, Pencil, Plus, Trash2 } from "lucide-react";
import { toast } from "sonner";
import {
  deleteAddressAction,
  saveAddressAction,
  setDefaultAddressAction,
  type AccountState,
} from "@/app/actions/account";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { cn } from "@/lib/utils";

export type AddressRecord = {
  id: string;
  label: string;
  fullName: string;
  phone: string;
  country: string;
  city: string;
  addressLine1: string;
  addressLine2: string | null;
  postalCode: string | null;
  isDefault: boolean;
};

const COUNTRY_CODES = [
  "MA", "FR", "BE", "NL", "ES", "IT", "DE", "PT", "IE", "AT", "LU", "DK", "SE", "FI", "PL", "CZ", "GR",
  "GB", "CH", "US", "CA", "AE", "SA", "QA", "KW", "TR", "AU", "JP", "SG",
];

type Labels = {
  title: string;
  desc: string;
  add: string;
  edit: string;
  empty: string;
  label: string;
  fullName: string;
  phone: string;
  country: string;
  city: string;
  address: string;
  address2: string;
  postalCode: string;
  isDefault: string;
  defaultBadge: string;
  setDefault: string;
  remove: string;
  save: string;
  cancel: string;
  saved: string;
  deleted: string;
  deleteConfirm: string;
  error: string;
};

const initial: AccountState = { status: "idle" };

export function AddressManager({
  locale,
  addresses,
  defaults,
  labels,
}: {
  locale: string;
  addresses: AddressRecord[];
  defaults: { fullName: string; phone: string; country: string };
  labels: Labels;
}) {
  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState<AddressRecord | null>(null);

  const countryNames = useMemo(() => {
    try {
      const display = new Intl.DisplayNames([locale === "ar" ? "ar" : locale], { type: "region" });
      return Object.fromEntries(COUNTRY_CODES.map((code) => [code, display.of(code) ?? code]));
    } catch {
      return Object.fromEntries(COUNTRY_CODES.map((code) => [code, code]));
    }
  }, [locale]);

  const openNew = () => {
    setEditing(null);
    setOpen(true);
  };

  const openEdit = (address: AddressRecord) => {
    setEditing(address);
    setOpen(true);
  };

  return (
    <div>
      <div className="flex flex-wrap items-end justify-between gap-4 border-b border-line pb-4">
        <div>
          <p className="eyebrow">{labels.title}</p>
          <h2 className="mt-2 font-serif text-3xl font-light">{labels.title}</h2>
          <p className="mt-1.5 max-w-lg text-[14px] leading-relaxed text-walnut">{labels.desc}</p>
        </div>
        <Button type="button" onClick={openNew} size="sm">
          <Plus className="h-3.5 w-3.5" />
          {labels.add}
        </Button>
      </div>

      {addresses.length === 0 ? (
        <div className="flex flex-col items-center py-16 text-center">
          <MapPin className="h-6 w-6 text-gold-ink" strokeWidth={1.1} />
          <p className="mt-4 font-serif text-xl text-charcoal">{labels.empty}</p>
          <Button type="button" variant="outline" className="mt-5" onClick={openNew}>
            {labels.add}
          </Button>
        </div>
      ) : (
        <div className="mt-6 grid gap-4 md:grid-cols-2">
          {addresses.map((address) => (
            <AddressCard
              key={address.id}
              address={address}
              locale={locale}
              countryName={countryNames[address.country] ?? address.country}
              labels={labels}
              onEdit={() => openEdit(address)}
            />
          ))}
        </div>
      )}

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editing ? labels.edit : labels.add}</DialogTitle>
            <DialogDescription>{labels.desc}</DialogDescription>
          </DialogHeader>
          <AddressForm
            key={editing?.id ?? "new"}
            locale={locale}
            address={editing}
            defaults={defaults}
            countryNames={countryNames}
            labels={labels}
            onDone={() => setOpen(false)}
          />
        </DialogContent>
      </Dialog>
    </div>
  );
}

function AddressCard({
  address,
  locale,
  countryName,
  labels,
  onEdit,
}: {
  address: AddressRecord;
  locale: string;
  countryName: string;
  labels: Labels;
  onEdit: () => void;
}) {
  const [pending, startTransition] = useTransition();
  const router = useRouter();

  const run = (action: (formData: FormData) => Promise<void>, success: string, confirmText?: string) => {
    if (confirmText && !window.confirm(confirmText)) return;
    startTransition(async () => {
      const formData = new FormData();
      formData.set("locale", locale);
      formData.set("id", address.id);
      await action(formData);
      toast.success(success);
      router.refresh();
    });
  };

  return (
    <article className={cn("relative border bg-cream p-5 shadow-panel", address.isDefault ? "border-line-strong" : "border-line")}>
      <div className="flex items-start justify-between gap-3">
        <div className="flex items-center gap-2">
          <Home className="h-3.5 w-3.5 text-gold-ink" strokeWidth={1.4} />
          <p className="text-[12px] uppercase tracking-[0.12em] text-charcoal">{address.label}</p>
        </div>
        {address.isDefault && <Badge variant="gold">{labels.defaultBadge}</Badge>}
      </div>

      <address className="mt-4 space-y-1 text-[14px] not-italic leading-relaxed text-walnut">
        <p className="text-charcoal">{address.fullName}</p>
        <p>{address.addressLine1}</p>
        {address.addressLine2 && <p>{address.addressLine2}</p>}
        <p>
          {address.postalCode ? `${address.postalCode} ` : ""}
          {address.city}
        </p>
        <p>{countryName}</p>
        <p>{address.phone}</p>
      </address>

      <div className="mt-5 flex flex-wrap items-center gap-x-4 gap-y-2 border-t border-line pt-3">
        <button
          type="button"
          onClick={onEdit}
          className="flex items-center gap-1.5 text-[12px] uppercase tracking-[0.1em] text-walnut hover:text-charcoal"
        >
          <Pencil className="h-3 w-3" />
          {labels.edit}
        </button>
        {!address.isDefault && (
          <button
            type="button"
            disabled={pending}
            onClick={() => run(setDefaultAddressAction, labels.saved)}
            className="text-[12px] uppercase tracking-[0.1em] text-walnut hover:text-charcoal disabled:opacity-60"
          >
            {labels.setDefault}
          </button>
        )}
        <button
          type="button"
          disabled={pending}
          onClick={() => run(deleteAddressAction, labels.deleted, labels.deleteConfirm)}
          className="flex items-center gap-1.5 text-[12px] uppercase tracking-[0.1em] text-walnut hover:text-terracotta disabled:opacity-60"
        >
          {pending ? <Loader2 className="h-3 w-3 animate-spin" /> : <Trash2 className="h-3 w-3" />}
          {labels.remove}
        </button>
      </div>
    </article>
  );
}

function AddressForm({
  locale,
  address,
  defaults,
  countryNames,
  labels,
  onDone,
}: {
  locale: string;
  address: AddressRecord | null;
  defaults: { fullName: string; phone: string; country: string };
  countryNames: Record<string, string>;
  labels: Labels;
  onDone: () => void;
}) {
  const [state, action] = useActionState(saveAddressAction, initial);
  const router = useRouter();

  useEffect(() => {
    if (state.status === "success") {
      toast.success(labels.saved);
      onDone();
      router.refresh();
    }
    if (state.status === "error" && state.message) toast.error(state.message);
  }, [state, labels.saved, onDone, router]);

  const errorFor = (field: string) => state.fieldErrors?.[field]?.[0];

  return (
    <form action={action} className="mt-2 space-y-4">
      <input type="hidden" name="locale" value={locale} />
      {address && <input type="hidden" name="id" value={address.id} />}

      <div className="grid gap-4 sm:grid-cols-2">
        <Field label={labels.label} className="sm:col-span-2">
          <Input name="label" defaultValue={address?.label ?? ""} placeholder="Domicile" className="h-10 bg-cream" />
        </Field>
        <Field label={labels.fullName} error={errorFor("fullName")} className="sm:col-span-2">
          <Input name="fullName" required defaultValue={address?.fullName ?? defaults.fullName} className="h-10 bg-cream" />
        </Field>
        <Field label={labels.phone} error={errorFor("phone")}>
          <Input name="phone" type="tel" required defaultValue={address?.phone ?? defaults.phone} className="h-10 bg-cream" />
        </Field>
        <Field label={labels.country} error={errorFor("country")}>
          <select
            name="country"
            defaultValue={address?.country ?? defaults.country}
            className="h-10 w-full border border-input bg-cream px-3 text-[14px] text-charcoal focus:border-gold-ink focus-visible:outline-none"
          >
            {COUNTRY_CODES.map((code) => (
              <option key={code} value={code}>
                {countryNames[code]}
              </option>
            ))}
          </select>
        </Field>
        <Field label={labels.city} error={errorFor("city")}>
          <Input name="city" required defaultValue={address?.city ?? ""} className="h-10 bg-cream" />
        </Field>
        <Field label={labels.postalCode} error={errorFor("postalCode")}>
          <Input name="postalCode" defaultValue={address?.postalCode ?? ""} className="h-10 bg-cream" />
        </Field>
        <Field label={labels.address} error={errorFor("addressLine1")} className="sm:col-span-2">
          <Input name="addressLine1" required defaultValue={address?.addressLine1 ?? ""} className="h-10 bg-cream" />
        </Field>
        <Field label={labels.address2} error={errorFor("addressLine2")} className="sm:col-span-2">
          <Input name="addressLine2" defaultValue={address?.addressLine2 ?? ""} className="h-10 bg-cream" />
        </Field>
      </div>

      <label className="flex items-center gap-2.5 text-[13px] text-walnut">
        <input
          type="checkbox"
          name="isDefault"
          defaultChecked={address?.isDefault ?? false}
          className="h-3.5 w-3.5 accent-[#24221D]"
        />
        {labels.isDefault}
      </label>

      <div className="flex justify-end gap-2 pt-2">
        <Button type="button" variant="ghost" onClick={onDone}>
          {labels.cancel}
        </Button>
        <SaveAddressButton label={labels.save} />
      </div>
    </form>
  );
}

function SaveAddressButton({ label }: { label: string }) {
  const { pending } = useFormStatus();

  return (
    <Button type="submit" disabled={pending} aria-busy={pending}>
      {pending && <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />}
      {label}
    </Button>
  );
}

function Field({
  label,
  error,
  className,
  children,
}: {
  label: string;
  error?: string;
  className?: string;
  children: React.ReactNode;
}) {
  return (
    <div className={className}>
      <Label className="mb-1.5 block text-[12px] uppercase tracking-[0.1em] text-walnut">{label}</Label>
      {children}
      {error && <p className="mt-1 text-[12px] text-terracotta">{error}</p>}
    </div>
  );
}
