// @File: src/pages/admin/cms/uptimerobot/CmsUptimeRobotPackages.tsx
// @Desc: CRUD screen for monitoring packages. Admins define limits,
//        allowed monitor types, min interval and WHMCS product mapping
//        here. Every write path goes through adminApi so the audit log
//        captures who changed what.
import { useCallback, useEffect, useMemo, useState } from "react";
import { Layers, Loader2, Plus, Save, Trash2, X } from "lucide-react";
import { toast } from "sonner";
import CmsLayout from "../CmsLayout";
import { PageHeader, SectionCard, Field, TextInput, TextArea, Select, Toggle } from "../ui";
import {
  adminCreatePackage,
  adminDeletePackage,
  adminListPackages,
  adminUpdatePackage,
  type UptimePackage,
  type UptimePackageInput,
} from "@/lib/uptimerobotApi";

const MONITOR_TYPES = ["http", "ping", "port", "keyword", "heartbeat"] as const;

const EMPTY_FORM: UptimePackageInput = {
  slug: "",
  name: "",
  description: "",
  max_monitors: 5,
  monitors_unlimited: false,
  max_alert_contacts: 5,
  alert_contacts_unlimited: false,
  max_maintenance_windows: 2,
  maintenance_windows_unlimited: false,
  max_status_pages: 1,
  status_pages_unlimited: false,
  min_check_interval: 300,
  allowed_monitor_types: "http",
  public_status_page_allowed: false,
  api_monitoring_allowed: false,
  advanced_notifications_allowed: false,
  whmcs_product_id: null,
  terminate_action: "archive",
  is_active: true,
  price_per_month: "",
};

