// @File: src/pages/admin/cms/whatsapp/CmsWhatsappPackages.tsx
// @Desc: CRUD console for WhatsApp reseller packages. Lets the admin
//        create, edit, toggle active, and soft-delete plan entries.
import { FormEvent, useEffect, useMemo, useState } from "react";
import {
  Layers,
  Plus,
  Pencil,
  Trash2,
  Loader2,
  Check,
  X,
  Star,
} from "lucide-react";
import CmsLayout from "../CmsLayout";
import { PageHeader, SectionCard, Badge, Field, TextInput, TextArea, Select } from "../ui";
import {
  waAdminCreatePackage,
  waAdminDeletePackage,
  waAdminListPackages,
  waAdminUpdatePackage,
  type WhatsappPackage,
  type WhatsappPackagePayload,
} from "@/lib/whatsappApi";

const EMPTY: WhatsappPackagePayload = {
  slug: "",
  name: "",
  description: "",
  tagline: "",
  max_devices: 1,
  devices_unlimited: false,
  messages_per_month: 1000,
  messages_unlimited: false,
  max_contacts: 1000,
  contacts_unlimited: false,
  max_campaigns: 5,
  campaigns_unlimited: false,
  max_workflows: 5,
  workflows_unlimited: false,
  max_team_operators: 1,
  team_operators_unlimited: false,
  chat_retention_days: 90,
  auto_reply_allowed: false,
  ai_assistant_allowed: false,
  workflow_automation_allowed: false,
  webhook_access_allowed: false,
  api_access_allowed: false,
  media_sending_allowed: true,
  template_messages_allowed: false,
  whmcs_product_id: null,
  terminate_action: "archive",
  is_active: true,
  is_featured: false,
  price_per_month: "",
  sort_order: 0,
};

function Toggle({
  checked,
  onChange,
  label,
}: {
  checked: boolean;
  onChange: (v: boolean) => void;
  label: string;
}) {
  return (
    <label className="flex items-center justify-between gap-2 px-3 py-2 rounded-lg border border-slate-200 bg-white text-sm">
      <span className="text-slate-700">{label}</span>
      <button
        type="button"
        onClick={() => onChange(!checked)}
        className={`relative w-10 h-6 rounded-full transition ${
          checked ? "bg-[#0b6e3e]" : "bg-slate-300"
        }`}
        aria-pressed={checked}
      >
        <span
          className={`absolute top-0.5 left-0.5 w-5 h-5 rounded-full bg-white shadow transition ${
            checked ? "translate-x-4" : ""
          }`}
        />
      </button>
    </label>
  );
}

