"use client";

import { useEffect, useState, useCallback } from "react";

interface Subscription {
  id: string;
  family_id: string;
  family_name: string | null;
  plan_name: string | null;
  price_paise: number | null;
  status: string;
  razorpay_subscription_id: string;
  razorpay_customer_id: string | null;
  current_start: string | null;
  current_end: string | null;
  cancelled_at: string | null;
  ended_at: string | null;
  created_at: string;
  updated_at: string;
}

interface WebhookEvent {
  razorpay_event_id: string;
  event_type: string;
  received_at: string;
  sub_id: string | null;
  sub_status: string | null;
}

interface Summary {
  total: number;
  byStatus: Record<string, number>;
  mrrPaise: number;
  arrPaise: number;
}

const inr = (paise: number | null | undefined) =>
  "₹" + ((Number(paise) || 0) / 100).toLocaleString("en-IN", { maximumFractionDigits: 0 });

const fmt = (iso: string | null) =>
  iso
    ? new Date(iso).toLocaleString("en-IN", {
        timeZone: "Asia/Kolkata",
        day: "numeric",
        month: "short",
        year: "numeric",
        hour: "2-digit",
        minute: "2-digit",
      })
    : "—";

const STATUS_COLORS: Record<string, string> = {
  active: "bg-emerald-500/15 text-emerald-400",
  authenticated: "bg-emerald-500/15 text-emerald-400",
  pending: "bg-amber-500/15 text-amber-400",
  created: "bg-gray-500/15 text-gray-400",
  halted: "bg-red-500/15 text-red-400",
  cancelled: "bg-red-500/15 text-red-400",
  completed: "bg-blue-500/15 text-blue-400",
  expired: "bg-gray-500/15 text-gray-500",
  paused: "bg-amber-500/15 text-amber-400",
};

