
'use client';

import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { 
  TrendingUp, 
  TrendingDown, 
  DollarSign, 
  Award, 
  Target, 
  Users,
  FileText,
  CheckCircle,
  Star,
  Trophy,
  BarChart3,
  Download
} from 'lucide-react';
import { Line, Bar } from 'react-chartjs-2';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  Title,
  Tooltip,
  Legend,
  Filler
} from 'chart.js';

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  Title,
  Tooltip,
  Legend,
  Filler
);

interface PerformanceMetric {
  id: string;
  userId: string;
  partnerId: string;
  period: string;
  leadsAssigned: number;
  quotesSubmitted: number;
  contractsWon: number;
  revenue: number;
  averageRating: number;
  completionRate: number;
  customerSatisfaction: number;
  createdAt: string;
  updatedAt: string;
  user: {
    name: string | null;
    email: string;
    companyName: string | null;
  };
  partner: {
    companyName: string;
  };
}

interface LeaderboardEntry {
  rank: number;
  userId: string;
  partnerName: string;
  companyName: string;
  revenue: number;
  contractsWon: number;
  averageRating: number;
  completionRate: number;
  trend: 'up' | 'down' | 'stable';
  change: number;
}

interface DashboardStats {
  totalRevenue: number;
  totalContracts: number;
  averageRating: number;
  completionRate: number;
  revenueChange: number;
  contractsChange: number;
  ratingChange: number;
  completionChange: number;
}