export default function CmsWhatsappPackages() {
  const [rows, setRows] = useState<WhatsappPackage[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [editing, setEditing] = useState<WhatsappPackage | null>(null);
  const [form, setForm] = useState<WhatsappPackagePayload>(EMPTY);
  const [showForm, setShowForm] = useState(false);
  const [saving, setSaving] = useState(false);

  const load = async () => {
    setLoading(true);
    setError(null);
    try {
      const list = await waAdminListPackages(true);
      setRows(list);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to load packages");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    void load();
  }, []);

  const openCreate = () => {
    setEditing(null);
    setForm(EMPTY);
    setShowForm(true);
  };

  const openEdit = (pkg: WhatsappPackage) => {
    setEditing(pkg);
    setForm({ ...pkg });
    setShowForm(true);
  };

  const closeForm = () => {
    setShowForm(false);
    setEditing(null);
    setForm(EMPTY);
  };

  const update = <K extends keyof WhatsappPackagePayload>(
    key: K,
    value: WhatsappPackagePayload[K],
  ) => setForm((prev) => ({ ...prev, [key]: value }));

  const submit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setSaving(true);
    setError(null);
    try {
      if (editing) {
        await waAdminUpdatePackage(editing.id, form);
      } else {
        await waAdminCreatePackage(form);
      }
      closeForm();
      await load();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Save failed");
    } finally {
      setSaving(false);
    }
  };

  const remove = async (pkg: WhatsappPackage) => {
    if (!confirm(`Deactivate package "${pkg.name}"? Existing subscriptions remain valid.`))
      return;
    try {
      await waAdminDeletePackage(pkg.id);
      await load();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Delete failed");
    }
  };

  const sorted = useMemo(
    () => [...rows].sort((a, b) => a.sort_order - b.sort_order || a.id - b.id),
    [rows],
  );

  return (
    <CmsLayout>
      <PageHeader
        icon={<Layers className="w-6 h-6" />}
        title="WhatsApp Packages"
        description="Define the WhatsApp reseller plans you sell — quotas, feature flags, pricing and WHMCS linkage."
      />

      <SectionCard
        title={`Packages (${rows.length})`}
        description="Soft-delete keeps historical subscriptions valid. Featured plans show up first on the marketing page."
        actions={
          <button
            type="button"
            onClick={openCreate}
            className="px-3 py-2 rounded-lg bg-[#0b6e3e] text-white text-xs font-semibold hover:bg-[#0a8048] transition inline-flex items-center gap-2"
          >
            <Plus className="w-4 h-4" />
            New Package
          </button>
        }
      >
        {error && (
          <div className="rounded-lg border border-rose-200 bg-rose-50 p-3 text-sm text-rose-700">
            {error}
          </div>
        )}

        <div className="overflow-x-auto rounded-xl border border-slate-200">
          <table className="min-w-full text-sm">
            <thead className="bg-slate-50 text-slate-600">
              <tr>
                <th className="text-left p-3 font-semibold">Package</th>
                <th className="text-left p-3 font-semibold">Quotas</th>
                <th className="text-left p-3 font-semibold">Features</th>
                <th className="text-left p-3 font-semibold">Price</th>
                <th className="text-left p-3 font-semibold">Status</th>
                <th className="text-right p-3 font-semibold">Actions</th>
              </tr>
            </thead>
            <tbody>
              {loading && (
                <tr>
                  <td colSpan={6} className="p-6 text-center text-slate-500">
                    <Loader2 className="w-4 h-4 animate-spin inline mr-2" /> Loading…
                  </td>
                </tr>
              )}
              {!loading && sorted.length === 0 && (
                <tr>
                  <td colSpan={6} className="p-6 text-center text-slate-500">
                    No packages yet — click “New Package” to create one.
                  </td>
                </tr>
              )}
              {sorted.map((p) => (
                <tr key={p.id} className="border-t border-slate-200">
                  <td className="p-3 align-top">
                    <div className="font-semibold text-slate-900 flex items-center gap-1.5">
                      {p.name}
                      {p.is_featured && (
                        <Star className="w-3.5 h-3.5 text-amber-500 fill-amber-400" />
                      )}
                    </div>
                    <div className="text-[11px] text-slate-500 font-mono">{p.slug}</div>
                    {p.tagline && (
                      <div className="text-xs text-slate-500 mt-0.5">{p.tagline}</div>
                    )}
                  </td>
                  <td className="p-3 align-top text-xs text-slate-700 space-y-0.5">
                    <div>
                      Devices: {p.devices_unlimited ? "∞" : p.max_devices}
                    </div>
                    <div>
                      Messages/mo: {p.messages_unlimited ? "∞" : p.messages_per_month.toLocaleString()}
                    </div>
                    <div>
                      Contacts: {p.contacts_unlimited ? "∞" : p.max_contacts.toLocaleString()}
                    </div>
                    <div>
                      Campaigns: {p.campaigns_unlimited ? "∞" : p.max_campaigns}
                    </div>
                    <div>
                      Operators: {p.team_operators_unlimited ? "∞" : p.max_team_operators}
                    </div>
                  </td>
                  <td className="p-3 align-top">
                    <div className="flex flex-wrap gap-1">
                      {p.auto_reply_allowed && <Badge tone="blue">Auto-Reply</Badge>}
                      {p.ai_assistant_allowed && <Badge tone="violet">AI</Badge>}
                      {p.workflow_automation_allowed && <Badge tone="blue">Workflows</Badge>}
                      {p.api_access_allowed && <Badge tone="slate">API</Badge>}
                      {p.webhook_access_allowed && <Badge tone="slate">Webhooks</Badge>}
                      {p.template_messages_allowed && <Badge tone="amber">Templates</Badge>}
                      {!p.media_sending_allowed && <Badge tone="red">No Media</Badge>}
                    </div>
                  </td>
                  <td className="p-3 align-top text-sm text-slate-700">
                    {p.price_per_month || <span className="text-slate-400">—</span>}
                    {p.whmcs_product_id != null && (
                      <div className="text-[11px] text-slate-500">
                        WHMCS #{p.whmcs_product_id}
                      </div>
                    )}
                  </td>
                  <td className="p-3 align-top">
                    {p.is_active ? (
                      <Badge tone="green">Active</Badge>
                    ) : (
                      <Badge tone="slate">Inactive</Badge>
                    )}
                  </td>
                  <td className="p-3 align-top text-right">
                    <div className="inline-flex gap-1">
                      <button
                        onClick={() => openEdit(p)}
                        className="p-1.5 rounded-lg border border-slate-200 hover:bg-slate-100 text-slate-600"
                        title="Edit"
                      >
                        <Pencil className="w-4 h-4" />
                      </button>
                      <button
                        onClick={() => remove(p)}
                        className="p-1.5 rounded-lg border border-rose-200 hover:bg-rose-50 text-rose-600"
                        title="Deactivate"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </SectionCard>

      {showForm && (
        <div className="fixed inset-0 z-50 bg-black/40 flex items-start justify-center p-4 overflow-y-auto">
          <form
            onSubmit={submit}
            className="bg-white rounded-2xl shadow-2xl border border-slate-200 w-full max-w-3xl my-8"
          >
            <div className="flex items-center justify-between px-6 py-4 border-b border-slate-200">
              <div>
                <h3 className="text-lg font-bold text-slate-900">
                  {editing ? `Edit: ${editing.name}` : "New WhatsApp Package"}
                </h3>
                <p className="text-xs text-slate-500">
                  Leave a number blank and tick “Unlimited” to disable that quota.
                </p>
              </div>
              <button
                type="button"
                onClick={closeForm}
                className="p-2 rounded-lg hover:bg-slate-100"
              >
                <X className="w-4 h-4" />
              </button>
            </div>

            <div className="p-6 space-y-5 max-h-[70vh] overflow-y-auto">
              <div className="grid md:grid-cols-2 gap-4">
                <Field label="Slug" required hint="lowercase, no spaces">
                  <TextInput
                    required
                    value={form.slug}
                    onChange={(e) => update("slug", e.target.value.trim())}
                    placeholder="starter / pro / enterprise"
                  />
                </Field>
                <Field label="Name" required>
                  <TextInput
                    required
                    value={form.name}
                    onChange={(e) => update("name", e.target.value)}
                    placeholder="WhatsApp Pro"
                  />
                </Field>
              </div>

              <Field label="Tagline">
                <TextInput
                  value={form.tagline ?? ""}
                  onChange={(e) => update("tagline", e.target.value)}
                  placeholder="Best for growing teams"
                />
              </Field>

              <Field label="Description">
                <TextArea
                  rows={2}
                  value={form.description ?? ""}
                  onChange={(e) => update("description", e.target.value)}
                />
              </Field>

              <div className="grid md:grid-cols-3 gap-4">
                <Field label="Devices">
                  <TextInput
                    type="number"
                    min={0}
                    value={form.max_devices ?? 0}
                    onChange={(e) => update("max_devices", Number(e.target.value))}
                    disabled={form.devices_unlimited}
                  />
                </Field>
                <Field label="Messages / month">
                  <TextInput
                    type="number"
                    min={0}
                    value={form.messages_per_month ?? 0}
                    onChange={(e) => update("messages_per_month", Number(e.target.value))}
                    disabled={form.messages_unlimited}
                  />
                </Field>
                <Field label="Contacts">
                  <TextInput
                    type="number"
                    min={0}
                    value={form.max_contacts ?? 0}
                    onChange={(e) => update("max_contacts", Number(e.target.value))}
                    disabled={form.contacts_unlimited}
                  />
                </Field>
                <Field label="Campaigns">
                  <TextInput
                    type="number"
                    min={0}
                    value={form.max_campaigns ?? 0}
                    onChange={(e) => update("max_campaigns", Number(e.target.value))}
                    disabled={form.campaigns_unlimited}
                  />
                </Field>
                <Field label="Workflows">
                  <TextInput
                    type="number"
                    min={0}
                    value={form.max_workflows ?? 0}
                    onChange={(e) => update("max_workflows", Number(e.target.value))}
                    disabled={form.workflows_unlimited}
                  />
                </Field>
                <Field label="Team operators">
                  <TextInput
                    type="number"
                    min={0}
                    value={form.max_team_operators ?? 0}
                    onChange={(e) => update("max_team_operators", Number(e.target.value))}
                    disabled={form.team_operators_unlimited}
                  />
                </Field>
              </div>

              <div className="grid md:grid-cols-3 gap-2">
                <Toggle
                  checked={!!form.devices_unlimited}
                  onChange={(v) => update("devices_unlimited", v)}
                  label="Unlimited devices"
                />
                <Toggle
                  checked={!!form.messages_unlimited}
                  onChange={(v) => update("messages_unlimited", v)}
                  label="Unlimited messages"
                />
                <Toggle
                  checked={!!form.contacts_unlimited}
                  onChange={(v) => update("contacts_unlimited", v)}
                  label="Unlimited contacts"
                />
                <Toggle
                  checked={!!form.campaigns_unlimited}
                  onChange={(v) => update("campaigns_unlimited", v)}
                  label="Unlimited campaigns"
                />
                <Toggle
                  checked={!!form.workflows_unlimited}
                  onChange={(v) => update("workflows_unlimited", v)}
                  label="Unlimited workflows"
                />
                <Toggle
                  checked={!!form.team_operators_unlimited}
                  onChange={(v) => update("team_operators_unlimited", v)}
                  label="Unlimited operators"
                />
              </div>

              <div className="grid md:grid-cols-3 gap-2">
                <Toggle
                  checked={!!form.auto_reply_allowed}
                  onChange={(v) => update("auto_reply_allowed", v)}
                  label="Auto-reply"
                />
                <Toggle
                  checked={!!form.ai_assistant_allowed}
                  onChange={(v) => update("ai_assistant_allowed", v)}
                  label="AI assistant"
                />
                <Toggle
                  checked={!!form.workflow_automation_allowed}
                  onChange={(v) => update("workflow_automation_allowed", v)}
                  label="Workflow automation"
                />
                <Toggle
                  checked={!!form.webhook_access_allowed}
                  onChange={(v) => update("webhook_access_allowed", v)}
                  label="Webhooks"
                />
                <Toggle
                  checked={!!form.api_access_allowed}
                  onChange={(v) => update("api_access_allowed", v)}
                  label="Public API"
                />
                <Toggle
                  checked={!!form.media_sending_allowed}
                  onChange={(v) => update("media_sending_allowed", v)}
                  label="Media sending"
                />
                <Toggle
                  checked={!!form.template_messages_allowed}
                  onChange={(v) => update("template_messages_allowed", v)}
                  label="Template messages"
                />
              </div>

              <div className="grid md:grid-cols-3 gap-4">
                <Field label="Chat retention (days)">
                  <TextInput
                    type="number"
                    min={0}
                    value={form.chat_retention_days ?? 0}
                    onChange={(e) => update("chat_retention_days", Number(e.target.value))}
                  />
                </Field>
                <Field label="Price per month (display)">
                  <TextInput
                    value={form.price_per_month ?? ""}
                    onChange={(e) => update("price_per_month", e.target.value)}
                    placeholder="$49"
                  />
                </Field>
                <Field label="Sort order">
                  <TextInput
                    type="number"
                    value={form.sort_order ?? 0}
                    onChange={(e) => update("sort_order", Number(e.target.value))}
                  />
                </Field>
                <Field label="WHMCS product ID">
                  <TextInput
                    type="number"
                    value={form.whmcs_product_id ?? ""}
                    onChange={(e) =>
                      update(
                        "whmcs_product_id",
                        e.target.value === "" ? null : Number(e.target.value),
                      )
                    }
                    placeholder="Optional"
                  />
                </Field>
                <Field label="On termination">
                  <Select
                    value={form.terminate_action ?? "archive"}
                    onChange={(e) => update("terminate_action", e.target.value)}
                  >
                    <option value="archive">Archive</option>
                    <option value="delete">Delete upstream data</option>
                  </Select>
                </Field>
              </div>

              <div className="grid md:grid-cols-2 gap-2">
                <Toggle
                  checked={!!form.is_active}
                  onChange={(v) => update("is_active", v)}
                  label="Active (sellable)"
                />
                <Toggle
                  checked={!!form.is_featured}
                  onChange={(v) => update("is_featured", v)}
                  label="Featured"
                />
              </div>
            </div>

            <div className="flex items-center justify-end gap-2 px-6 py-4 border-t border-slate-200 bg-slate-50 rounded-b-2xl">
              <button
                type="button"
                onClick={closeForm}
                className="px-4 py-2 rounded-lg border border-slate-300 bg-white text-sm font-semibold text-slate-700 hover:bg-slate-100"
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={saving}
                className="px-4 py-2 rounded-lg bg-[#0b6e3e] text-white text-sm font-semibold hover:bg-[#0a8048] disabled:opacity-60 inline-flex items-center gap-2"
              >
                {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Check className="w-4 h-4" />}
                {editing ? "Save" : "Create"}
              </button>
            </div>
          </form>
        </div>
      )}
    </CmsLayout>
  );
}