"use client";

import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { StatCard } from "@/components/dashboard/stats";
import { DealCard } from "@/components/dashboard/deal-card";
import {
  FileText,
  Users,
  Target,
  Send,
  TrendingUp,
  Plus,
  ArrowRight,
  Activity,
  BarChart3,
  Zap,
} from "lucide-react";
import { useApiData } from "@/hooks/use-api-data";
import { mockSellerLeads, mockBuyers, mockMatches, mockOutreach, recentActivity } from "@/lib/mock-data";
import type { SellerLead, Match, Outreach } from "@/types";

export default function DashboardPage() {
  const { data: sellers, loading: loadingSellers } = useApiData<SellerLead[]>('/api/sellers', []);
  const { data: matches } = useApiData<Match[]>('/api/matches', []);
  const { data: outreach } = useApiData<Outreach[]>('/api/outreach', []);
  const { data: buyers } = useApiData<{ id: string }[]>('/api/buyers', []);

  // Use API data, fall back to mock if empty
  const sellerLeads = sellers.length > 0 ? sellers : mockSellerLeads;
  const allMatches = matches.length > 0 ? matches : mockMatches;
  const allOutreach = outreach.length > 0 ? outreach : mockOutreach;
  const buyerCount = buyers.length > 0 ? buyers.length : mockBuyers.length;

  const activeDeals = sellerLeads.filter((l) => l.status === "active").length;
  const totalMatches = allMatches.length;
  const sentOutreach = allOutreach.filter((o) => o.status !== "draft").length;
  const repliedOutreach = allOutreach.filter((o) => o.replied_at).length;
  const responseRate = sentOutreach > 0 ? Math.round((repliedOutreach / sentOutreach) * 100) : 0;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-navy-900">Dashboard</h1>
          <p className="text-sm text-navy-500 mt-1">
            Welcome back, John. Here&apos;s your deal pipeline overview.
          </p>
        </div>
        <div className="flex items-center gap-3 w-full sm:w-auto">
          <Link href="/dashboard/sellers/new" className="w-full sm:w-auto">
            <Button variant="gold" className="w-full sm:w-auto">
              <Plus className="mr-2 h-4 w-4" />
              Add Seller Lead
            </Button>
          </Link>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <StatCard
          title="Active Deals"
          value={activeDeals}
          change="+2 this week"
          changeType="positive"
          icon={FileText}
          iconColor="text-blue-600"
        />
        <StatCard
          title="Total Buyers"
          value={buyerCount}
          change="+3 this month"
          changeType="positive"
          icon={Users}
          iconColor="text-emerald-600"
        />
        <StatCard
          title="Matches Made"
          value={totalMatches}
          change="+5 this week"
          changeType="positive"
          icon={Target}
          iconColor="text-gold-600"
        />
        <StatCard
          title="Response Rate"
          value={`${responseRate}%`}
          change="+8% vs last month"
          changeType="positive"
          icon={TrendingUp}
          iconColor="text-purple-600"
        />
      </div>

      {/* Main content grid */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Active Deals */}
        <div className="lg:col-span-2 space-y-4">
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold text-navy-900">Active Deals</h2>
            <Link href="/dashboard/sellers">
              <Button variant="ghost" size="sm">
                View All
                <ArrowRight className="ml-1 h-4 w-4" />
              </Button>
            </Link>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            {sellerLeads.slice(0, 4).map((deal) => {
              const matchCount = allMatches.filter((m) => m.lead_id === deal.id).length;
              return <DealCard key={deal.id} deal={deal} matchCount={matchCount} />;
            })}
          </div>
        </div>

        {/* Recent Activity */}
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold text-navy-900">Recent Activity</h2>
            <Activity className="h-4 w-4 text-navy-400" />
          </div>
          <Card>
            <CardContent className="p-0">
              <div className="divide-y divide-navy-50">
                {recentActivity.map((item, idx) => (
                  <div key={idx} className="flex items-start gap-3 p-4">
                    <div className="mt-0.5">
                      {item.type === "match" && (
                        <div className="h-2 w-2 rounded-full bg-gold-500" />
                      )}
                      {item.type === "reply" && (
                        <div className="h-2 w-2 rounded-full bg-emerald-500" />
                      )}
                      {item.type === "nda" && (
                        <div className="h-2 w-2 rounded-full bg-blue-500" />
                      )}
                      {item.type === "lead" && (
                        <div className="h-2 w-2 rounded-full bg-purple-500" />
                      )}
                      {item.type === "open" && (
                        <div className="h-2 w-2 rounded-full bg-amber-500" />
                      )}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm text-navy-700 leading-snug">{item.message}</p>
                      <p className="text-xs text-navy-400 mt-0.5">{item.time}</p>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>

          {/* Quick Actions */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm font-semibold flex items-center gap-2">
                <Zap className="h-4 w-4 text-gold-500" />
                Quick Actions
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-2">
              <Link href="/dashboard/sellers/new" className="block">
                <Button variant="outline" className="w-full justify-start" size="sm">
                  <Plus className="mr-2 h-4 w-4" />
                  New Seller Lead
                </Button>
              </Link>
              <Link href="/dashboard/buyers" className="block">
                <Button variant="outline" className="w-full justify-start" size="sm">
                  <Users className="mr-2 h-4 w-4" />
                  Manage Buyers
                </Button>
              </Link>
              <Link href="/dashboard/matches" className="block">
                <Button variant="outline" className="w-full justify-start" size="sm">
                  <Target className="mr-2 h-4 w-4" />
                  View Matches
                </Button>
              </Link>
              <Link href="/dashboard/outreach" className="block">
                <Button variant="outline" className="w-full justify-start" size="sm">
                  <Send className="mr-2 h-4 w-4" />
                  Outreach Center
                </Button>
              </Link>
            </CardContent>
          </Card>

          {/* Performance Summary */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm font-semibold flex items-center gap-2">
                <BarChart3 className="h-4 w-4 text-navy-500" />
                This Month
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-sm text-navy-500">Outreach Sent</span>
                <span className="text-sm font-semibold text-navy-900">{sentOutreach}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-navy-500">Emails Opened</span>
                <span className="text-sm font-semibold text-navy-900">
                  {allOutreach.filter((o) => o.opened_at).length}
                </span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-navy-500">Replies Received</span>
                <span className="text-sm font-semibold text-navy-900">{repliedOutreach}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-navy-500">NDAs Signed</span>
                <span className="text-sm font-semibold text-navy-900">3</span>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
