"use client";

import { Check, Copy, ExternalLink, Globe2, LoaderCircle, Palette, Plus, Save, Store, X } from "lucide-react";
import { FormEvent, useCallback, useEffect, useState } from "react";
import { languageNames, type TenantConfig, useTenant } from "@/components/tenant-provider";

const languages = ["en", "hi", "bn", "ta", "te", "mr"];

export default function TenantSettings() {
  const { tenant: activeTenant, refreshTenant } = useTenant();
  const [tenants, setTenants] = useState<TenantConfig[]>([]);
  const [selected, setSelected] = useState<TenantConfig | null>(null);
  const [creating, setCreating] = useState(false);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const [notice, setNotice] = useState("");

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const response = await fetch("/api/tenant?includeAll=1", { cache: "no-store" });
      const data = (await response.json()) as { tenants?: TenantConfig[]; error?: string };
      if (!response.ok) throw new Error(data.error || "Could not load tenants");
      const rows = data.tenants ?? [];
      setTenants(rows);
      setSelected((current) => rows.find((item) => item.id === current?.id) || rows.find((item) => item.slug === activeTenant.slug) || rows[0] || null);
    } catch (reason) {
      setError(reason instanceof Error ? reason.message : "Could not load tenants");
    } finally {
      setLoading(false);
    }
  }, [activeTenant.slug]);

  useEffect(() => { void load(); }, [load]);
  useEffect(() => { if (!notice) return; const timer = window.setTimeout(() => setNotice(""), 2500); return () => window.clearTimeout(timer); }, [notice]);

  async function save(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setSaving(true);
    setError("");
    const form = new FormData(event.currentTarget);
    const body = {
      ...(creating ? {} : { id: selected?.id }),
      ...Object.fromEntries(form.entries()),
      supportedLanguages: form.getAll("supportedLanguages"),
    };
    try {
      const response = await fetch("/api/tenant", {
        method: creating ? "POST" : "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      const data = (await response.json()) as { tenant?: TenantConfig; error?: string };
      if (!response.ok || !data.tenant) throw new Error(data.error || "Could not save tenant settings");
      if (creating) {
        setCreating(false);
        setSelected(data.tenant);
      }
      setNotice(creating ? "New tenant created" : "Brand settings saved");
      await load();
      if (data.tenant.slug === activeTenant.slug) await refreshTenant();
    } catch (reason) {
      setError(reason instanceof Error ? reason.message : "Could not save tenant settings");
    } finally {
      setSaving(false);
    }
  }

  async function activate(tenant: TenantConfig) {
    window.localStorage.setItem("active-tenant", tenant.slug);
    document.cookie = `tenant_slug=${encodeURIComponent(tenant.slug)}; path=/; max-age=31536000; samesite=lax`;
    await refreshTenant();
    setNotice(`${tenant.brandName} is now the active workspace`);
    window.setTimeout(() => window.location.reload(), 350);
  }

  const previewUrl = selected ? `/?tenant=${encodeURIComponent(selected.slug)}` : "/";
  const formKey = creating ? "new" : selected?.id || "none";

  return (
    <div className="grid gap-5 xl:grid-cols-[0.34fr_0.66fr]">
      <aside className="h-fit rounded-2xl border border-slate-200 bg-white p-4 shadow-sm xl:sticky xl:top-5">
        <div className="flex items-center justify-between"><div><h2 className="font-black">Resale tenants</h2><p className="mt-1 text-[9px] text-slate-400">{tenants.length} configured storefronts</p></div><button onClick={() => { setCreating(true); setError(""); }} className="grid h-9 w-9 place-items-center rounded-xl bg-[var(--brand)] text-white" aria-label="Create tenant"><Plus size={16} /></button></div>
        <div className="mt-4 space-y-2">{loading ? <div className="flex justify-center p-8"><LoaderCircle className="animate-spin text-slate-400" /></div> : tenants.map((item) => <button key={item.id} onClick={() => { setSelected(item); setCreating(false); setError(""); }} className={`flex w-full items-center gap-3 rounded-xl border p-3 text-left ${!creating && selected?.id === item.id ? "border-blue-200 bg-blue-50" : "border-slate-100 hover:bg-slate-50"}`}><span className="grid h-10 w-10 shrink-0 place-items-center rounded-xl text-sm font-black text-white" style={{ backgroundColor: item.primaryColor }}>{item.brandName.charAt(0)}</span><div className="min-w-0 flex-1"><p className="truncate text-xs font-black">{item.brandName}</p><p className="mt-1 truncate text-[9px] text-slate-400">{item.customDomain || `?tenant=${item.slug}`}</p></div>{item.slug === activeTenant.slug && <span className="h-2 w-2 rounded-full bg-green-500" title="Active tenant" />}</button>)}</div>
        {selected && !creating && <div className="mt-4 grid grid-cols-2 gap-2"><button onClick={() => void activate(selected)} disabled={selected.slug === activeTenant.slug} className="rounded-lg bg-slate-100 px-2 py-2 text-[9px] font-black disabled:text-green-600">{selected.slug === activeTenant.slug ? "Active workspace" : "Switch workspace"}</button><a href={previewUrl} target="_blank" className="flex items-center justify-center gap-1 rounded-lg bg-slate-100 px-2 py-2 text-[9px] font-black">Preview <ExternalLink size={11} /></a></div>}
      </aside>

      <section className="overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm">
        <div className="flex flex-wrap items-center justify-between gap-3 border-b border-slate-100 p-5"><div className="flex items-center gap-3"><span className="grid h-10 w-10 place-items-center rounded-xl bg-blue-50 text-[var(--brand)]">{creating ? <Plus size={19} /> : <Palette size={19} />}</span><div><h2 className="font-black">{creating ? "Create resale tenant" : `Brand settings — ${selected?.brandName || "Tenant"}`}</h2><p className="mt-1 text-[9px] text-slate-400">Everything here changes without editing code.</p></div></div>{creating && <button onClick={() => setCreating(false)} className="grid h-9 w-9 place-items-center rounded-full bg-slate-100"><X size={16} /></button>}</div>
        {(creating || selected) && <form key={formKey} onSubmit={save} className="p-5">
          <SectionTitle icon={Store} title="Brand identity" text="Store name, legal entity and assets" />
          <div className="mt-4 grid gap-4 sm:grid-cols-2"><Field name="brandName" label="Brand name *" defaultValue={creating ? "" : selected?.brandName} required /><Field name="slug" label="Tenant slug *" defaultValue={creating ? "" : selected?.slug} placeholder="my-store" required /><Field name="legalName" label="Legal company name *" defaultValue={creating ? "" : selected?.legalName} required /><Field name="tagline" label="Tagline" defaultValue={creating ? "Shop happy, save more" : selected?.tagline} /><Field name="logoUrl" label="Logo URL" defaultValue={creating ? "" : selected?.logoUrl || ""} placeholder="https://…/logo.png" /><Field name="faviconUrl" label="Favicon URL" defaultValue={creating ? "" : selected?.faviconUrl || ""} placeholder="https://…/favicon.png" /><Field name="customDomain" label="Custom domain" defaultValue={creating ? "" : selected?.customDomain || ""} placeholder="shop.example.com" /><SelectField name="plan" label="Tenant plan" defaultValue={creating ? "business" : selected?.plan || "business"} options={["starter", "business", "enterprise"]} /><Field name="appName" label="Mobile app name" defaultValue={creating ? "" : selected?.appName || ""} placeholder="My Store App" /><Field name="androidAppUrl" label="Android APK / Play link" defaultValue={creating ? "" : selected?.androidAppUrl || ""} placeholder="https://…/application.apk" /><Field name="iosAppUrl" label="iPhone App Store link" defaultValue={creating ? "" : selected?.iosAppUrl || ""} placeholder="https://apps.apple.com/…" /></div>

          <SectionTitle icon={Globe2} title="Contact & legal" text="Shown in the footer, support and invoices" />
          <div className="mt-4 grid gap-4 sm:grid-cols-2"><Field name="supportEmail" type="email" label="Support email *" defaultValue={creating ? "" : selected?.supportEmail} required /><Field name="phonePrimary" label="Primary phone *" defaultValue={creating ? "" : selected?.phonePrimary} required /><Field name="phoneSecondary" label="Secondary phone" defaultValue={creating ? "" : selected?.phoneSecondary || ""} /><Field name="whatsapp" label="WhatsApp" defaultValue={creating ? "" : selected?.whatsapp || ""} /><Field name="gstin" label="GSTIN" defaultValue={creating ? "" : selected?.gstin || ""} /><Field name="address" label="Registered address" defaultValue={creating ? "" : selected?.address || ""} /><Field name="city" label="City" defaultValue={creating ? "" : selected?.city || ""} /><Field name="state" label="State" defaultValue={creating ? "" : selected?.state || ""} /><Field name="pincode" label="PIN code" defaultValue={creating ? "" : selected?.pincode || ""} /><Field name="country" label="Country" defaultValue={creating ? "India" : selected?.country} /><Field name="currency" label="Currency" defaultValue={creating ? "INR" : selected?.currency} /><SelectField name="status" label="Store status" defaultValue={creating ? "active" : selected?.status || "active"} options={["active", "suspended"]} /></div>

          <SectionTitle icon={Palette} title="Theme & storefront" text="Colors and customer-facing homepage copy" />
          <div className="mt-4 grid gap-4 sm:grid-cols-3"><ColorField name="primaryColor" label="Primary" defaultValue={creating ? "#155ee9" : selected?.primaryColor || "#155ee9"} /><ColorField name="secondaryColor" label="Navigation" defaultValue={creating ? "#071f4a" : selected?.secondaryColor || "#071f4a"} /><ColorField name="accentColor" label="Accent" defaultValue={creating ? "#ffb21d" : selected?.accentColor || "#ffb21d"} /></div>
          <div className="mt-4 grid gap-4"><Field name="heroTitle" label="Homepage hero title" defaultValue={creating ? "Everything you love, at prices you’ll love." : selected?.heroTitle} /><TextField name="heroSubtitle" label="Homepage hero description" defaultValue={creating ? "Discover trusted products, sellers and great deals." : selected?.heroSubtitle} /><TextField name="footerText" label="Footer description" defaultValue={creating ? "Your trusted online marketplace." : selected?.footerText || ""} /></div>

          <SectionTitle icon={Globe2} title="Language & locale" text="Choose what shoppers can use and the tenant default" />
          <div className="mt-4 grid gap-4 sm:grid-cols-2"><label className="input-label">Default language<select name="defaultLanguage" defaultValue={creating ? "en" : selected?.defaultLanguage || "en"} className="checkout-input">{languages.map((code) => <option key={code} value={code}>{languageNames[code]}</option>)}</select></label><div className="input-label"><span>Languages available to shoppers *</span><div className="flex min-h-11 flex-wrap items-center gap-3 rounded-xl border border-slate-200 px-3 py-2">{languages.map((code) => <label key={code} className="flex items-center gap-1.5 text-[10px]"><input type="checkbox" name="supportedLanguages" value={code} defaultChecked={creating ? ["en", "hi"].includes(code) : selected?.supportedLanguages.includes(code)} className="accent-[var(--brand)]" />{languageNames[code]}</label>)}</div></div></div>

          {error && <p className="mt-5 rounded-xl bg-red-50 p-3 text-xs font-bold text-red-600">{error}</p>}
          <div className="mt-6 flex flex-wrap items-center justify-between gap-3 border-t border-slate-100 pt-5"><div className="flex items-center gap-2 text-[9px] text-slate-400"><Copy size={12} /> Preview with <code>?tenant={creating ? "your-slug" : selected?.slug}</code></div><button disabled={saving} className="flex items-center gap-2 rounded-xl bg-[var(--brand)] px-6 py-3 text-xs font-black text-white shadow-lg disabled:opacity-60">{saving ? <LoaderCircle size={15} className="animate-spin" /> : <Save size={15} />}{creating ? "Create tenant" : "Save all settings"}</button></div>
        </form>}
      </section>
      {notice && <div className="fixed bottom-6 left-1/2 z-[90] flex -translate-x-1/2 items-center gap-2 rounded-xl bg-[#101d37] px-5 py-3 text-xs font-bold text-white shadow-2xl"><Check size={14} className="text-green-400" />{notice}</div>}
    </div>
  );
}

function SectionTitle({ icon: Icon, title, text }: { icon: React.ElementType; title: string; text: string }) { return <div className="mt-8 flex items-center gap-3 border-b border-slate-100 pb-3 first:mt-0"><span className="grid h-8 w-8 place-items-center rounded-lg bg-slate-100 text-[var(--brand)]"><Icon size={15} /></span><div><h3 className="text-xs font-black">{title}</h3><p className="mt-0.5 text-[9px] text-slate-400">{text}</p></div></div>; }
function Field({ name, label, type = "text", defaultValue, placeholder, required }: { name: string; label: string; type?: string; defaultValue?: string | null; placeholder?: string; required?: boolean }) { return <label className="input-label">{label}<input name={name} type={type} required={required} defaultValue={defaultValue || ""} placeholder={placeholder} className="checkout-input" /></label>; }
function TextField({ name, label, defaultValue }: { name: string; label: string; defaultValue?: string | null }) { return <label className="input-label">{label}<textarea name={name} rows={3} defaultValue={defaultValue || ""} className="checkout-input resize-none" /></label>; }
function ColorField({ name, label, defaultValue }: { name: string; label: string; defaultValue: string }) { return <label className="input-label">{label}<span className="flex h-11 items-center gap-2 rounded-xl border border-slate-200 px-2"><input type="color" name={name} defaultValue={defaultValue} className="h-7 w-9 rounded border-0 bg-transparent" /><span className="text-[10px] font-bold text-slate-500">{defaultValue}</span></span></label>; }
function SelectField({ name, label, defaultValue, options }: { name: string; label: string; defaultValue: string; options: string[] }) { return <label className="input-label">{label}<select name={name} defaultValue={defaultValue} className="checkout-input">{options.map((option) => <option key={option}>{option}</option>)}</select></label>; }
