"use client";

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { StatCard } from "@/components/dashboard/stats";
import { useApiData } from "@/hooks/use-api-data";
import {
  Users,
  DollarSign,
  CreditCard,
  TrendingUp,
  Building2,
  Target,
  Send,
  BarChart3,
} from "lucide-react";

const monthlyRevenue = [
  { month: "Jul", revenue: 5940 },
  { month: "Aug", revenue: 8910 },
  { month: "Sep", revenue: 11880 },
  { month: "Oct", revenue: 14850 },
  { month: "Nov", revenue: 17820 },
  { month: "Dec", revenue: 20790 },
];

interface AdminStats {
  users: { total: number; agents: number; buyers: number };
  leads: number;
  buyers_count: number;
  matches: { total: number; avg_score: number };
  outreach_sent: number;
  active_subscriptions: number;
}

export default function AdminPage() {
  const { data: stats } = useApiData<AdminStats | null>('/api/admin/stats', null);

  // Fallback to hard-coded values if API doesn't return (not logged in as admin)
  const totalUsers = stats?.users?.total ?? 284;
  const userBreakdown = stats ? `${stats.users.agents} agents, ${stats.users.buyers} buyers` : "42 agents, 242 buyers";
  const activeSubs = stats?.active_subscriptions ?? 70;
  const platformDeals = stats?.leads ?? 156;
  const totalMatches = stats?.matches?.total ?? 1247;
  const avgScore = stats?.matches?.avg_score ? `${stats.matches.avg_score.toFixed(1)}%` : "78.4%";
  const emailsSent = stats?.outreach_sent ?? 3892;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-navy-900">Admin Dashboard</h1>
        <p className="text-sm text-navy-500 mt-1">System overview and analytics</p>
      </div>

      {/* Revenue & User Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <StatCard
          title="Monthly Revenue"
          value="$20,790"
          change="+16.7% vs last month"
          changeType="positive"
          icon={DollarSign}
          iconColor="text-emerald-600"
        />
        <StatCard
          title="Active Subscriptions"
          value={activeSubs}
          change="+8 this month"
          changeType="positive"
          icon={CreditCard}
          iconColor="text-blue-600"
        />
        <StatCard
          title="Total Users"
          value={totalUsers}
          change={userBreakdown}
          changeType="neutral"
          icon={Users}
          iconColor="text-indigo-600"
        />
        <StatCard
          title="Platform Deals"
          value={platformDeals}
          change="+23 this month"
          changeType="positive"
          icon={Building2}
          iconColor="text-gold-600"
        />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Revenue Chart (simplified) */}
        <div className="lg:col-span-2">
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center gap-2">
                <BarChart3 className="h-5 w-5 text-navy-500" />
                Revenue Growth
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex items-end gap-3 h-48">
                {monthlyRevenue.map((item) => (
                  <div key={item.month} className="flex-1 flex flex-col items-center gap-1">
                    <span className="text-xs font-semibold text-navy-700">
                      ${(item.revenue / 1000).toFixed(1)}k
                    </span>
                    <div
                      className="w-full rounded-t-md bg-gradient-to-t from-navy-800 to-navy-600 transition-all hover:from-gold-500 hover:to-gold-400"
                      style={{
                        height: `${(item.revenue / 25000) * 160}px`,
                        minHeight: "20px",
                      }}
                    />
                    <span className="text-xs text-navy-500">{item.month}</span>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Platform Stats */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">Platform Metrics</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center justify-between p-3 rounded-lg bg-navy-50">
              <div className="flex items-center gap-2">
                <Target className="h-4 w-4 text-gold-600" />
                <span className="text-sm text-navy-700">Total Matches</span>
              </div>
              <span className="text-sm font-bold text-navy-900">{totalMatches.toLocaleString()}</span>
            </div>
            <div className="flex items-center justify-between p-3 rounded-lg bg-navy-50">
              <div className="flex items-center gap-2">
                <Send className="h-4 w-4 text-blue-600" />
                <span className="text-sm text-navy-700">Emails Sent</span>
              </div>
              <span className="text-sm font-bold text-navy-900">{emailsSent.toLocaleString()}</span>
            </div>
            <div className="flex items-center justify-between p-3 rounded-lg bg-navy-50">
              <div className="flex items-center gap-2">
                <TrendingUp className="h-4 w-4 text-emerald-600" />
                <span className="text-sm text-navy-700">Avg Match Score</span>
              </div>
              <span className="text-sm font-bold text-navy-900">{avgScore}</span>
            </div>
            <div className="flex items-center justify-between p-3 rounded-lg bg-navy-50">
              <div className="flex items-center gap-2">
                <DollarSign className="h-4 w-4 text-purple-600" />
                <span className="text-sm text-navy-700">Deal Volume</span>
              </div>
              <span className="text-sm font-bold text-navy-900">$2.4B</span>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Top Agents — keep static data since this is illustrative */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">Top Agents</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="overflow-x-auto -mx-px">
            <table className="w-full min-w-[500px]">
              <thead>
                <tr className="border-b border-navy-100">
                  <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-4 py-3">
                    Agent
                  </th>
                  <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-4 py-3">
                    Active Deals
                  </th>
                  <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-4 py-3">
                    Matches
                  </th>
                  <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-4 py-3">
                    MRR
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-navy-50">
                {[
                  { name: "John Doe", deals: 6, matches: 18, revenue: "$297" },
                  { name: "Jane Smith", deals: 4, matches: 12, revenue: "$297" },
                  { name: "Mike Johnson", deals: 3, matches: 9, revenue: "$297" },
                  { name: "Sarah Lee", deals: 5, matches: 15, revenue: "$297" },
                  { name: "Chris Wong", deals: 2, matches: 7, revenue: "$297" },
                ].map((agent) => (
                  <tr key={agent.name} className="hover:bg-navy-25 transition-colors">
                    <td className="px-4 py-3 text-sm font-medium text-navy-900">
                      {agent.name}
                    </td>
                    <td className="px-4 py-3 text-sm text-navy-700">{agent.deals}</td>
                    <td className="px-4 py-3 text-sm text-navy-700">{agent.matches}</td>
                    <td className="px-4 py-3 text-sm font-semibold text-emerald-600">
                      {agent.revenue}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
