import { useState } from "react";
import { DollarSign, Plus, Trash2, ArrowUp, ArrowDown, Star, CheckCircle2, AlertCircle } from "lucide-react";
import CmsLayout from "./CmsLayout";
import { PageHeader, SectionCard, Field, TextInput, Select, Toggle, SaveBar, Badge, ColorPicker } from "./ui";
import { useSiteSettings } from "@/hooks/useSiteSettings";

type Plan = {
  id: string;
  name: string;
  type: "Shared" | "Cloud VPS" | "Virtual Dedicated" | "Dedicated Server";
  monthly: number;
  yearly: number;
  cpu: string;
  ram: string;
  storage: string;
  bandwidth: string;
  highlight: boolean;
};

type PricingState = {
  layout: "cards3" | "cards4" | "table" | "compact";
  accent: string;
  showYearlyToggle: boolean;
  yearlyDiscountLabel: string;
  plans: Plan[];
};

const DEFAULTS: PricingState = {
  layout: "cards3",
  accent: "#f5c400",
  showYearlyToggle: true,
  yearlyDiscountLabel: "-20%",
  plans: [
    { id: "p1", name: "Starter VPS", type: "Cloud VPS", monthly: 12.99, yearly: 129, cpu: "2 vCPU", ram: "4 GB", storage: "80 GB NVMe", bandwidth: "4 TB", highlight: false },
    { id: "p2", name: "Business VDS", type: "Virtual Dedicated", monthly: 39.99, yearly: 399, cpu: "6 vCPU", ram: "16 GB", storage: "250 GB NVMe", bandwidth: "10 TB", highlight: true },
    { id: "p3", name: "Enterprise Dedicated", type: "Dedicated Server", monthly: 89.99, yearly: 899, cpu: "16 Cores Xeon", ram: "64 GB", storage: "2× 1 TB NVMe", bandwidth: "Unmetered", highlight: false },
  ],
};