export default function CmsUptimeRobotPackages() {
  const [packages, setPackages] = useState<UptimePackage[]>([]);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState<UptimePackage | null>(null);
  const [form, setForm] = useState<UptimePackageInput>(EMPTY_FORM);
  const [saving, setSaving] = useState(false);
  const [showForm, setShowForm] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const rows = await adminListPackages();
      setPackages(rows);
    } catch (e) {
      toast.error(`Failed to load packages: ${e instanceof Error ? e.message : e}`);
    } finally {
      setLoading(false);
    }
  }, []);

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

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

  const openEdit = (pkg: UptimePackage) => {
    setEditing(pkg);
    const { id: _id, created_at: _c, updated_at: _u, ...rest } = pkg;
    setForm({ ...rest });
    setShowForm(true);
  };

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

  const toggleType = (t: string) => {
    const current = form.allowed_monitor_types
      .split(",")
      .map((x) => x.trim())
      .filter(Boolean);
    const next = current.includes(t)
      ? current.filter((x) => x !== t)
      : [...current, t];
    setForm({ ...form, allowed_monitor_types: next.join(",") || "http" });
  };

  const submit = async () => {
    if (!form.slug || !form.name) {
      toast.error("Slug and name are required.");
      return;
    }
    setSaving(true);
    try {
      if (editing) {
        await adminUpdatePackage(editing.id, form);
        toast.success(`Package '${form.name}' updated.`);
      } else {
        await adminCreatePackage(form);
        toast.success(`Package '${form.name}' created.`);
      }
      closeForm();
      await load();
    } catch (e) {
      toast.error(`Save failed: ${e instanceof Error ? e.message : e}`);
    } finally {
      setSaving(false);
    }
  };

  const remove = async (pkg: UptimePackage) => {
    if (!confirm(`Delete package '${pkg.name}'?`)) return;
    try {
      await adminDeletePackage(pkg.id);
      toast.success(`Package '${pkg.name}' deleted.`);
      await load();
    } catch (e) {
      toast.error(`Delete failed: ${e instanceof Error ? e.message : e}`);
    }
  };

  const selectedTypes = useMemo(
    () =>
      new Set(
        form.allowed_monitor_types
          .split(",")
          .map((t) => t.trim())
          .filter(Boolean),
      ),
    [form.allowed_monitor_types],
  );

  return (
    <CmsLayout>
      <PageHeader
        title="Monitoring Packages"
        description="Define the plans you sell to customers. Limits, allowed monitor types, and WHMCS product mapping all live here."
        icon={<Layers className="w-6 h-6" />}
      />

      <SectionCard
        title="All packages"
        description={`${packages.length} package(s) configured.`}
        actions={
          <button
            onClick={openCreate}
            className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-[#0b6e3e] text-white text-sm font-semibold hover:bg-[#095a32] transition"
          >
            <Plus className="w-4 h-4" /> New package
          </button>
        }
      >
        {loading ? (
          <div className="flex items-center gap-2 text-slate-500 text-sm">
            <Loader2 className="w-4 h-4 animate-spin" /> Loading…
          </div>
        ) : packages.length === 0 ? (
          <div className="text-sm text-slate-500">
            No packages yet. Click “New package” to create your first plan.
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="text-left text-xs uppercase text-slate-500 border-b border-slate-200">
                  <th className="py-2 pr-4">Name</th>
                  <th className="py-2 pr-4">Slug</th>
                  <th className="py-2 pr-4">Monitors</th>
                  <th className="py-2 pr-4">Contacts</th>
                  <th className="py-2 pr-4">Pages</th>
                  <th className="py-2 pr-4">Interval ≥</th>
                  <th className="py-2 pr-4">WHMCS ID</th>
                  <th className="py-2 pr-4">Status</th>
                  <th className="py-2" />
                </tr>
              </thead>
              <tbody>
                {packages.map((p) => (
                  <tr key={p.id} className="border-b border-slate-100 hover:bg-slate-50">
                    <td className="py-2 pr-4 font-semibold text-slate-900">{p.name}</td>
                    <td className="py-2 pr-4 text-slate-600">{p.slug}</td>
                    <td className="py-2 pr-4">
                      {p.monitors_unlimited ? "∞" : p.max_monitors}
                    </td>
                    <td className="py-2 pr-4">
                      {p.alert_contacts_unlimited ? "∞" : p.max_alert_contacts}
                    </td>
                    <td className="py-2 pr-4">
                      {p.status_pages_unlimited ? "∞" : p.max_status_pages}
                    </td>
                    <td className="py-2 pr-4">{p.min_check_interval}s</td>
                    <td className="py-2 pr-4">{p.whmcs_product_id ?? "—"}</td>
                    <td className="py-2 pr-4">
                      {p.is_active ? (
                        <span className="px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-700 text-xs font-semibold border border-emerald-200">
                          Active
                        </span>
                      ) : (
                        <span className="px-2 py-0.5 rounded-full bg-slate-100 text-slate-500 text-xs font-semibold border border-slate-200">
                          Inactive
                        </span>
                      )}
                    </td>
                    <td className="py-2 text-right space-x-2 whitespace-nowrap">
                      <button
                        onClick={() => openEdit(p)}
                        className="px-3 py-1.5 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-semibold"
                      >
                        Edit
                      </button>
                      <button
                        onClick={() => remove(p)}
                        className="px-3 py-1.5 rounded-lg bg-red-50 hover:bg-red-100 text-red-700 text-xs font-semibold inline-flex items-center gap-1"
                      >
                        <Trash2 className="w-3 h-3" />
                        Delete
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </SectionCard>

      {showForm && (
        <div className="fixed inset-0 bg-slate-900/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl shadow-2xl max-w-3xl w-full max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between p-5 border-b border-slate-200 sticky top-0 bg-white z-10">
              <div>
                <h3 className="text-lg font-bold text-slate-900">
                  {editing ? `Edit: ${editing.name}` : "Create package"}
                </h3>
                <p className="text-xs text-slate-500">
                  Limits apply per client subscription. ∞ means no cap.
                </p>
              </div>
              <button
                onClick={closeForm}
                className="p-2 rounded-lg hover:bg-slate-100"
                aria-label="Close"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-5 space-y-5">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <Field label="Slug" required hint="lowercase, unique">
                  <TextInput
                    value={form.slug}
                    onChange={(e) => setForm({ ...form, slug: e.target.value })}
                    placeholder="starter"
                    disabled={!!editing}
                  />
                </Field>
                <Field label="Name" required>
                  <TextInput
                    value={form.name}
                    onChange={(e) => setForm({ ...form, name: e.target.value })}
                    placeholder="Starter"
                  />
                </Field>
              </div>
              <Field label="Description">
                <TextArea
                  rows={2}
                  value={form.description ?? ""}
                  onChange={(e) => setForm({ ...form, description: e.target.value })}
                />
              </Field>

              <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                <Field label="Monitors">
                  <TextInput
                    type="number"
                    value={form.max_monitors}
                    onChange={(e) =>
                      setForm({ ...form, max_monitors: Number(e.target.value) })
                    }
                    disabled={form.monitors_unlimited}
                  />
                </Field>
                <Field label="Alert contacts">
                  <TextInput
                    type="number"
                    value={form.max_alert_contacts}
                    onChange={(e) =>
                      setForm({ ...form, max_alert_contacts: Number(e.target.value) })
                    }
                    disabled={form.alert_contacts_unlimited}
                  />
                </Field>
                <Field label="Maintenance windows">
                  <TextInput
                    type="number"
                    value={form.max_maintenance_windows}
                    onChange={(e) =>
                      setForm({
                        ...form,
                        max_maintenance_windows: Number(e.target.value),
                      })
                    }
                    disabled={form.maintenance_windows_unlimited}
                  />
                </Field>
                <Field label="Status pages">
                  <TextInput
                    type="number"
                    value={form.max_status_pages}
                    onChange={(e) =>
                      setForm({ ...form, max_status_pages: Number(e.target.value) })
                    }
                    disabled={form.status_pages_unlimited}
                  />
                </Field>
              </div>

              <div className="rounded-xl border border-slate-200 divide-y divide-slate-100">
                <Toggle
                  label="Unlimited monitors"
                  checked={form.monitors_unlimited}
                  onChange={(v) => setForm({ ...form, monitors_unlimited: v })}
                />
                <Toggle
                  label="Unlimited alert contacts"
                  checked={form.alert_contacts_unlimited}
                  onChange={(v) => setForm({ ...form, alert_contacts_unlimited: v })}
                />
                <Toggle
                  label="Unlimited maintenance windows"
                  checked={form.maintenance_windows_unlimited}
                  onChange={(v) =>
                    setForm({ ...form, maintenance_windows_unlimited: v })
                  }
                />
                <Toggle
                  label="Unlimited status pages"
                  checked={form.status_pages_unlimited}
                  onChange={(v) => setForm({ ...form, status_pages_unlimited: v })}
                />
              </div>

              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <Field label="Min check interval (sec)" hint="60–3600">
                  <TextInput
                    type="number"
                    value={form.min_check_interval}
                    onChange={(e) =>
                      setForm({ ...form, min_check_interval: Number(e.target.value) })
                    }
                  />
                </Field>
                <Field label="WHMCS product id">
                  <TextInput
                    type="number"
                    value={form.whmcs_product_id ?? ""}
                    placeholder="(optional)"
                    onChange={(e) =>
                      setForm({
                        ...form,
                        whmcs_product_id: e.target.value
                          ? Number(e.target.value)
                          : null,
                      })
                    }
                  />
                </Field>
                <Field label="On WHMCS termination">
                  <Select
                    value={form.terminate_action}
                    onChange={(e) =>
                      setForm({
                        ...form,
                        terminate_action: e.target.value as "archive" | "delete",
                      })
                    }
                  >
                    <option value="archive">Archive (pause) monitors</option>
                    <option value="delete">Delete monitors</option>
                  </Select>
                </Field>
              </div>

              <div>
                <div className="text-sm font-semibold text-slate-800 mb-2">
                  Allowed monitor types
                </div>
                <div className="flex flex-wrap gap-2">
                  {MONITOR_TYPES.map((t) => {
                    const active = selectedTypes.has(t);
                    return (
                      <button
                        type="button"
                        key={t}
                        onClick={() => toggleType(t)}
                        className={`px-3 py-1.5 rounded-lg text-xs font-semibold border ${
                          active
                            ? "bg-[#0b6e3e] text-white border-[#0b6e3e]"
                            : "bg-white text-slate-600 border-slate-300"
                        }`}
                      >
                        {t}
                      </button>
                    );
                  })}
                </div>
              </div>

              <div className="rounded-xl border border-slate-200 divide-y divide-slate-100">
                <Toggle
                  label="Public status pages allowed"
                  checked={form.public_status_page_allowed}
                  onChange={(v) =>
                    setForm({ ...form, public_status_page_allowed: v })
                  }
                />
                <Toggle
                  label="API monitoring allowed"
                  checked={form.api_monitoring_allowed}
                  onChange={(v) => setForm({ ...form, api_monitoring_allowed: v })}
                />
                <Toggle
                  label="Advanced notifications (Slack/Webhook/Telegram) allowed"
                  checked={form.advanced_notifications_allowed}
                  onChange={(v) =>
                    setForm({ ...form, advanced_notifications_allowed: v })
                  }
                />
                <Toggle
                  label="Package is active"
                  checked={form.is_active}
                  onChange={(v) => setForm({ ...form, is_active: v })}
                />
              </div>

              <Field label="Display price per month">
                <TextInput
                  value={form.price_per_month ?? ""}
                  onChange={(e) =>
                    setForm({ ...form, price_per_month: e.target.value })
                  }
                  placeholder="e.g. $9.99"
                />
              </Field>

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