// @File: src/pages/admin/cms/bizmail/CmsBizmailPlans.tsx
// @Desc: Admin CRUD UI for the Bizmail360 plan catalog. Inline editor
//        with toggle for active / featured flags and pricing fields.
import { useEffect, useState } from "react";
import { Inbox, Plus, Trash2, Save, Loader2, AlertTriangle } from "lucide-react";
import CmsLayout from "../CmsLayout";
import { PageHeader, SectionCard, Field, TextInput, TextArea, Toggle, Badge } from "../ui";
import {
  adminCreatePlan,
  adminDeletePlan,
  adminListPlans,
  adminUpdatePlan,
  type BizmailPlan,
} from "@/lib/bizmailApi";
import { toast } from "sonner";

function slugify(s: string): string {
  return s
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .slice(0, 40);
}

interface PlanDraft {
  slug: string;
  name: string;
  description: string;
  price_monthly: string;
  price_yearly: string;
  currency: string;
  mailbox_quota: number;
  storage_mb_per_mailbox: number;
  aliases_included: number;
  features: string;
  is_active: boolean;
  is_featured: boolean;
  sort_order: number;
}

const EMPTY_DRAFT: PlanDraft = {
  slug: "",
  name: "",
  description: "",
  price_monthly: "",
  price_yearly: "",
  currency: "USD",
  mailbox_quota: 5,
  storage_mb_per_mailbox: 5120,
  aliases_included: 10,
  features: "",
  is_active: true,
  is_featured: false,
  sort_order: 0,
};

function planToDraft(p: BizmailPlan): PlanDraft {
  return {
    slug: p.slug,
    name: p.name,
    description: p.description ?? "",
    price_monthly: p.price_monthly ?? "",
    price_yearly: p.price_yearly ?? "",
    currency: p.currency,
    mailbox_quota: p.mailbox_quota,
    storage_mb_per_mailbox: p.storage_mb_per_mailbox,
    aliases_included: p.aliases_included,
    features: p.features ?? "",
    is_active: p.is_active,
    is_featured: p.is_featured,
    sort_order: p.sort_order,
  };
}

