"use client";
import { useEffect, useState } from "react";
import { createClient } from "@/utils/supabase/client";
import { 
  AreaChart, Area, XAxis, YAxis, Tooltip, ResponsiveContainer,
  PieChart, Pie, Cell 
} from 'recharts';
import { CreditCard, ArrowUpRight, TrendingUp, Users, DollarSign, Search } from "lucide-react";

export default function SubscriptionsPage() {
  const supabase = createClient();
  const [loading, setLoading] = useState(true);
  const [subs, setSubs] = useState<any[]>([]);
  const [stats, setStats] = useState({
    mrr: 0,
    activePlans: 0,
    churnRate: "2.4%",
    avgRevenue: 0
  });

  useEffect(() => {
    async function fetchSubscriptionData() {
      try {
        // 1. Fetch Subscriptions joined with Profiles
        const { data, error } = await supabase
          .from('subscriptions')
          .select(`
            *,
            profiles:user_id (full_name, email)
          `)
          .order('created_at', { ascending: false });

        if (error) throw error;

        // 2. Calculate Stats
        const activeSubs = data?.filter(s => s.status === 'active') || [];
        const totalMRR = activeSubs.reduce((acc, curr) => {
            // Logic: Assume Annual is $199 and Monthly is $19
            return acc + (curr.plan_interval === 'year' ? 199 / 12 : 19);
        }, 0);

        setSubs(data || []);
        setStats({
          mrr: Math.round(totalMRR),
          activePlans: activeSubs.length,
          churnRate: "2.4%", // This usually requires historical comparison
          avgRevenue: activeSubs.length ? Math.round(totalMRR / activeSubs.length) : 0
        });
      } catch (err) {
        console.error(err);
      } finally {
        setLoading(false);
      }
    }
    fetchSubscriptionData();
  }, [supabase]);

  // Chart Data for Plan Distribution
  const planDistribution = [
    { name: 'Monthly', value: subs.filter(s => s.plan_interval === 'month').length, color: '#D4FB51' },
    { name: 'Annual', value: subs.filter(s => s.plan_interval === 'year').length, color: '#8A74F9' },
  ];

  // Mocked Revenue Growth Data
  const growthData = [
    { month: 'Jan', revenue: 4500 }, { month: 'Feb', revenue: 5200 },
    { month: 'Mar', revenue: 4800 }, { month: 'Apr', revenue: 6100 },
    { month: 'May', revenue: 5900 }, { month: 'Jun', revenue: 7200 },
  ];

  if (loading) return <div className="flex justify-center items-center h-64"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#D4FB51]"></div></div>;

  return (
    <div className="space-y-8 animate-in fade-in duration-700 pb-10">
      
      {/* --- FINANCIAL STATS --- */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <StatCard title="Monthly Revenue (MRR)" value={`$${stats.mrr.toLocaleString()}`} change="+8.2%" icon={<DollarSign size={18}/>} />
        <StatCard title="Active Subscribers" value={stats.activePlans.toLocaleString()} change="+12%" icon={<Users size={18}/>} />
        <StatCard title="Churn Rate" value={stats.churnRate} change="-0.4%" isLoss icon={<TrendingUp size={18}/>} />
        <StatCard title="ARPU" value={`$${stats.avgRevenue}`} change="+2.1%" icon={<CreditCard size={18}/>} />
      </div>

      <div className="grid grid-cols-12 gap-6">
        {/* --- REVENUE GROWTH CHART --- */}
        <div className="col-span-12 lg:col-span-8 bg-white p-8 rounded-[32px] shadow-sm border border-slate-100">
          <div className="flex justify-between items-center mb-8">
            <div>
                <h3 className="text-xl font-bold text-[#1C1C1C]">Revenue Performance</h3>
                <p className="text-xs text-slate-400 font-bold uppercase tracking-widest mt-1">Growth over last 6 months</p>
            </div>
            <button className="bg-black text-white text-[10px] px-4 py-2 rounded-xl font-black uppercase tracking-wider">Download Report</button>
          </div>
          <div className="h-72">
            <ResponsiveContainer width="100%" height="100%">
              <AreaChart data={growthData as any}>
                <defs>
                  <linearGradient id="colorRev" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%" stopColor="#D4FB51" stopOpacity={0.3}/>
                    <stop offset="95%" stopColor="#D4FB51" stopOpacity={0}/>
                  </linearGradient>
                </defs>
                <XAxis dataKey="month" axisLine={false} tickLine={false} tick={{fontSize: 12, fill: '#9CA3AF', fontWeight: 600}} dy={10} />
                <YAxis hide />
                <Tooltip contentStyle={{borderRadius: '16px', border: 'none', boxShadow: '0 10px 30px rgba(0,0,0,0.05)'}} />
                <Area type="monotone" dataKey="revenue" stroke="#D4FB51" strokeWidth={4} fillOpacity={1} fill="url(#colorRev)" />
              </AreaChart>
            </ResponsiveContainer>
          </div>
        </div>

        {/* --- PLAN DISTRIBUTION --- */}
        <div className="col-span-12 lg:col-span-4 bg-white p-8 rounded-[32px] shadow-sm border border-slate-100">
          <h3 className="text-lg font-bold text-[#1C1C1C] mb-8">Plan Mix</h3>
          <div className="h-48 relative">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie data={planDistribution} innerRadius={60} outerRadius={80} paddingAngle={5} dataKey="value">
                  {planDistribution.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
              </PieChart>
            </ResponsiveContainer>
            <div className="absolute inset-0 flex flex-col items-center justify-center pointer-events-none">
                <p className="text-2xl font-black">{stats.activePlans}</p>
                <p className="text-[10px] font-bold text-slate-400 uppercase">Total</p>
            </div>
          </div>
          <div className="mt-8 space-y-3">
            {planDistribution.map(plan => (
                <div key={plan.name} className="flex justify-between items-center bg-slate-50 p-3 rounded-xl">
                    <div className="flex items-center gap-2 text-xs font-bold text-[#1C1C1C]">
                        <div className="w-2 h-2 rounded-full" style={{backgroundColor: plan.color}}></div> {plan.name}
                    </div>
                    <span className="text-xs font-black">{plan.value} users</span>
                </div>
            ))}
          </div>
        </div>

        {/* --- DETAILED SUBSCRIPTIONS TABLE --- */}
        <div className="col-span-12 bg-white rounded-[32px] shadow-sm border border-slate-100 overflow-hidden">
          <div className="p-8 border-b border-slate-50 flex justify-between items-center">
            <h3 className="text-lg font-bold text-[#1C1C1C]">Subscription Details</h3>
            <div className="relative">
                <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
                <input type="text" placeholder="Filter by user..." className="pl-10 pr-4 py-2 bg-slate-50 rounded-xl text-xs font-bold outline-none border border-transparent focus:border-[#D4FB51] transition-all" />
            </div>
          </div>
          <table className="w-full text-left">
            <thead>
              <tr className="bg-slate-50/50 text-[10px] font-black text-slate-400 uppercase tracking-widest">
                <th className="px-8 py-4">Subscriber</th>
                <th className="px-8 py-4">Plan</th>
                <th className="px-8 py-4 text-center">Status</th>
                <th className="px-8 py-4">Next Billing</th>
                <th className="px-8 py-4 text-right">Amount</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50">
              {subs.map((sub) => (
                <tr key={sub.id} className="hover:bg-slate-50 transition-colors cursor-pointer group">
                  <td className="px-8 py-5">
                    <p className="text-sm font-bold text-[#1C1C1C] group-hover:text-[#8A74F9] transition-colors">
                        {sub.profiles?.full_name || 'Anonymous User'}
                    </p>
                    <p className="text-[10px] text-slate-400 font-medium">{sub.profiles?.email}</p>
                  </td>
                  <td className="px-8 py-5 text-xs font-bold text-slate-600 capitalize">
                    {sub.plan_interval}ly Premium
                  </td>
                  <td className="px-8 py-5">
                    <div className="flex justify-center">
                        <span className={`text-[10px] font-black px-3 py-1 rounded-lg uppercase border ${
                        sub.status === 'active' ? 'text-emerald-500 bg-emerald-50 border-emerald-100' : 'text-slate-400 bg-slate-50 border-slate-100'
                        }`}>
                        {sub.status}
                        </span>
                    </div>
                  </td>
                  <td className="px-8 py-5 text-xs font-medium text-slate-500">
                    {sub.current_period_end ? new Date(sub.current_period_end).toLocaleDateString() : 'N/A'}
                  </td>
                  <td className="px-8 py-5 text-right font-black text-[#1C1C1C]">
                    ${sub.plan_interval === 'year' ? '199.00' : '19.00'}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function StatCard({ title, value, change, isLoss = false, icon }: any) {
  return (
    <div className="bg-white p-8 rounded-[32px] shadow-sm relative overflow-hidden transition-all hover:translate-y-[-4px] border border-slate-50">
      <div className="flex justify-between items-start mb-4">
          <div className="bg-slate-50 p-2 rounded-lg text-slate-400">{icon}</div>
          <p className={`text-[10px] font-black flex items-center gap-1 ${isLoss ? 'text-rose-500' : 'text-emerald-500'}`}>
            {change} <ArrowUpRight size={10} />
          </p>
      </div>
      <p className="text-[11px] font-black text-slate-400 uppercase tracking-widest">{title}</p>
      <p className="text-3xl font-black text-[#1C1C1C] mt-1 tracking-tighter">{value}</p>
    </div>
  );
}