"use client";
import { useEffect, useState } from "react";
import { createClient } from "@/utils/supabase/client";
import { 
  AreaChart, Area, XAxis, YAxis, Tooltip, ResponsiveContainer,
  BarChart, Bar
} from 'recharts';
import { MoreHorizontal, User, Edit2 } from "lucide-react";

export default function AnalyticsPage() {
  const supabase = createClient();
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState({ 
    totalRevenue: 0, 
    totalUsers: 0, 
    activeAppointments: 0, 
    activityRate: 0 
  });
  const [recentUsers, setRecentUsers] = useState<any[]>([]);
  const [planData, setPlanData] = useState<any[]>([]);

  useEffect(() => {
    async function fetchDatabaseData() {
      try {
        // 1. Fetch Total Users from 'profiles'
        const { count: userCount } = await supabase
          .from('profiles')
          .select('*', { count: 'exact', head: true });

        // 2. Fetch Active Subscriptions & Calculate Revenue
        const { data: subs } = await supabase
          .from('subscriptions')
          .select('status')
          .eq('status', 'active');
        
        const activeSubCount = subs?.length || 0;
        // Calculation: Assuming $19.99 average per active subscription
        const revenue = activeSubCount * 19.99;

        // 3. Fetch Active Appointments (Your 'Reservations')
        const { count: appointmentCount } = await supabase
          .from('appointments')
          .select('*', { count: 'exact', head: true });

        // 4. Fetch Engagement (Activity Rate)
        // We'll calculate this based on how many users have created 'feeding_logs'
        const { data: logs } = await supabase.from('feeding_logs').select('parent_id');
        const uniqueActiveUsers = new Set(logs?.map(l => l.parent_id)).size;
        const rate = userCount ? Math.round((uniqueActiveUsers / userCount) * 100) : 0;

        // 5. Fetch Recent Sign-ups for the list
        const { data: recent } = await supabase
          .from('profiles')
          .select('id, full_name, email, created_at, onboarding_complete')
          .order('created_at', { ascending: false })
          .limit(4);

        // 6. Plan Breakdown (Grouping profiles by current_plan)
        const { data: profiles } = await supabase.from('profiles').select('current_plan');
        const counts = profiles?.reduce((acc: any, curr: any) => {
          const plan = curr.current_plan || 'free';
          acc[plan] = (acc[plan] || 0) + 1;
          return acc;
        }, {});

        setStats({
          totalRevenue: revenue,
          totalUsers: userCount || 0,
          activeAppointments: appointmentCount || 0,
          activityRate: rate
        });

        setRecentUsers(recent || []);
        
        setPlanData([
          { label: "Premium Annual", count: counts?.annual || 0, color: "bg-[#D4FB51]" },
          { label: "Premium Monthly", count: counts?.monthly || 0, color: "bg-emerald-400" },
          { label: "Free Plan", count: counts?.free || 0, color: "bg-slate-200" },
        ]);

      } catch (error) {
        console.error("Database fetch error:", error);
      } finally {
        setLoading(false);
      }
    }

    fetchDatabaseData();
  }, [supabase]);

  // Mocked trend data for the charts (Time-series grouping requires complex SQL)
  const chartData = [
    { name: 'Mon', value: 40 }, { name: 'Tue', value: 60 }, { name: 'Wed', value: 45 },
    { name: 'Thu', value: 90 }, { name: 'Fri', value: 65 }, { name: 'Sat', value: 85 }, { name: 'Sun', value: 50 },
  ];

  if (loading) return (
    <div className="flex items-center justify-center h-[60vh]">
      <div className="w-8 h-8 border-4 border-[#D4FB51] border-t-transparent rounded-full animate-spin"></div>
    </div>
  );

  return (
    <div className="space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-700">
      
      {/* --- REAL STATS CARDS --- */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <StatCard title="Total Revenue" value={`$${Math.round(stats.totalRevenue).toLocaleString()}`} change="+12%" />
        <StatCard title="App Users" value={stats.totalUsers.toLocaleString()} change="+5%" />
        <StatCard title="Appointments" value={stats.activeAppointments.toLocaleString()} change="+18%" />
        <StatCard title="Engagement" value={`${stats.activityRate}%`} change="-2%" isLoss />
      </div>

      <div className="grid grid-cols-12 gap-6">
        {/* --- RECENT USERS TABLE --- */}
        <div className="col-span-12 lg:col-span-7 bg-white p-8 rounded-[32px] shadow-sm border border-slate-100">
          <div className="flex justify-between items-center mb-8">
            <h3 className="text-lg font-bold text-[#1C1C1C]">Latest Sign-ups</h3>
            <button className="text-xs text-slate-400 font-bold hover:text-black">View All</button>
          </div>
          <div className="space-y-6">
            {recentUsers.map(user => (
              <div key={user.id} className="flex items-center justify-between group">
                <div className="flex items-center gap-4">
                  <div className="w-11 h-11 rounded-full bg-slate-50 flex items-center justify-center border border-slate-100">
                    <User size={18} className="text-slate-400" />
                  </div>
                  <div>
                    <p className="text-sm font-bold text-[#1C1C1C]">{user.full_name || 'Anonymous'}</p>
                    <p className="text-[10px] text-slate-400 font-black uppercase tracking-widest">{user.email}</p>
                  </div>
                </div>
                <div className="flex items-center gap-8">
                   <p className="text-xs text-slate-400 font-bold">
                    {new Date(user.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                   </p>
                   <span className={`text-[10px] font-black px-3 py-1 rounded-md border uppercase ${
                     user.onboarding_complete ? 'text-emerald-500 bg-emerald-50 border-emerald-100' : 'text-amber-500 bg-amber-50 border-amber-100'
                   }`}>
                    {user.onboarding_complete ? 'Active' : 'Pending'}
                   </span>
                   <Edit2 size={14} className="text-slate-200 hover:text-black cursor-pointer" />
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* --- USAGE CHART --- */}
        <div className="col-span-12 lg:col-span-5 bg-white p-8 rounded-[32px] shadow-sm border border-slate-100">
          <h3 className="text-lg font-bold text-[#1C1C1C] mb-8">Engagement Trend</h3>
          <div className="h-56">
            <ResponsiveContainer width="100%" height="100%">
              <AreaChart data={chartData as any}>
                <defs>
                  <linearGradient id="colorVal" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%" stopColor="#8A74F9" stopOpacity={0.2}/>
                    <stop offset="95%" stopColor="#8A74F9" stopOpacity={0}/>
                  </linearGradient>
                </defs>
                <Area type="monotone" dataKey="value" stroke="#8A74F9" strokeWidth={3} fillOpacity={1} fill="url(#colorVal)" />
                <Tooltip contentStyle={{borderRadius: '16px', border: 'none', boxShadow: '0 10px 30px rgba(0,0,0,0.05)'}} />
              </AreaChart>
            </ResponsiveContainer>
          </div>
        </div>

        {/* --- PLAN BREAKDOWN --- */}
        <div className="col-span-12 bg-white p-8 rounded-[32px] shadow-sm border border-slate-100">
          <h3 className="text-lg font-bold text-[#1C1C1C] mb-8">Subscription Distribution</h3>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-12">
            {planData.map((plan, idx) => (
              <div key={idx} className="flex justify-between items-center bg-slate-50 p-4 rounded-2xl">
                <div className="flex items-center gap-3 font-bold text-[#1C1C1C] text-sm">
                  <div className={`w-3 h-3 rounded-full ${plan.color}`}></div> {plan.label}
                </div>
                <span className="text-lg font-black text-[#1C1C1C]">{plan.count}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function StatCard({ title, value, change, isLoss = false }: any) {
  return (
    <div className="bg-white p-8 rounded-[32px] shadow-sm relative overflow-hidden transition-all hover:shadow-md border border-slate-50">
      <p className="text-[11px] font-black text-slate-400 mb-3 uppercase tracking-widest">{title}</p>
      <div className="flex items-baseline gap-4">
        <p className="text-3xl font-black text-[#1C1C1C] tracking-tighter">{value}</p>
        <p className={`text-xs font-black ${isLoss ? 'text-rose-500' : 'text-emerald-500'}`}>{change}</p>
      </div>
      <div className="absolute top-6 right-8 text-slate-200 cursor-pointer"><MoreHorizontal size={20} /></div>
    </div>
  );
}