"use client";

import { useState } from "react";

import { toast } from "sonner";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ANALYTICS_DATA } from "@/data/analytics";
import { DEMO_SUBSCRIPTIONS } from "@/data/subscriptions";
import { DEMO_TRANSACTIONS } from "@/data/transactions";
import { DEMO_USERS } from "@/data/users";

const STATUS_COLORS: Record<string, string> = {
  succeeded: "bg-green-100 text-green-700",
  failed: "bg-red-100 text-red-700",
  refunded: "bg-amber-100 text-amber-700",
};

const SUB_STATUS_COLORS: Record<string, string> = {
  active: "bg-green-100 text-green-700",
  cancelled: "bg-gray-100 text-gray-700",
  expired: "bg-red-100 text-red-700",
};

export default function PaymentsPage() {
  const [filter, setFilter] = useState<string>("all");

  const filtered = filter === "all" ? DEMO_TRANSACTIONS : DEMO_TRANSACTIONS.filter((t) => t.status === filter);
  const totalRevenue = DEMO_TRANSACTIONS.filter((t) => t.status === "succeeded").reduce((s, t) => s + t.amount, 0);
  const failedCount = DEMO_TRANSACTIONS.filter((t) => t.status === "failed").length;

  return (
    <div className="space-y-6 p-6">
      <div>
        <h1 className="text-2xl font-bold text-gray-900">Payments & Subscriptions</h1>
        <p className="text-sm text-gray-500 mt-1">Monitor revenue, transactions, and subscription billing.</p>
      </div>

      <div className="grid gap-4 sm:grid-cols-4">
        {[
          { label: "MRR", value: `CHF ${(ANALYTICS_DATA.kpis.activeSubscriptions * 149).toLocaleString()}`, sub: "183 active subscriptions" },
          { label: "Total Revenue", value: `CHF ${ANALYTICS_DATA.kpis.totalRevenueChf.toLocaleString()}`, sub: "All time" },
          { label: "Active Subscriptions", value: ANALYTICS_DATA.kpis.activeSubscriptions, sub: "Professional tier" },
          { label: "Failed Payments", value: failedCount, sub: "This month" },
        ].map((kpi) => (
          <Card key={kpi.label} className="border-gray-100">
            <CardContent className="p-5">
              <p className="text-xs text-gray-500 uppercase tracking-wide">{kpi.label}</p>
              <p className="text-2xl font-bold text-gray-900 mt-1">{kpi.value}</p>
              <p className="text-xs text-gray-400 mt-0.5">{kpi.sub}</p>
            </CardContent>
          </Card>
        ))}
      </div>

      <Tabs defaultValue="transactions">
        <TabsList className="bg-gray-100">
          <TabsTrigger value="transactions">Transactions</TabsTrigger>
          <TabsTrigger value="subscriptions">Subscriptions</TabsTrigger>
        </TabsList>

        <TabsContent value="transactions" className="mt-4">
          <Card className="border-gray-100">
            <CardHeader className="pb-3 flex-row items-center justify-between gap-3">
              <CardTitle className="text-base">Transaction History</CardTitle>
              <div className="flex gap-2">
                {["all", "succeeded", "failed", "refunded"].map((f) => (
                  <Button
                    key={f}
                    size="sm"
                    variant={filter === f ? "default" : "outline"}
                    className={`h-7 text-xs capitalize ${filter === f ? "bg-teal-600 hover:bg-teal-700 text-white" : ""}`}
                    onClick={() => setFilter(f)}
                  >
                    {f}
                  </Button>
                ))}
              </div>
            </CardHeader>
            <CardContent className="p-0">
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead className="bg-gray-50 border-y border-gray-100">
                    <tr>
                      {["ID", "User", "Package", "Amount", "Status", "Date", "Actions"].map((h) => (
                        <th key={h} className="px-4 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wide">{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-50">
                    {filtered.map((txn) => {
                      const user = DEMO_USERS.find((u) => u.id === txn.userId);
                      return (
                        <tr key={txn.id} className="hover:bg-gray-50/50">
                          <td className="px-4 py-3 font-mono text-xs text-gray-400">{txn.stripePaymentIntentId.slice(-8)}</td>
                          <td className="px-4 py-3 font-medium text-gray-900">{user ? `${user.firstName} ${user.lastName}` : txn.userId}</td>
                          <td className="px-4 py-3 capitalize">{txn.packageId}</td>
                          <td className="px-4 py-3 font-semibold">CHF {txn.amount}</td>
                          <td className="px-4 py-3">
                            <Badge className={STATUS_COLORS[txn.status] + " border-0 capitalize"}>{txn.status}</Badge>
                          </td>
                          <td className="px-4 py-3 text-gray-400 text-xs">{new Date(txn.createdAt).toLocaleDateString()}</td>
                          <td className="px-4 py-3">
                            <Button size="sm" variant="ghost" className="h-7 text-xs" onClick={() => toast.info("Refund action simulated (PoC)")}>Refund</Button>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="subscriptions" className="mt-4">
          <Card className="border-gray-100">
            <CardHeader className="pb-3"><CardTitle className="text-base">Active Subscriptions</CardTitle></CardHeader>
            <CardContent className="p-0">
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead className="bg-gray-50 border-y border-gray-100">
                    <tr>
                      {["User", "Plan", "Start Date", "Next Billing", "Amount", "Status", "Actions"].map((h) => (
                        <th key={h} className="px-4 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wide">{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-50">
                    {DEMO_SUBSCRIPTIONS.map((sub) => {
                      const user = DEMO_USERS.find((u) => u.id === sub.userId);
                      return (
                        <tr key={sub.id} className="hover:bg-gray-50/50">
                          <td className="px-4 py-3 font-medium text-gray-900">{user ? `${user.firstName} ${user.lastName}` : sub.userId}</td>
                          <td className="px-4 py-3 capitalize">{sub.packageId}</td>
                          <td className="px-4 py-3 text-gray-500 text-xs">{sub.startDate}</td>
                          <td className="px-4 py-3 text-gray-500 text-xs">{sub.nextBillingDate ?? "—"}</td>
                          <td className="px-4 py-3 font-semibold">CHF {sub.priceChf}/mo</td>
                          <td className="px-4 py-3">
                            <Badge className={SUB_STATUS_COLORS[sub.status] + " border-0 capitalize"}>{sub.status}</Badge>
                          </td>
                          <td className="px-4 py-3">
                            <Button size="sm" variant="ghost" className="h-7 text-xs text-red-600 hover:text-red-700" onClick={() => toast.info("Cancellation triggered (PoC simulation)")}>Cancel</Button>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
              <div className="border-t border-gray-100 px-4 py-3">
                <p className="text-xs text-gray-400">Showing {DEMO_SUBSCRIPTIONS.length} active subscription(s) — demo data only. Production will show all {ANALYTICS_DATA.kpis.activeSubscriptions} subscriptions.</p>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