export default function ContractorPerformanceDashboard({ 
  userRole, 
  userId 
}: { 
  userRole: string; 
  userId: string;
}) {
  const [period, setPeriod] = useState<'monthly' | 'quarterly' | 'yearly'>('monthly');
  const [timeRange, setTimeRange] = useState<'6' | '12' | '24'>('6');
  const [metrics, setMetrics] = useState<PerformanceMetric[]>([]);
  const [leaderboard, setLeaderboard] = useState<LeaderboardEntry[]>([]);
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [selectedView, setSelectedView] = useState<'overview' | 'revenue' | 'leaderboard'>('overview');

  useEffect(() => {
    fetchPerformanceData();
  }, [period, timeRange]);

  const fetchPerformanceData = async () => {
    setLoading(true);
    try {
      const [metricsRes, leaderboardRes, statsRes] = await Promise.all([
        fetch(`/api/contractors/performance?period=${period}&timeRange=${timeRange}`),
        fetch(`/api/contractors/leaderboard?period=${period}`),
        fetch(`/api/contractors/stats?period=${period}`)
      ]);

      if (metricsRes.ok) {
        const data = await metricsRes.json();
        setMetrics(data.metrics || []);
      }

      if (leaderboardRes.ok) {
        const data = await leaderboardRes.json();
        setLeaderboard(data.leaderboard || []);
      }

      if (statsRes.ok) {
        const data = await statsRes.json();
        setStats(data.stats);
      }
    } catch (error) {
      console.error('Error fetching performance data:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleExport = async () => {
    try {
      const response = await fetch(`/api/contractors/performance/export?period=${period}&timeRange=${timeRange}`);
      if (response.ok) {
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `contractor-performance-${period}-${new Date().toISOString().split('T')[0]}.csv`;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
      }
    } catch (error) {
      console.error('Error exporting data:', error);
    }
  };

  // Prepare chart data
  const prepareRevenueChartData = () => {
    const sortedMetrics = [...metrics].sort((a, b) => 
      new Date(a.period).getTime() - new Date(b.period).getTime()
    );

    return {
      labels: sortedMetrics.map(m => m.period),
      datasets: [
        {
          label: 'Revenue',
          data: sortedMetrics.map(m => m.revenue),
          borderColor: 'rgb(59, 130, 246)',
          backgroundColor: 'rgba(59, 130, 246, 0.1)',
          fill: true,
          tension: 0.4,
        }
      ]
    };
  };

  const prepareContractsChartData = () => {
    const sortedMetrics = [...metrics].sort((a, b) => 
      new Date(a.period).getTime() - new Date(b.period).getTime()
    );

    return {
      labels: sortedMetrics.map(m => m.period),
      datasets: [
        {
          label: 'Contracts Won',
          data: sortedMetrics.map(m => m.contractsWon),
          backgroundColor: 'rgba(34, 197, 94, 0.6)',
          borderColor: 'rgb(34, 197, 94)',
          borderWidth: 1,
        },
        {
          label: 'Quotes Submitted',
          data: sortedMetrics.map(m => m.quotesSubmitted),
          backgroundColor: 'rgba(234, 179, 8, 0.6)',
          borderColor: 'rgb(234, 179, 8)',
          borderWidth: 1,
        }
      ]
    };
  };

  const chartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        position: 'top' as const,
      },
    },
    scales: {
      y: {
        beginAtZero: true,
      }
    }
  };

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <h1 className="text-3xl font-bold">Contractor Performance</h1>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          {[1, 2, 3, 4].map((i) => (
            <Card key={i} className="animate-pulse">
              <CardHeader className="pb-2">
                <div className="h-4 bg-gray-200 rounded w-3/4"></div>
              </CardHeader>
              <CardContent>
                <div className="h-8 bg-gray-200 rounded w-1/2"></div>
              </CardContent>
            </Card>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Contractor Performance</h1>
          <p className="text-muted-foreground mt-1">
            Track revenue, metrics, and leaderboard rankings
          </p>
        </div>
        <div className="flex flex-wrap items-center gap-3">
          <Select value={period} onValueChange={(value: any) => setPeriod(value)}>
            <SelectTrigger className="w-[140px]">
              <SelectValue placeholder="Period" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="monthly">Monthly</SelectItem>
              <SelectItem value="quarterly">Quarterly</SelectItem>
              <SelectItem value="yearly">Yearly</SelectItem>
            </SelectContent>
          </Select>
          <Select value={timeRange} onValueChange={(value: any) => setTimeRange(value)}>
            <SelectTrigger className="w-[140px]">
              <SelectValue placeholder="Time Range" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="6">Last 6 periods</SelectItem>
              <SelectItem value="12">Last 12 periods</SelectItem>
              <SelectItem value="24">Last 24 periods</SelectItem>
            </SelectContent>
          </Select>
          <Button onClick={handleExport} variant="outline" size="sm">
            <Download className="h-4 w-4 mr-2" />
            Export
          </Button>
        </div>
      </div>

      {/* Stats Cards */}
      {stats && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                Total Revenue
              </CardTitle>
              <DollarSign className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                ${stats.totalRevenue.toLocaleString()}
              </div>
              <p className="text-xs text-muted-foreground flex items-center mt-1">
                {stats.revenueChange >= 0 ? (
                  <>
                    <TrendingUp className="h-3 w-3 text-green-600 mr-1" />
                    <span className="text-green-600">+{stats.revenueChange.toFixed(1)}%</span>
                  </>
                ) : (
                  <>
                    <TrendingDown className="h-3 w-3 text-red-600 mr-1" />
                    <span className="text-red-600">{stats.revenueChange.toFixed(1)}%</span>
                  </>
                )}
                <span className="ml-1">from last period</span>
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                Contracts Won
              </CardTitle>
              <CheckCircle className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.totalContracts}</div>
              <p className="text-xs text-muted-foreground flex items-center mt-1">
                {stats.contractsChange >= 0 ? (
                  <>
                    <TrendingUp className="h-3 w-3 text-green-600 mr-1" />
                    <span className="text-green-600">+{stats.contractsChange.toFixed(1)}%</span>
                  </>
                ) : (
                  <>
                    <TrendingDown className="h-3 w-3 text-red-600 mr-1" />
                    <span className="text-red-600">{stats.contractsChange.toFixed(1)}%</span>
                  </>
                )}
                <span className="ml-1">from last period</span>
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                Average Rating
              </CardTitle>
              <Star className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.averageRating.toFixed(2)}</div>
              <p className="text-xs text-muted-foreground flex items-center mt-1">
                {stats.ratingChange >= 0 ? (
                  <>
                    <TrendingUp className="h-3 w-3 text-green-600 mr-1" />
                    <span className="text-green-600">+{stats.ratingChange.toFixed(2)}</span>
                  </>
                ) : (
                  <>
                    <TrendingDown className="h-3 w-3 text-red-600 mr-1" />
                    <span className="text-red-600">{stats.ratingChange.toFixed(2)}</span>
                  </>
                )}
                <span className="ml-1">from last period</span>
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                Completion Rate
              </CardTitle>
              <Target className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.completionRate.toFixed(1)}%</div>
              <p className="text-xs text-muted-foreground flex items-center mt-1">
                {stats.completionChange >= 0 ? (
                  <>
                    <TrendingUp className="h-3 w-3 text-green-600 mr-1" />
                    <span className="text-green-600">+{stats.completionChange.toFixed(1)}%</span>
                  </>
                ) : (
                  <>
                    <TrendingDown className="h-3 w-3 text-red-600 mr-1" />
                    <span className="text-red-600">{stats.completionChange.toFixed(1)}%</span>
                  </>
                )}
                <span className="ml-1">from last period</span>
              </p>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Main Content Tabs */}
      <Tabs value={selectedView} onValueChange={(value: any) => setSelectedView(value)} className="space-y-4">
        <TabsList>
          <TabsTrigger value="overview">
            <BarChart3 className="h-4 w-4 mr-2" />
            Overview
          </TabsTrigger>
          <TabsTrigger value="revenue">
            <DollarSign className="h-4 w-4 mr-2" />
            Revenue Tracking
          </TabsTrigger>
          <TabsTrigger value="leaderboard">
            <Trophy className="h-4 w-4 mr-2" />
            Leaderboard
          </TabsTrigger>
        </TabsList>

        {/* Overview Tab */}
        <TabsContent value="overview" className="space-y-6">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <Card>
              <CardHeader>
                <CardTitle>Revenue Trend</CardTitle>
                <CardDescription>
                  Revenue performance over {timeRange} {period} periods
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="h-[300px]">
                  <Line data={prepareRevenueChartData()} options={chartOptions} />
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Contracts & Quotes</CardTitle>
                <CardDescription>
                  Comparison of quotes submitted vs contracts won
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="h-[300px]">
                  <Bar data={prepareContractsChartData()} options={chartOptions} />
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Recent Performance */}
          <Card>
            <CardHeader>
              <CardTitle>Recent Performance Metrics</CardTitle>
              <CardDescription>
                Detailed breakdown of contractor performance
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="border-b">
                      <th className="text-left py-3 px-4 font-medium">Period</th>
                      <th className="text-left py-3 px-4 font-medium">Contractor</th>
                      <th className="text-right py-3 px-4 font-medium">Leads</th>
                      <th className="text-right py-3 px-4 font-medium">Quotes</th>
                      <th className="text-right py-3 px-4 font-medium">Contracts</th>
                      <th className="text-right py-3 px-4 font-medium">Revenue</th>
                      <th className="text-right py-3 px-4 font-medium">Rating</th>
                      <th className="text-right py-3 px-4 font-medium">Completion</th>
                    </tr>
                  </thead>
                  <tbody>
                    {metrics.slice(0, 10).map((metric) => (
                      <tr key={metric.id} className="border-b hover:bg-muted/50">
                        <td className="py-3 px-4">{metric.period}</td>
                        <td className="py-3 px-4">
                          <div>
                            <div className="font-medium">{metric.partner.companyName}</div>
                            <div className="text-sm text-muted-foreground">{metric.user.name || metric.user.email}</div>
                          </div>
                        </td>
                        <td className="text-right py-3 px-4">{metric.leadsAssigned}</td>
                        <td className="text-right py-3 px-4">{metric.quotesSubmitted}</td>
                        <td className="text-right py-3 px-4">{metric.contractsWon}</td>
                        <td className="text-right py-3 px-4 font-medium">
                          ${metric.revenue.toLocaleString()}
                        </td>
                        <td className="text-right py-3 px-4">
                          <div className="flex items-center justify-end gap-1">
                            <Star className="h-4 w-4 fill-yellow-400 text-yellow-400" />
                            {metric.averageRating.toFixed(1)}
                          </div>
                        </td>
                        <td className="text-right py-3 px-4">
                          <Badge variant={metric.completionRate >= 90 ? "default" : "secondary"}>
                            {metric.completionRate.toFixed(1)}%
                          </Badge>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Revenue Tracking Tab */}
        <TabsContent value="revenue" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Revenue Analysis</CardTitle>
              <CardDescription>
                Comprehensive revenue tracking and analysis
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="h-[400px]">
                <Line data={prepareRevenueChartData()} options={{
                  ...chartOptions,
                  plugins: {
                    ...chartOptions.plugins,
                    tooltip: {
                      callbacks: {
                        label: function(context: any) {
                          return `Revenue: $${context.parsed.y.toLocaleString()}`;
                        }
                      }
                    }
                  }
                }} />
              </div>
            </CardContent>
          </Card>

          {/* Revenue Leaderboard */}
          <Card>
            <CardHeader>
              <CardTitle>Top Revenue Generators</CardTitle>
              <CardDescription>
                Contractors ranked by total revenue in selected period
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {leaderboard
                  .sort((a, b) => b.revenue - a.revenue)
                  .slice(0, 10)
                  .map((entry, index) => (
                    <div key={entry.userId} className="flex items-center gap-4 p-4 rounded-lg border bg-card hover:bg-muted/50 transition-colors">
                      <div className="flex items-center justify-center w-10 h-10 rounded-full bg-primary/10 font-bold text-primary">
                        {index + 1}
                      </div>
                      <div className="flex-1">
                        <div className="font-semibold">{entry.partnerName}</div>
                        <div className="text-sm text-muted-foreground">{entry.companyName}</div>
                      </div>
                      <div className="text-right">
                        <div className="text-lg font-bold">${entry.revenue.toLocaleString()}</div>
                        <div className="text-sm text-muted-foreground">
                          {entry.contractsWon} contracts
                        </div>
                      </div>
                      {entry.trend !== 'stable' && (
                        <div className="flex items-center gap-1">
                          {entry.trend === 'up' ? (
                            <TrendingUp className="h-4 w-4 text-green-600" />
                          ) : (
                            <TrendingDown className="h-4 w-4 text-red-600" />
                          )}
                          <span className={entry.trend === 'up' ? 'text-green-600' : 'text-red-600'}>
                            {Math.abs(entry.change).toFixed(0)}%
                          </span>
                        </div>
                      )}
                    </div>
                  ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Leaderboard Tab */}
        <TabsContent value="leaderboard" className="space-y-6">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Overall Leaderboard */}
            <Card>
              <CardHeader>
                <CardTitle>
                  <Trophy className="h-5 w-5 inline mr-2 text-yellow-500" />
                  Overall Rankings
                </CardTitle>
                <CardDescription>
                  Based on revenue, contracts, and ratings
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {leaderboard.slice(0, 10).map((entry) => (
                    <div 
                      key={entry.userId}
                      className={`flex items-center gap-3 p-3 rounded-lg border ${
                        entry.rank <= 3 
                          ? 'bg-gradient-to-r from-yellow-50 to-transparent border-yellow-200' 
                          : 'bg-card'
                      }`}
                    >
                      <div className={`flex items-center justify-center w-8 h-8 rounded-full font-bold ${
                        entry.rank === 1 ? 'bg-yellow-500 text-white' :
                        entry.rank === 2 ? 'bg-gray-400 text-white' :
                        entry.rank === 3 ? 'bg-amber-600 text-white' :
                        'bg-muted text-muted-foreground'
                      }`}>
                        {entry.rank}
                      </div>
                      <div className="flex-1">
                        <div className="font-medium">{entry.partnerName}</div>
                        <div className="text-xs text-muted-foreground flex items-center gap-2">
                          <span>${entry.revenue.toLocaleString()}</span>
                          <span>•</span>
                          <span>{entry.contractsWon} contracts</span>
                          <span>•</span>
                          <span className="flex items-center gap-0.5">
                            <Star className="h-3 w-3 fill-yellow-400 text-yellow-400" />
                            {entry.averageRating.toFixed(1)}
                          </span>
                        </div>
                      </div>
                      {entry.trend !== 'stable' && (
                        <div className="text-right">
                          {entry.trend === 'up' ? (
                            <TrendingUp className="h-4 w-4 text-green-600 inline" />
                          ) : (
                            <TrendingDown className="h-4 w-4 text-red-600 inline" />
                          )}
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>

            {/* Top Performers by Category */}
            <div className="space-y-6">
              {/* Highest Rated */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Star className="h-5 w-5 text-yellow-500" />
                    Highest Rated
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    {leaderboard
                      .sort((a, b) => b.averageRating - a.averageRating)
                      .slice(0, 5)
                      .map((entry, index) => (
                        <div key={entry.userId} className="flex items-center justify-between">
                          <div>
                            <div className="font-medium">{entry.partnerName}</div>
                            <div className="text-sm text-muted-foreground">{entry.companyName}</div>
                          </div>
                          <div className="flex items-center gap-1">
                            <Star className="h-4 w-4 fill-yellow-400 text-yellow-400" />
                            <span className="font-bold">{entry.averageRating.toFixed(2)}</span>
                          </div>
                        </div>
                      ))}
                  </div>
                </CardContent>
              </Card>

              {/* Best Completion Rate */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Target className="h-5 w-5 text-green-600" />
                    Best Completion Rate
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    {leaderboard
                      .sort((a, b) => b.completionRate - a.completionRate)
                      .slice(0, 5)
                      .map((entry, index) => (
                        <div key={entry.userId} className="flex items-center justify-between">
                          <div>
                            <div className="font-medium">{entry.partnerName}</div>
                            <div className="text-sm text-muted-foreground">{entry.companyName}</div>
                          </div>
                          <Badge variant="default">
                            {entry.completionRate.toFixed(1)}%
                          </Badge>
                        </div>
                      ))}
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}