export default function CmsBizmailPlans() {
  const [plans, setPlans] = useState<BizmailPlan[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [drafts, setDrafts] = useState<Record<number, PlanDraft>>({});
  const [saving, setSaving] = useState<Record<number, boolean>>({});
  const [creating, setCreating] = useState(false);
  const [newDraft, setNewDraft] = useState<PlanDraft>(EMPTY_DRAFT);

  const load = async () => {
    setLoading(true);
    setError(null);
    try {
      const rows = await adminListPlans(true);
      setPlans(rows);
      const next: Record<number, PlanDraft> = {};
      rows.forEach((p) => {
        next[p.id] = planToDraft(p);
      });
      setDrafts(next);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to load plans");
    } finally {
      setLoading(false);
    }
  };

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

  const updateDraft = (id: number, patch: Partial<PlanDraft>) => {
    setDrafts((prev) => ({ ...prev, [id]: { ...prev[id], ...patch } }));
  };

  const savePlan = async (id: number) => {
    const draft = drafts[id];
    if (!draft) return;
    setSaving((s) => ({ ...s, [id]: true }));
    try {
      const saved = await adminUpdatePlan(id, {
        ...draft,
        price_monthly: draft.price_monthly || null,
        price_yearly: draft.price_yearly || null,
        description: draft.description || null,
        features: draft.features || null,
      });
      setPlans((prev) => prev.map((p) => (p.id === id ? saved : p)));
      toast.success("Plan saved");
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Save failed");
    } finally {
      setSaving((s) => ({ ...s, [id]: false }));
    }
  };

  const deletePlan = async (id: number) => {
    if (!confirm("Delete this plan? Active subscriptions will keep their current terms.")) return;
    try {
      await adminDeletePlan(id);
      setPlans((prev) => prev.filter((p) => p.id !== id));
      toast.success("Plan deleted");
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Delete failed");
    }
  };

  const createPlan = async () => {
    if (!newDraft.name.trim()) {
      toast.error("Plan name is required");
      return;
    }
    const slug = newDraft.slug.trim() || slugify(newDraft.name);
    setCreating(true);
    try {
      await adminCreatePlan({
        ...newDraft,
        slug,
        price_monthly: newDraft.price_monthly || null,
        price_yearly: newDraft.price_yearly || null,
        description: newDraft.description || null,
        features: newDraft.features || null,
      });
      setNewDraft(EMPTY_DRAFT);
      toast.success("Plan created");
      await load();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Create failed");
    } finally {
      setCreating(false);
    }
  };

  return (
    <CmsLayout>
      <PageHeader
        icon={<Inbox className="w-6 h-6" />}
        title="Bizmail360 Plans"
        description="The SmarterMail-powered mail plans you offer to clients."
      />

      {error && (
        <div className="mb-4 flex items-start gap-2 rounded-lg border border-rose-200 bg-rose-50 p-3 text-sm text-rose-700">
          <AlertTriangle className="w-4 h-4 mt-0.5 shrink-0" />
          <span>{error}</span>
        </div>
      )}

      <SectionCard
        title="Create New Plan"
        description="Every plan sets mailbox quota, aliases and per-mailbox storage. Mark one plan as Featured to highlight it on the pricing page."
      >
        <div className="grid md:grid-cols-2 gap-4">
          <Field label="Name" required>
            <TextInput
              value={newDraft.name}
              onChange={(e) => setNewDraft({ ...newDraft, name: e.target.value })}
              placeholder="Bizmail360 Pro"
            />
          </Field>
          <Field label="Slug" hint="Auto from name">
            <TextInput
              value={newDraft.slug}
              onChange={(e) => setNewDraft({ ...newDraft, slug: e.target.value })}
              placeholder="bizmail360-pro"
            />
          </Field>
          <Field label="Description">
            <TextArea
              rows={2}
              value={newDraft.description}
              onChange={(e) => setNewDraft({ ...newDraft, description: e.target.value })}
            />
          </Field>
          <Field label="Features (one per line)">
            <TextArea
              rows={2}
              value={newDraft.features}
              onChange={(e) => setNewDraft({ ...newDraft, features: e.target.value })}
              placeholder={"IMAP/POP/SMTP\nWebmail\nCalendars & Contacts"}
            />
          </Field>
          <Field label="Monthly Price">
            <TextInput
              value={newDraft.price_monthly}
              onChange={(e) => setNewDraft({ ...newDraft, price_monthly: e.target.value })}
              placeholder="2.99"
            />
          </Field>
          <Field label="Yearly Price">
            <TextInput
              value={newDraft.price_yearly}
              onChange={(e) => setNewDraft({ ...newDraft, price_yearly: e.target.value })}
              placeholder="29.99"
            />
          </Field>
          <Field label="Currency">
            <TextInput
              value={newDraft.currency}
              onChange={(e) => setNewDraft({ ...newDraft, currency: e.target.value.toUpperCase() })}
              placeholder="USD"
            />
          </Field>
          <Field label="Sort order" hint="Lower = first">
            <TextInput
              type="number"
              value={newDraft.sort_order}
              onChange={(e) => setNewDraft({ ...newDraft, sort_order: Number(e.target.value) || 0 })}
            />
          </Field>
          <Field label="Mailbox quota">
            <TextInput
              type="number"
              min={1}
              value={newDraft.mailbox_quota}
              onChange={(e) =>
                setNewDraft({ ...newDraft, mailbox_quota: Number(e.target.value) || 1 })
              }
            />
          </Field>
          <Field label="Aliases included">
            <TextInput
              type="number"
              min={0}
              value={newDraft.aliases_included}
              onChange={(e) =>
                setNewDraft({ ...newDraft, aliases_included: Number(e.target.value) || 0 })
              }
            />
          </Field>
          <Field label="Storage per mailbox (MB)">
            <TextInput
              type="number"
              min={256}
              value={newDraft.storage_mb_per_mailbox}
              onChange={(e) =>
                setNewDraft({
                  ...newDraft,
                  storage_mb_per_mailbox: Number(e.target.value) || 1024,
                })
              }
            />
          </Field>
        </div>
        <div className="grid md:grid-cols-2 gap-4 mt-2">
          <Toggle
            label="Active"
            description="Inactive plans are hidden from the public pricing page."
            checked={newDraft.is_active}
            onChange={(v) => setNewDraft({ ...newDraft, is_active: v })}
          />
          <Toggle
            label="Featured"
            description="Highlighted with a 'Most Popular' badge."
            checked={newDraft.is_featured}
            onChange={(v) => setNewDraft({ ...newDraft, is_featured: v })}
          />
        </div>
        <div className="flex justify-end">
          <button
            onClick={() => void createPlan()}
            disabled={creating}
            className="px-5 py-2.5 rounded-lg bg-[#0b6e3e] text-white text-sm font-bold hover:bg-[#0a8048] transition disabled:opacity-60 inline-flex items-center gap-2"
          >
            {creating ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}
            Create Plan
          </button>
        </div>
      </SectionCard>

      <div className="mt-6 space-y-5">
        <SectionCard
          title="Existing Plans"
          description={`${plans.length} plan${plans.length === 1 ? "" : "s"} configured.`}
        >
          {loading ? (
            <div className="flex items-center gap-2 text-slate-500 text-sm">
              <Loader2 className="w-4 h-4 animate-spin" /> Loading plans…
            </div>
          ) : plans.length === 0 ? (
            <div className="text-sm text-slate-500">No plans yet. Create one above.</div>
          ) : (
            <div className="space-y-4">
              {plans.map((p) => {
                const d = drafts[p.id];
                if (!d) return null;
                return (
                  <div
                    key={p.id}
                    className="border border-slate-200 rounded-xl p-4 md:p-5 space-y-3 bg-slate-50/40"
                  >
                    <div className="flex items-center justify-between gap-3 flex-wrap">
                      <div className="flex items-center gap-2">
                        <div className="font-bold text-slate-900">{p.name}</div>
                        <span className="text-xs text-slate-500">({p.slug})</span>
                        {p.is_featured && <Badge tone="yellow">Featured</Badge>}
                        {p.is_active ? (
                          <Badge tone="green">Active</Badge>
                        ) : (
                          <Badge tone="slate">Inactive</Badge>
                        )}
                      </div>
                      <div className="flex items-center gap-2">
                        <button
                          onClick={() => void savePlan(p.id)}
                          disabled={saving[p.id]}
                          className="px-3 py-2 rounded-lg bg-[#0b6e3e] text-white text-xs font-semibold hover:bg-[#0a8048] transition disabled:opacity-60 inline-flex items-center gap-1.5"
                        >
                          {saving[p.id] ? (
                            <Loader2 className="w-3.5 h-3.5 animate-spin" />
                          ) : (
                            <Save className="w-3.5 h-3.5" />
                          )}
                          Save
                        </button>
                        <button
                          onClick={() => void deletePlan(p.id)}
                          className="px-3 py-2 rounded-lg border border-rose-300 text-rose-600 text-xs font-semibold hover:bg-rose-50 transition inline-flex items-center gap-1.5"
                        >
                          <Trash2 className="w-3.5 h-3.5" /> Delete
                        </button>
                      </div>
                    </div>
                    <div className="grid md:grid-cols-3 gap-3">
                      <Field label="Name">
                        <TextInput
                          value={d.name}
                          onChange={(e) => updateDraft(p.id, { name: e.target.value })}
                        />
                      </Field>
                      <Field label="Slug">
                        <TextInput
                          value={d.slug}
                          onChange={(e) => updateDraft(p.id, { slug: e.target.value })}
                        />
                      </Field>
                      <Field label="Sort order">
                        <TextInput
                          type="number"
                          value={d.sort_order}
                          onChange={(e) =>
                            updateDraft(p.id, { sort_order: Number(e.target.value) || 0 })
                          }
                        />
                      </Field>
                      <Field label="Monthly Price">
                        <TextInput
                          value={d.price_monthly}
                          onChange={(e) => updateDraft(p.id, { price_monthly: e.target.value })}
                        />
                      </Field>
                      <Field label="Yearly Price">
                        <TextInput
                          value={d.price_yearly}
                          onChange={(e) => updateDraft(p.id, { price_yearly: e.target.value })}
                        />
                      </Field>
                      <Field label="Currency">
                        <TextInput
                          value={d.currency}
                          onChange={(e) =>
                            updateDraft(p.id, { currency: e.target.value.toUpperCase() })
                          }
                        />
                      </Field>
                      <Field label="Mailbox quota">
                        <TextInput
                          type="number"
                          min={1}
                          value={d.mailbox_quota}
                          onChange={(e) =>
                            updateDraft(p.id, { mailbox_quota: Number(e.target.value) || 1 })
                          }
                        />
                      </Field>
                      <Field label="Aliases included">
                        <TextInput
                          type="number"
                          min={0}
                          value={d.aliases_included}
                          onChange={(e) =>
                            updateDraft(p.id, { aliases_included: Number(e.target.value) || 0 })
                          }
                        />
                      </Field>
                      <Field label="Storage per mailbox (MB)">
                        <TextInput
                          type="number"
                          min={256}
                          value={d.storage_mb_per_mailbox}
                          onChange={(e) =>
                            updateDraft(p.id, {
                              storage_mb_per_mailbox: Number(e.target.value) || 1024,
                            })
                          }
                        />
                      </Field>
                      <Field label="Description">
                        <TextArea
                          rows={2}
                          value={d.description}
                          onChange={(e) => updateDraft(p.id, { description: e.target.value })}
                        />
                      </Field>
                      <Field label="Features (one per line)">
                        <TextArea
                          rows={2}
                          value={d.features}
                          onChange={(e) => updateDraft(p.id, { features: e.target.value })}
                        />
                      </Field>
                    </div>
                    <div className="grid md:grid-cols-2 gap-3">
                      <Toggle
                        label="Active"
                        checked={d.is_active}
                        onChange={(v) => updateDraft(p.id, { is_active: v })}
                      />
                      <Toggle
                        label="Featured"
                        checked={d.is_featured}
                        onChange={(v) => updateDraft(p.id, { is_featured: v })}
                      />
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </SectionCard>
      </div>
    </CmsLayout>
  );
}