export default function AdminSubscriptions() {
  const [subs, setSubs] = useState<Subscription[]>([]);
  const [events, setEvents] = useState<WebhookEvent[]>([]);
  const [summary, setSummary] = useState<Summary | null>(null);
  const [loading, setLoading] = useState(true);
  const [reconciling, setReconciling] = useState(false);
  const [msg, setMsg] = useState<string | null>(null);

  const fetchData = useCallback(async () => {
    try {
      const res = await fetch("/api/admin/subscriptions", { credentials: "include" });
      const data = await res.json();
      if (data.error) throw new Error(data.error);
      setSubs(data.subscriptions || []);
      setEvents(data.webhookEvents || []);
      setSummary(data.summary || null);
    } catch (e) {
      setMsg(e instanceof Error ? e.message : "Failed to load");
    }
    setLoading(false);
  }, []);

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

  const reconcile = async () => {
    setReconciling(true);
    setMsg(null);
    try {
      const res = await fetch("/api/admin/subscriptions", { method: "POST", credentials: "include" });
      const data = await res.json();
      const ok = (data.reconciled || []).filter((r: { ok?: boolean }) => r.ok).length;
      const failed = (data.reconciled || []).filter((r: { ok?: boolean }) => r.ok === false).length;
      setMsg(`Reconciled ${ok} OK${failed ? `, ${failed} failed` : ""}.`);
      fetchData();
    } catch (e) {
      setMsg(e instanceof Error ? e.message : "Reconcile failed");
    }
    setReconciling(false);
  };

  if (loading) return <div className="p-6 text-white">Loading…</div>;

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-bold">Subscriptions</h1>
          <p className="text-gray-400">Razorpay subscription state &amp; webhook monitoring</p>
        </div>
        <button
          onClick={reconcile}
          disabled={reconciling}
          className="px-4 py-2 bg-rose-500 hover:bg-rose-600 disabled:opacity-50 rounded-lg text-sm font-medium"
          title="Replay latest webhook events to re-sync entitlement"
        >
          {reconciling ? "Reconciling…" : "↻ Reconcile"}
        </button>
      </div>

      {msg && (
        <div className="bg-blue-500/15 border border-blue-500/30 text-blue-300 px-4 py-2 rounded-lg text-sm">
          {msg}
        </div>
      )}

      {/* Summary cards */}
      {summary && (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div className="bg-gray-800 p-5 rounded-xl">
            <div className="text-2xl font-bold text-emerald-400">{inr(summary.mrrPaise)}</div>
            <div className="text-gray-400 text-sm">MRR (active)</div>
          </div>
          <div className="bg-gray-800 p-5 rounded-xl">
            <div className="text-2xl font-bold text-rose-400">{inr(summary.arrPaise)}</div>
            <div className="text-gray-400 text-sm">Annual run rate</div>
          </div>
          <div className="bg-gray-800 p-5 rounded-xl">
            <div className="text-2xl font-bold">{summary.byStatus.active || 0}</div>
            <div className="text-gray-400 text-sm">Active</div>
          </div>
          <div className="bg-gray-800 p-5 rounded-xl">
            <div className="text-2xl font-bold text-gray-300">{summary.total}</div>
            <div className="text-gray-400 text-sm">Total subscriptions</div>
          </div>
        </div>
      )}

      {/* Status breakdown chips */}
      {summary && Object.keys(summary.byStatus).length > 0 && (
        <div className="flex flex-wrap gap-2">
          {Object.entries(summary.byStatus).map(([status, count]) => (
            <span key={status} className={`text-xs px-2.5 py-1 rounded-full ${STATUS_COLORS[status] || "bg-gray-700 text-gray-300"}`}>
              {status}: {count}
            </span>
          ))}
        </div>
      )}

      {/* Subscriptions table */}
      <div className="bg-gray-800 rounded-xl overflow-hidden">
        <div className="px-4 py-3 border-b border-gray-700 font-semibold">Subscriptions</div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-gray-700/50 text-gray-300">
              <tr>
                <th className="px-4 py-2 text-left">Family</th>
                <th className="px-4 py-2 text-left">Plan</th>
                <th className="px-4 py-2 text-left">Status</th>
                <th className="px-4 py-2 text-left">Started</th>
                <th className="px-4 py-2 text-left">Renews / Expires</th>
                <th className="px-4 py-2 text-left">Razorpay ID</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-700">
              {subs.map((s) => (
                <tr key={s.id} className="hover:bg-gray-750">
                  <td className="px-4 py-2">{s.family_name || <span className="text-gray-600">{s.family_id.slice(0, 8)}…</span>}</td>
                  <td className="px-4 py-2">
                    {s.plan_name || "—"}
                    {s.price_paise ? <span className="text-gray-500"> · {inr(s.price_paise)}</span> : null}
                  </td>
                  <td className="px-4 py-2">
                    <span className={`text-xs px-2 py-0.5 rounded-full ${STATUS_COLORS[s.status] || "bg-gray-700 text-gray-300"}`}>
                      {s.status}
                    </span>
                  </td>
                  <td className="px-4 py-2 text-gray-400">{fmt(s.current_start)}</td>
                  <td className="px-4 py-2 text-gray-400">
                    {s.cancelled_at ? <span className="text-amber-400">cancels {fmt(s.current_end)}</span> : fmt(s.current_end)}
                  </td>
                  <td className="px-4 py-2 text-gray-500 font-mono text-xs">{s.razorpay_subscription_id}</td>
                </tr>
              ))}
            </tbody>
          </table>
          {subs.length === 0 && <div className="p-8 text-center text-gray-500">No subscriptions yet</div>}
        </div>
      </div>

      {/* Webhook events log */}
      <div className="bg-gray-800 rounded-xl overflow-hidden">
        <div className="px-4 py-3 border-b border-gray-700 font-semibold">Recent Webhook Events</div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-gray-700/50 text-gray-300">
              <tr>
                <th className="px-4 py-2 text-left">Received</th>
                <th className="px-4 py-2 text-left">Event</th>
                <th className="px-4 py-2 text-left">Subscription</th>
                <th className="px-4 py-2 text-left">Status</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-700">
              {events.map((e) => (
                <tr key={e.razorpay_event_id} className="hover:bg-gray-750">
                  <td className="px-4 py-2 text-gray-400">{fmt(e.received_at)}</td>
                  <td className="px-4 py-2 font-mono text-xs">{e.event_type}</td>
                  <td className="px-4 py-2 text-gray-500 font-mono text-xs">{e.sub_id || "—"}</td>
                  <td className="px-4 py-2 text-gray-400">{e.sub_status || "—"}</td>
                </tr>
              ))}
            </tbody>
          </table>
          {events.length === 0 && <div className="p-8 text-center text-gray-500">No webhook events received yet</div>}
        </div>
      </div>
    </div>
  );
}