export default function CmsPricing() {
  const { value: state, setValue: setState, save, loading, saving } = useSiteSettings<PricingState>("pricing_layout", DEFAULTS);
  const [toast, setToast] = useState<{ ok: boolean; msg: string } | null>(null);

  const notify = (ok: boolean, msg: string) => {
    setToast({ ok, msg });
    setTimeout(() => setToast(null), 3500);
  };

  const update = <K extends keyof PricingState>(k: K, v: PricingState[K]) =>
    setState({ ...state, [k]: v });

  const handleSave = async () => {
    const r = await save();
    if (r.ok) notify(true, "Pricing layout saved. Tip: use Plan Management for the service-specific plan catalog.");
    else notify(false, r.error || "Save failed.");
  };

  const addPlan = () => {
    const id = Date.now().toString();
    update("plans", [...state.plans, { id, name: "New Plan", type: "Cloud VPS", monthly: 9.99, yearly: 99, cpu: "1 vCPU", ram: "1 GB", storage: "25 GB", bandwidth: "1 TB", highlight: false }]);
  };
  const removePlan = (id: string) => update("plans", state.plans.filter((p) => p.id !== id));
  const editPlan = (id: string, patch: Partial<Plan>) =>
    update("plans", state.plans.map((p) => (p.id === id ? { ...p, ...patch } : p)));
  const movePlan = (id: string, dir: -1 | 1) => {
    const i = state.plans.findIndex((p) => p.id === id);
    if (i < 0) return;
    const j = i + dir;
    if (j < 0 || j >= state.plans.length) return;
    const next = [...state.plans];
    [next[i], next[j]] = [next[j], next[i]];
    update("plans", next);
  };

  const gridCols = state.layout === "cards4" ? "md:grid-cols-4" : "md:grid-cols-3";

  return (
    <CmsLayout>
      <PageHeader
        icon={<DollarSign className="w-6 h-6" />}
        title="Pricing Plans"
        description="Manage your pricing matrix, layout, and styling. For service-specific plans, use Plan Management."
      />

      {loading && (
        <div className="mb-4 p-3 rounded-lg bg-blue-50 border border-blue-200 text-sm text-blue-800">Loading saved layout…</div>
      )}
      {toast && (
        <div className={`mb-4 p-3 rounded-lg text-sm flex items-center gap-2 ${toast.ok ? "bg-emerald-50 border border-emerald-200 text-emerald-800" : "bg-red-50 border border-red-200 text-red-800"}`}>
          {toast.ok ? <CheckCircle2 className="w-4 h-4" /> : <AlertCircle className="w-4 h-4" />}
          {toast.msg}
        </div>
      )}

      <SectionCard title="Layout & Style">
        <div className="grid md:grid-cols-3 gap-5">
          <Field label="Layout">
            <Select value={state.layout} onChange={(e) => update("layout", e.target.value as PricingState["layout"])}>
              <option value="cards3">3-column cards</option>
              <option value="cards4">4-column cards</option>
              <option value="table">Comparison table</option>
              <option value="compact">Compact list</option>
            </Select>
          </Field>
          <ColorPicker label="Accent" value={state.accent} onChange={(v) => update("accent", v)} />
          <Field label="Yearly discount label"><TextInput value={state.yearlyDiscountLabel} onChange={(e) => update("yearlyDiscountLabel", e.target.value)} /></Field>
        </div>
        <Toggle label="Show monthly / yearly billing toggle" checked={state.showYearlyToggle} onChange={(v) => update("showYearlyToggle", v)} />
      </SectionCard>

      <div className="h-6" />
      <SectionCard
        title="Plans"
        description="Add, edit, reorder or delete plans. Highlighted plan appears as 'Most Popular'."
        actions={
          <button onClick={addPlan} className="px-3 py-1.5 rounded-lg bg-[#0b6e3e] text-white text-xs font-semibold inline-flex items-center gap-1 hover:bg-[#0a8048]">
            <Plus className="w-3.5 h-3.5" /> Add Plan
          </button>
        }
      >
        <div className="space-y-4">
          {state.plans.map((p, idx) => (
            <div key={p.id} className="rounded-xl border border-slate-200 bg-slate-50 p-4">
              <div className="flex items-center justify-between mb-3">
                <div className="flex items-center gap-2">
                  <Badge tone="blue">Plan {idx + 1}</Badge>
                  {p.highlight && <Badge tone="yellow">★ Most Popular</Badge>}
                </div>
                <div className="flex items-center gap-1">
                  <button onClick={() => movePlan(p.id, -1)} className="p-1.5 rounded hover:bg-slate-200" aria-label="Move up"><ArrowUp className="w-4 h-4" /></button>
                  <button onClick={() => movePlan(p.id, 1)} className="p-1.5 rounded hover:bg-slate-200" aria-label="Move down"><ArrowDown className="w-4 h-4" /></button>
                  <button onClick={() => editPlan(p.id, { highlight: !p.highlight })} className="p-1.5 rounded hover:bg-amber-100 text-amber-600" aria-label="Toggle highlight"><Star className="w-4 h-4" /></button>
                  <button onClick={() => removePlan(p.id)} className="p-1.5 rounded hover:bg-red-100 text-red-600" aria-label="Remove"><Trash2 className="w-4 h-4" /></button>
                </div>
              </div>
              <div className="grid md:grid-cols-3 gap-3">
                <Field label="Name"><TextInput value={p.name} onChange={(e) => editPlan(p.id, { name: e.target.value })} /></Field>
                <Field label="Type">
                  <Select value={p.type} onChange={(e) => editPlan(p.id, { type: e.target.value as Plan["type"] })}>
                    <option>Shared</option>
                    <option>Cloud VPS</option>
                    <option>Virtual Dedicated</option>
                    <option>Dedicated Server</option>
                  </Select>
                </Field>
                <div />
                <Field label="Monthly price ($)"><TextInput type="number" step="0.01" value={p.monthly} onChange={(e) => editPlan(p.id, { monthly: Number(e.target.value) })} /></Field>
                <Field label="Yearly price ($)"><TextInput type="number" step="0.01" value={p.yearly} onChange={(e) => editPlan(p.id, { yearly: Number(e.target.value) })} /></Field>
                <div />
                <Field label="CPU"><TextInput value={p.cpu} onChange={(e) => editPlan(p.id, { cpu: e.target.value })} /></Field>
                <Field label="RAM"><TextInput value={p.ram} onChange={(e) => editPlan(p.id, { ram: e.target.value })} /></Field>
                <Field label="Storage"><TextInput value={p.storage} onChange={(e) => editPlan(p.id, { storage: e.target.value })} /></Field>
                <Field label="Bandwidth"><TextInput value={p.bandwidth} onChange={(e) => editPlan(p.id, { bandwidth: e.target.value })} /></Field>
              </div>
            </div>
          ))}
        </div>
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Live Preview" description="Approximation of how plans will render on the site.">
        {state.layout === "table" ? (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[640px] text-sm">
              <thead className="bg-[#0b6e3e] text-white">
                <tr>
                  <th className="p-3 text-left">Plan</th>
                  <th className="p-3">CPU</th>
                  <th className="p-3">RAM</th>
                  <th className="p-3">Storage</th>
                  <th className="p-3">Bandwidth</th>
                  <th className="p-3">Monthly</th>
                </tr>
              </thead>
              <tbody>
                {state.plans.map((p, i) => (
                  <tr key={p.id} className={i % 2 ? "bg-slate-50" : "bg-white"}>
                    <td className="p-3 font-bold">{p.name}</td>
                    <td className="p-3 text-center">{p.cpu}</td>
                    <td className="p-3 text-center">{p.ram}</td>
                    <td className="p-3 text-center">{p.storage}</td>
                    <td className="p-3 text-center">{p.bandwidth}</td>
                    <td className="p-3 text-center font-bold" style={{ color: state.accent }}>${p.monthly}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : state.layout === "compact" ? (
          <div className="space-y-2">
            {state.plans.map((p) => (
              <div key={p.id} className="flex items-center justify-between bg-white border border-slate-200 rounded-xl p-4">
                <div>
                  <div className="font-bold text-slate-900">{p.name} <span className="text-xs text-slate-500 ml-1">{p.type}</span></div>
                  <div className="text-xs text-slate-500">{p.cpu} · {p.ram} · {p.storage}</div>
                </div>
                <div className="font-extrabold text-lg" style={{ color: state.accent }}>${p.monthly}/mo</div>
              </div>
            ))}
          </div>
        ) : (
          <div className={`grid gap-4 ${gridCols}`}>
            {state.plans.map((p) => (
              <div key={p.id} className={`rounded-2xl p-5 border ${p.highlight ? "bg-[#063019] text-white border-[#0b6e3e] shadow-lg" : "bg-white text-slate-900 border-slate-200"}`}>
                {p.highlight && <div className="text-[10px] uppercase tracking-widest font-bold mb-1" style={{ color: state.accent }}>Most Popular</div>}
                <div className="text-xs uppercase font-bold mb-1" style={{ color: state.accent }}>{p.type}</div>
                <div className="text-lg font-extrabold">{p.name}</div>
                <div className="mt-2"><span className="text-3xl font-extrabold">${p.monthly}</span><span className={`text-xs ml-1 ${p.highlight ? "text-slate-300" : "text-slate-500"}`}>/mo</span></div>
                <ul className={`mt-3 space-y-1 text-xs ${p.highlight ? "text-slate-200" : "text-slate-600"}`}>
                  <li>• {p.cpu}</li><li>• {p.ram}</li><li>• {p.storage}</li><li>• {p.bandwidth}</li>
                </ul>
              </div>
            ))}
          </div>
        )}
      </SectionCard>

      <SaveBar onSave={handleSave} onReset={() => setState(DEFAULTS)} saving={saving} />
    </CmsLayout>
  );
}