import React from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { 
  Package, Star, TrendingUp, TrendingDown, DollarSign,
  Users, CheckCircle, AlertTriangle, Award, Shield, Zap
} from "lucide-react";
import { ScatterChart, Scatter, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, ZAxis, Cell } from "recharts";

export default function VendorPerformanceMatrix({ vendors, assignments, rates, metrics, userRole }) {
  // Generate vendor performance data
  const vendorPerformance = vendors.slice(0, 8).map((vendor, idx) => ({
    id: vendor.id,
    name: vendor.legal_name || vendor.doing_business_as || `Vendor ${idx + 1}`,
    region: vendor.region || "Bay Area",
    avgRate: metrics.avgContractedRate - (Math.random() * 10 - 5),
    reliability: 80 + Math.random() * 18,
    fillRate: 85 + Math.random() * 14,
    noShowRate: Math.random() * 5,
    onTimeRate: 88 + Math.random() * 11,
    workforce: vendor.workforce_count || Math.floor(50 + Math.random() * 150),
    spend: Math.floor(10000 + Math.random() * 50000),
    score: Math.floor(70 + Math.random() * 28),
    tier: idx < 2 ? "Preferred" : idx < 5 ? "Approved" : "Standard",
    savingsPotential: Math.floor(1000 + Math.random() * 5000),
  }));

  // Scatter plot data
  const scatterData = vendorPerformance.map(v => ({
    x: v.avgRate,
    y: v.reliability,
    z: v.spend / 1000,
    name: v.name,
    tier: v.tier,
  }));

  const tierColors = {
    Preferred: "#22c55e",
    Approved: "#0A39DF",
    Standard: "#f59e0b",
  };

  const tierBadgeColors = {
    Preferred: "bg-green-100 text-green-700",
    Approved: "bg-blue-100 text-blue-700",
    Standard: "bg-amber-100 text-amber-700",
  };

  const slaMetrics = [
    { metric: "Response Time", target: "< 2 hours", achieved: "1.5 hours", status: "met" },
    { metric: "Fill Rate", target: "> 95%", achieved: `${metrics.fillRate.toFixed(1)}%`, status: metrics.fillRate > 95 ? "met" : "at-risk" },
    { metric: "No-Show Rate", target: "< 3%", achieved: `${metrics.noShowRate.toFixed(1)}%`, status: metrics.noShowRate < 3 ? "met" : "at-risk" },
    { metric: "On-Time Arrival", target: "> 98%", achieved: "97.2%", status: "at-risk" },
  ];

  return (
    <div className="space-y-6">
      {/* Vendor Scorecard Summary */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="bg-green-50 border-green-200">
          <CardContent className="p-5">
            <div className="flex items-center gap-3">
              <div className="w-12 h-12 bg-green-500 rounded-xl flex items-center justify-center">
                <Star className="w-6 h-6 text-white" />
              </div>
              <div>
                <p className="text-sm text-green-600 font-medium">Preferred Vendors</p>
                <p className="text-2xl font-bold text-green-900">{vendorPerformance.filter(v => v.tier === "Preferred").length}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="bg-blue-50 border-blue-200">
          <CardContent className="p-5">
            <div className="flex items-center gap-3">
              <div className="w-12 h-12 bg-blue-500 rounded-xl flex items-center justify-center">
                <Shield className="w-6 h-6 text-white" />
              </div>
              <div>
                <p className="text-sm text-blue-600 font-medium">Approved Vendors</p>
                <p className="text-2xl font-bold text-blue-900">{vendorPerformance.filter(v => v.tier === "Approved").length}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="bg-amber-50 border-amber-200">
          <CardContent className="p-5">
            <div className="flex items-center gap-3">
              <div className="w-12 h-12 bg-amber-500 rounded-xl flex items-center justify-center">
                <Package className="w-6 h-6 text-white" />
              </div>
              <div>
                <p className="text-sm text-amber-600 font-medium">Standard Vendors</p>
                <p className="text-2xl font-bold text-amber-900">{vendorPerformance.filter(v => v.tier === "Standard").length}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="bg-purple-50 border-purple-200">
          <CardContent className="p-5">
            <div className="flex items-center gap-3">
              <div className="w-12 h-12 bg-purple-500 rounded-xl flex items-center justify-center">
                <DollarSign className="w-6 h-6 text-white" />
              </div>
              <div>
                <p className="text-sm text-purple-600 font-medium">Total Savings Potential</p>
                <p className="text-2xl font-bold text-purple-900">
                  ${vendorPerformance.reduce((sum, v) => sum + v.savingsPotential, 0).toLocaleString()}
                </p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Rate vs Reliability Scatter */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <TrendingUp className="w-5 h-5 text-blue-500" />
            Vendor Performance Matrix (Rate vs. Reliability)
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="h-80">
            <ResponsiveContainer width="100%" height="100%">
              <ScatterChart margin={{ top: 20, right: 20, bottom: 20, left: 20 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                <XAxis 
                  type="number" 
                  dataKey="x" 
                  name="Rate" 
                  unit="$/hr"
                  stroke="#64748b"
                  fontSize={12}
                  label={{ value: 'Hourly Rate ($)', position: 'bottom', offset: 0 }}
                />
                <YAxis 
                  type="number" 
                  dataKey="y" 
                  name="Reliability" 
                  unit="%"
                  stroke="#64748b"
                  fontSize={12}
                  domain={[70, 100]}
                  label={{ value: 'Reliability (%)', angle: -90, position: 'left' }}
                />
                <ZAxis type="number" dataKey="z" range={[100, 500]} />
                <Tooltip 
                  cursor={{ strokeDasharray: '3 3' }}
                  content={({ payload }) => {
                    if (payload && payload[0]) {
                      const data = payload[0].payload;
                      return (
                        <div className="bg-white p-3 border border-slate-200 rounded-lg shadow-lg">
                          <p className="font-bold text-slate-900">{data.name}</p>
                          <p className="text-sm text-slate-600">Rate: ${data.x.toFixed(2)}/hr</p>
                          <p className="text-sm text-slate-600">Reliability: {data.y.toFixed(1)}%</p>
                          <Badge className={tierBadgeColors[data.tier]}>{data.tier}</Badge>
                        </div>
                      );
                    }
                    return null;
                  }}
                />
                <Scatter data={scatterData}>
                  {scatterData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={tierColors[entry.tier]} />
                  ))}
                </Scatter>
              </ScatterChart>
            </ResponsiveContainer>
          </div>
          <div className="flex justify-center gap-6 mt-4">
            {Object.entries(tierColors).map(([tier, color]) => (
              <div key={tier} className="flex items-center gap-2">
                <div className="w-4 h-4 rounded-full" style={{ backgroundColor: color }} />
                <span className="text-sm text-slate-600">{tier}</span>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Vendor Table */}
      <Card>
        <CardHeader>
          <CardTitle>Vendor Performance Details</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow className="bg-slate-50">
                  <TableHead>Vendor</TableHead>
                  <TableHead>Tier</TableHead>
                  <TableHead className="text-right">Avg Rate</TableHead>
                  <TableHead className="text-right">Reliability</TableHead>
                  <TableHead className="text-right">Fill Rate</TableHead>
                  <TableHead className="text-right">No-Show</TableHead>
                  <TableHead className="text-right">Score</TableHead>
                  <TableHead className="text-right">Savings Potential</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {vendorPerformance.map((vendor) => (
                  <TableRow key={vendor.id} className="hover:bg-slate-50">
                    <TableCell>
                      <div className="flex items-center gap-3">
                        <div className="w-8 h-8 bg-[#0A39DF] rounded-lg flex items-center justify-center">
                          <Package className="w-4 h-4 text-white" />
                        </div>
                        <div>
                          <p className="font-medium text-slate-900">{vendor.name}</p>
                          <p className="text-xs text-slate-500">{vendor.region}</p>
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge className={tierBadgeColors[vendor.tier]}>{vendor.tier}</Badge>
                    </TableCell>
                    <TableCell className="text-right font-medium">${vendor.avgRate.toFixed(2)}</TableCell>
                    <TableCell className="text-right">
                      <div className="flex items-center justify-end gap-2">
                        <Progress value={vendor.reliability} className="w-12 h-2" />
                        <span className="text-sm">{vendor.reliability.toFixed(0)}%</span>
                      </div>
                    </TableCell>
                    <TableCell className="text-right">{vendor.fillRate.toFixed(0)}%</TableCell>
                    <TableCell className="text-right">
                      <span className={vendor.noShowRate < 3 ? "text-green-600" : "text-red-600"}>
                        {vendor.noShowRate.toFixed(1)}%
                      </span>
                    </TableCell>
                    <TableCell className="text-right">
                      <Badge className={vendor.score >= 90 ? "bg-green-100 text-green-700" : vendor.score >= 75 ? "bg-blue-100 text-blue-700" : "bg-amber-100 text-amber-700"}>
                        {vendor.score}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-right font-semibold text-green-600">
                      ${vendor.savingsPotential.toLocaleString()}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      {/* SLA Tracking */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Award className="w-5 h-5 text-amber-500" />
            Service Level Agreement (SLA) Tracking
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            {slaMetrics.map((sla, idx) => (
              <div key={idx} className={`p-4 rounded-xl border-2 ${sla.status === "met" ? "bg-green-50 border-green-200" : "bg-amber-50 border-amber-200"}`}>
                <div className="flex items-center justify-between mb-2">
                  <span className="font-medium text-slate-700">{sla.metric}</span>
                  {sla.status === "met" ? (
                    <CheckCircle className="w-5 h-5 text-green-500" />
                  ) : (
                    <AlertTriangle className="w-5 h-5 text-amber-500" />
                  )}
                </div>
                <div className="space-y-1">
                  <div className="flex justify-between text-sm">
                    <span className="text-slate-500">Target</span>
                    <span className="font-medium">{sla.target}</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-slate-500">Achieved</span>
                    <span className={`font-bold ${sla.status === "met" ? "text-green-600" : "text-amber-600"}`}>
                      {sla.achieved}
                    </span>
                  </div>
                </div>
                <Badge className={`mt-2 ${sla.status === "met" ? "bg-green-100 text-green-700" : "bg-amber-100 text-amber-700"}`}>
                  {sla.status === "met" ? "SLA Met" : "At Risk"}
                </Badge>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}