"use client";

import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Edit2, Filter, Loader2, Save, X } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { formatDate } from "@/lib/utils";
import { getPlanBadgeColor, PLAN_LIMITS } from "@/lib/plan-limits";
import {
  adminApi,
  type AdminSettings,
  type AdminStatsResponse,
  type AdminUserResponse,
  type Plan,
  type PlanCatalogInput,
  type PlanCatalogResponse,
} from "@/lib/api";
import { getAdminToken } from "@/lib/admin-store";

function featuresToText(features: PlanCatalogInput["features"]) {
  return features.map((feature) => `${feature.included ? "+" : "-"} ${feature.label}`).join("\n");
}

function textToFeatures(value: string) {
  return value
    .split("\n")
    .map((line) => line.trim())
    .filter(Boolean)
    .map((line) => ({
      included: !line.startsWith("-"),
      label: line.replace(/^[-+]\s*/, ""),
    }));
}

export default function AdminPlansPage() {
  const router = useRouter();
  const [stats, setStats] = useState<AdminStatsResponse | null>(null);
  const [users, setUsers] = useState<AdminUserResponse[]>([]);
  const [plans, setPlans] = useState<PlanCatalogResponse[]>([]);
  const [settings, setSettings] = useState<AdminSettings | null>(null);
  const [planFilter, setPlanFilter] = useState("all");
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [limitsSaving, setLimitsSaving] = useState(false);
  const [editingKey, setEditingKey] = useState<Plan | null>(null);
  const [form, setForm] = useState<PlanCatalogInput | null>(null);
  const [featuresText, setFeaturesText] = useState("");
  const [error, setError] = useState("");
  const [limitsError, setLimitsError] = useState("");

  const load = useCallback(async () => {
    const token = await getAdminToken();
    if (!token) {
      router.push("/admin-login");
      return;
    }
    const [s, u, p, cfg] = await Promise.all([
      adminApi.getStats(token),
      adminApi.getUsers(token),
      adminApi.getPlans(token),
      adminApi.getSettings(token),
    ]);
    setStats(s);
    setUsers(u);
    setPlans(p);
    setSettings(cfg);
  }, [router]);

  const saveLimits = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!settings) return;
    const token = await getAdminToken();
    if (!token) return;
    setLimitsSaving(true);
    setLimitsError("");
    try {
      const updated = await adminApi.updateSettings(token, settings);
      setSettings(updated);
    } catch (err: unknown) {
      setLimitsError(err instanceof Error ? err.message : "Could not save limits");
    } finally {
      setLimitsSaving(false);
    }
  };

  useEffect(() => {
    (async () => {
      try {
        await load();
      } catch {
        router.push("/admin-login");
      } finally {
        setLoading(false);
      }
    })();
  }, [load, router]);

  const edit = (plan: PlanCatalogResponse) => {
    setEditingKey(plan.plan_key);
    setForm({
      name: plan.name,
      description: plan.description,
      price_monthly: plan.price_monthly,
      price_yearly: plan.price_yearly,
      cta_label: plan.cta_label,
      cta_href: plan.cta_href,
      features: plan.features,
      is_popular: plan.is_popular,
      is_active: plan.is_active,
      sort_order: plan.sort_order,
    });
    setFeaturesText(featuresToText(plan.features));
    setError("");
  };

  const cancel = () => {
    setEditingKey(null);
    setForm(null);
    setFeaturesText("");
    setError("");
  };

  const save = async (event: React.FormEvent) => {
    event.preventDefault();
    if (!editingKey || !form) return;
    const token = await getAdminToken();
    if (!token) return;

    setSaving(true);
    setError("");
    try {
      const updated = await adminApi.updatePlan(token, editingKey, {
        ...form,
        price_monthly: form.price_monthly === null ? null : Number(form.price_monthly),
        price_yearly: form.price_yearly === null ? null : Number(form.price_yearly),
        sort_order: Number(form.sort_order) || 0,
        features: textToFeatures(featuresText),
      });
      setPlans((prev) => prev.map((plan) => (plan.plan_key === updated.plan_key ? updated : plan)));
      cancel();
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Could not save plan");
    } finally {
      setSaving(false);
    }
  };

  const filtered = users.filter((u) => planFilter === "all" || u.plan === planFilter);

  if (loading || !stats) {
    return (
      <div className="flex items-center justify-center py-20 text-zinc-500">
        <Loader2 className="w-5 h-5 animate-spin mr-2" /> Loading...
      </div>
    );
  }

  const summaryCards = [
    { label: "Free Users", value: stats.free_users, color: "border-zinc-700" },
    { label: "Pro Subscribers", value: stats.pro_users, color: "border-violet-500/40" },
    { label: "Pro Max", value: stats.pro_max_users, color: "border-cyan-500/40" },
    { label: "Paid Users", value: stats.pro_users + stats.pro_max_users, color: "border-emerald-500/40" },
  ];

  return (
    <div>
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-white">Plans & Subscriptions</h1>
        <p className="text-zinc-500 text-sm mt-1">Manage pricing-page plans and user subscriptions</p>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        {summaryCards.map((s) => (
          <div key={s.label} className={`glass-card p-5 border ${s.color}`}>
            <div className="text-2xl font-bold text-white">{s.value.toLocaleString()}</div>
            <div className="text-xs text-zinc-500 mt-1">{s.label}</div>
          </div>
        ))}
      </div>

      <div className="grid xl:grid-cols-[minmax(0,1fr)_400px] gap-6 mb-8">
        <div className="glass-card overflow-hidden">
          <div className="px-5 py-4 border-b border-white/8">
            <h2 className="text-base font-semibold text-white">Public Plan Cards</h2>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-white/8">
                  <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Plan</th>
                  <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Price</th>
                  <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Status</th>
                  <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Order</th>
                  <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Actions</th>
                </tr>
              </thead>
              <tbody>
                {plans.map((plan) => (
                  <tr key={plan.plan_key} className="border-b border-white/5 hover:bg-white/3 transition-colors">
                    <td className="px-5 py-4">
                      <Badge className={`text-xs ${getPlanBadgeColor(plan.plan_key)}`}>{plan.name}</Badge>
                      <div className="text-xs text-zinc-500 mt-1">{plan.description}</div>
                    </td>
                    <td className="px-5 py-4 text-sm text-zinc-400">
                      {plan.price_monthly === null ? "Custom" : `₹${plan.price_monthly}/mo`}
                    </td>
                    <td className="px-5 py-4">
                      <Badge className={plan.is_active ? "bg-emerald-500/15 text-emerald-400 border-emerald-500/30 text-xs" : "bg-zinc-800 text-zinc-400 border-zinc-700 text-xs"}>
                        {plan.is_active ? "active" : "hidden"}
                      </Badge>
                      {plan.is_popular && (
                        <Badge className="ml-2 bg-violet-500/15 text-violet-300 border-violet-500/30 text-xs">
                          popular
                        </Badge>
                      )}
                    </td>
                    <td className="px-5 py-4 text-sm text-zinc-400">{plan.sort_order}</td>
                    <td className="px-5 py-4">
                      <Button
                        type="button"
                        size="sm"
                        variant="ghost"
                        className="h-8 px-2 text-zinc-400 hover:text-white"
                        onClick={() => edit(plan)}
                      >
                        <Edit2 className="w-3.5 h-3.5" />
                      </Button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        <form onSubmit={save} className="glass-card p-6 h-fit">
          <div className="flex items-center justify-between mb-5">
            <h2 className="text-base font-semibold text-white">{editingKey ? "Edit Plan" : "Select a Plan"}</h2>
            {editingKey && (
              <button type="button" onClick={cancel} className="text-zinc-500 hover:text-zinc-300">
                <X className="w-4 h-4" />
              </button>
            )}
          </div>

          {!form ? (
            <p className="text-sm text-zinc-500">Choose a plan from the table to edit pricing-page content.</p>
          ) : (
            <div className="space-y-4">
              {error && (
                <div className="text-xs text-red-400 p-3 rounded-lg bg-red-500/10 border border-red-500/20">
                  {error}
                </div>
              )}
              <div className="space-y-1.5">
                <Label className="text-xs text-zinc-500">Name</Label>
                <Input value={form.name} onChange={(e) => setForm((p) => p && { ...p, name: e.target.value })} className="bg-white/5 border-white/10 text-white" />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs text-zinc-500">Description</Label>
                <Input value={form.description} onChange={(e) => setForm((p) => p && { ...p, description: e.target.value })} className="bg-white/5 border-white/10 text-white" />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div className="space-y-1.5">
                  <Label className="text-xs text-zinc-500">Monthly Price</Label>
                  <Input type="number" value={form.price_monthly ?? ""} onChange={(e) => setForm((p) => p && { ...p, price_monthly: e.target.value === "" ? null : Number(e.target.value) })} className="bg-white/5 border-white/10 text-white" />
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs text-zinc-500">Yearly Price</Label>
                  <Input type="number" value={form.price_yearly ?? ""} onChange={(e) => setForm((p) => p && { ...p, price_yearly: e.target.value === "" ? null : Number(e.target.value) })} className="bg-white/5 border-white/10 text-white" />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div className="space-y-1.5">
                  <Label className="text-xs text-zinc-500">CTA Label</Label>
                  <Input value={form.cta_label} onChange={(e) => setForm((p) => p && { ...p, cta_label: e.target.value })} className="bg-white/5 border-white/10 text-white" />
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs text-zinc-500">CTA URL</Label>
                  <Input value={form.cta_href} onChange={(e) => setForm((p) => p && { ...p, cta_href: e.target.value })} className="bg-white/5 border-white/10 text-white" />
                </div>
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs text-zinc-500">Features</Label>
                <Textarea
                  value={featuresText}
                  onChange={(e) => setFeaturesText(e.target.value)}
                  className="min-h-40 bg-white/5 border-white/10 text-white font-mono text-xs"
                />
                <p className="text-[11px] text-zinc-600">Prefix included features with + and excluded features with -.</p>
              </div>
              <div className="grid grid-cols-3 gap-3">
                <div className="space-y-1.5">
                  <Label className="text-xs text-zinc-500">Order</Label>
                  <Input type="number" value={form.sort_order} onChange={(e) => setForm((p) => p && { ...p, sort_order: Number(e.target.value) })} className="bg-white/5 border-white/10 text-white" />
                </div>
                <div className="flex items-center justify-between rounded-lg border border-white/8 bg-white/[0.03] p-3 col-span-2">
                  <div className="text-sm text-white">Popular</div>
                  <Switch checked={form.is_popular} onCheckedChange={(checked) => setForm((p) => p && { ...p, is_popular: checked })} className="data-[state=checked]:bg-violet-600" />
                </div>
              </div>
              <div className="flex items-center justify-between rounded-lg border border-white/8 bg-white/[0.03] p-3">
                <div>
                  <div className="text-sm text-white">Visible on pricing page</div>
                  <div className="text-xs text-zinc-500">Hidden plans remain assignable internally</div>
                </div>
                <Switch checked={form.is_active} onCheckedChange={(checked) => setForm((p) => p && { ...p, is_active: checked })} className="data-[state=checked]:bg-violet-600" />
              </div>
              <Button type="submit" disabled={saving} className="w-full bg-gradient-to-r from-violet-600 to-violet-500 text-white border-0">
                {saving ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : <Save className="w-4 h-4 mr-2" />}
                Save Plan
              </Button>
            </div>
          )}
        </form>
      </div>

      {/* Plan Limits */}
      {settings && (
        <form onSubmit={saveLimits} className="glass-card overflow-hidden mb-8">
          <div className="px-5 py-4 border-b border-white/8 flex items-center justify-between">
            <div>
              <h2 className="text-base font-semibold text-white">Plan Operation Limits</h2>
              <p className="text-xs text-zinc-500 mt-0.5">Controls actual processing limits enforced by the backend</p>
            </div>
            <Button type="submit" disabled={limitsSaving} size="sm" className="bg-gradient-to-r from-violet-600 to-violet-500 text-white border-0">
              {limitsSaving ? <Loader2 className="w-3.5 h-3.5 animate-spin mr-1.5" /> : <Save className="w-3.5 h-3.5 mr-1.5" />}
              Save Limits
            </Button>
          </div>

          {limitsError && (
            <div className="mx-5 mt-4 text-xs text-red-400 p-3 rounded-lg bg-red-500/10 border border-red-500/20">
              {limitsError}
            </div>
          )}

          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-white/8">
                  <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Plan</th>
                  <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Videos / Day</th>
                  <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Max Video Length (min)</th>
                  <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Max Clips / Job</th>
                </tr>
              </thead>
              <tbody>
                <tr className="border-b border-white/5">
                  <td className="px-5 py-4">
                    <Badge className="bg-zinc-800 text-zinc-300 border-zinc-700 text-xs">Free</Badge>
                  </td>
                  <td className="px-5 py-4">
                    <Input
                      type="number" min={0} max={100}
                      value={settings.free_daily_limit}
                      onChange={(e) => setSettings((s) => s && { ...s, free_daily_limit: Number(e.target.value) })}
                      className="w-24 h-8 bg-white/5 border-white/10 text-white text-sm"
                    />
                  </td>
                  <td className="px-5 py-4">
                    <Input
                      type="number" min={1} max={600}
                      value={settings.free_max_minutes}
                      onChange={(e) => setSettings((s) => s && { ...s, free_max_minutes: Number(e.target.value) })}
                      className="w-24 h-8 bg-white/5 border-white/10 text-white text-sm"
                    />
                  </td>
                  <td className="px-5 py-4">
                    <Input
                      type="number" min={1} max={20}
                      value={settings.free_max_clips}
                      onChange={(e) => setSettings((s) => s && { ...s, free_max_clips: Number(e.target.value) })}
                      className="w-24 h-8 bg-white/5 border-white/10 text-white text-sm"
                    />
                  </td>
                </tr>
                <tr className="border-b border-white/5">
                  <td className="px-5 py-4">
                    <Badge className="bg-violet-500/15 text-violet-300 border-violet-500/30 text-xs">Pro</Badge>
                  </td>
                  <td className="px-5 py-4">
                    <Input
                      type="number" min={0} max={100}
                      value={settings.pro_daily_limit}
                      onChange={(e) => setSettings((s) => s && { ...s, pro_daily_limit: Number(e.target.value) })}
                      className="w-24 h-8 bg-white/5 border-white/10 text-white text-sm"
                    />
                  </td>
                  <td className="px-5 py-4">
                    <Input
                      type="number" min={1} max={600}
                      value={settings.pro_max_minutes}
                      onChange={(e) => setSettings((s) => s && { ...s, pro_max_minutes: Number(e.target.value) })}
                      className="w-24 h-8 bg-white/5 border-white/10 text-white text-sm"
                    />
                  </td>
                  <td className="px-5 py-4">
                    <Input
                      type="number" min={1} max={20}
                      value={settings.pro_max_clips}
                      onChange={(e) => setSettings((s) => s && { ...s, pro_max_clips: Number(e.target.value) })}
                      className="w-24 h-8 bg-white/5 border-white/10 text-white text-sm"
                    />
                  </td>
                </tr>
                <tr>
                  <td className="px-5 py-4">
                    <Badge className="bg-cyan-500/15 text-cyan-300 border-cyan-500/30 text-xs">Pro Max</Badge>
                  </td>
                  <td className="px-5 py-4 text-sm text-zinc-500">Unlimited</td>
                  <td className="px-5 py-4 text-sm text-zinc-500">Unlimited</td>
                  <td className="px-5 py-4 text-sm text-zinc-500">Unlimited</td>
                </tr>
              </tbody>
            </table>
          </div>
        </form>
      )}

      <div className="mb-5">
        <Select value={planFilter} onValueChange={(v) => setPlanFilter(v ?? "all")}>
          <SelectTrigger className="w-44 bg-white/5 border-white/10 text-white">
            <Filter className="w-4 h-4 mr-2 text-zinc-500" />
            <SelectValue />
          </SelectTrigger>
          <SelectContent className="bg-zinc-900 border-white/10">
            <SelectItem value="all">All Users</SelectItem>
            <SelectItem value="free">Free</SelectItem>
            <SelectItem value="pro">Pro</SelectItem>
            <SelectItem value="pro_max">Pro Max</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <div className="glass-card overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-white/8">
                <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">User</th>
                <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Plan</th>
                <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Joined</th>
                <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Status</th>
                <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Jobs</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((user) => (
                <tr key={user.id} className="border-b border-white/5 hover:bg-white/3 transition-colors">
                  <td className="px-5 py-4">
                    <div className="text-sm font-medium text-white">{user.name}</div>
                    <div className="text-xs text-zinc-500">{user.email}</div>
                  </td>
                  <td className="px-5 py-4">
                    <Badge className={`text-xs ${getPlanBadgeColor(user.plan)}`}>
                      {plans.find((plan) => plan.plan_key === user.plan)?.name ?? PLAN_LIMITS[user.plan].name}
                    </Badge>
                  </td>
                  <td className="px-5 py-4 text-sm text-zinc-400">{formatDate(user.created_at)}</td>
                  <td className="px-5 py-4">
                    <Badge className={user.is_active ? "bg-emerald-500/15 text-emerald-400 border-emerald-500/30 text-xs" : "bg-zinc-800 text-zinc-400 border-zinc-700 text-xs"}>
                      {user.is_active ? "active" : "disabled"}
                    </Badge>
                  </td>
                  <td className="px-5 py-4 text-sm text-zinc-400">{user.total_jobs}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {filtered.length === 0 && (
          <div className="p-8 text-center text-zinc-500 text-sm">No users found.</div>
        )}
      </div>
    </div>
  );
}
