
import React, { useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Building2,
  Award,
  Shield,
  FileText,
  DollarSign,
  TrendingUp,
  Users,
  MapPin,
  Mail,
  Phone,
  Edit,
  Download,
  CheckCircle2,
  AlertCircle,
  Clock,
  Target,
  Upload,
  ArrowLeft // Added for viewer components
} from "lucide-react";

// COI Viewer Component
const COIViewer = ({ vendor, onClose }) => (
  <Card className="border-slate-200">
    <CardHeader className="bg-gradient-to-br from-blue-50 to-white border-b border-slate-100 flex-row items-center justify-between py-4 px-6">
      <div className="flex items-center gap-3">
        <Button variant="ghost" size="icon" onClick={onClose} className="rounded-full">
          <ArrowLeft className="w-5 h-5 text-slate-600" />
        </Button>
        <CardTitle className="text-base text-[#1C323E]">
          Certificate of Insurance for {vendor.name}
        </CardTitle>
      </div>
      <Button variant="outline" size="sm">
        <Download className="w-4 h-4 mr-2" />
        Download COI
      </Button>
    </CardHeader>
    <CardContent className="p-6 h-[500px] overflow-y-auto">
      {/* Mock PDF Viewer / Content */}
      <div className="flex flex-col items-center justify-center h-full bg-gray-100 rounded-lg p-4 text-gray-500 border border-gray-200">
        <FileText className="w-16 h-16 mb-4" />
        <p className="text-lg font-semibold mb-2">COI Document Preview</p>
        <p className="text-sm text-center">This is a placeholder for the Certificate of Insurance document viewer. In a real application, an embedded PDF viewer or a document image would be displayed here.</p>
        <p className="text-xs mt-4">Vendor Name: <span className="font-medium text-slate-700">{vendor.name}</span></p>
        <p className="text-xs">Policy Number: <span className="font-medium text-slate-700">ABC-123456789</span></p>
        <p className="text-xs">Expiration Date: <span className="font-medium text-slate-700">11/20/2025</span></p>
        <div className="mt-6 w-full max-w-lg h-[300px] bg-white border border-gray-300 flex items-center justify-center text-gray-400 text-sm rounded-md shadow-sm">
          [PDF Viewer Embed / Document Image Placeholder]
        </div>
      </div>
    </CardContent>
  </Card>
);

// W9 Form Viewer Component
const W9FormViewer = ({ vendor, onClose }) => (
  <Card className="border-slate-200">
    <CardHeader className="bg-gradient-to-br from-blue-50 to-white border-b border-slate-100 flex-row items-center justify-between py-4 px-6">
      <div className="flex items-center gap-3">
        <Button variant="ghost" size="icon" onClick={onClose} className="rounded-full">
          <ArrowLeft className="w-5 h-5 text-slate-600" />
        </Button>
        <CardTitle className="text-base text-[#1C323E]">
          W-9 Form for {vendor.name}
        </CardTitle>
      </div>
      <Button variant="outline" size="sm">
        <Download className="w-4 h-4 mr-2" />
        Download W-9
      </Button>
    </CardHeader>
    <CardContent className="p-6 h-[500px] overflow-y-auto">
      {/* Mock PDF Viewer / Content */}
      <div className="flex flex-col items-center justify-center h-full bg-gray-100 rounded-lg p-4 text-gray-500 border border-gray-200">
        <FileText className="w-16 h-16 mb-4" />
        <p className="text-lg font-semibold mb-2">W-9 Form Document Preview</p>
        <p className="text-sm text-center">This is a placeholder for the W-9 Form document viewer. In a real application, an embedded PDF viewer or a document image would be displayed here.</p>
        <p className="text-xs mt-4">Vendor Name: <span className="font-medium text-slate-700">{vendor.name}</span></p>
        <p className="text-xs">Tax ID: <span className="font-medium text-slate-700">XX-XXXXXXX</span></p>
        <p className="text-xs">Last Updated: <span className="font-medium text-slate-700">07/23/2025</span></p>
        <div className="mt-6 w-full max-w-lg h-[300px] bg-white border border-gray-300 flex items-center justify-center text-gray-400 text-sm rounded-md shadow-sm">
          [PDF Viewer Embed / Document Image Placeholder]
        </div>
      </div>
    </CardContent>
  </Card>
);

export default function VendorDetailModal({ vendor, open, onClose, onEdit }) {
  const [activeTab, setActiveTab] = useState("overview");
  const [showCOI, setShowCOI] = useState(false);
  const [showW9, setShowW9] = useState(false);

  if (!vendor) return null;

  // Mock compliance data - would come from backend
  const complianceData = {
    overall: vendor.name === "Legendary Event Staffing" ? 98 : 95,
    coi: { status: "valid", expires: "11/20/2025" },
    w9: { status: "valid", lastUpdated: "07/23/2025" },
    backgroundChecks: { status: "valid", percentage: 100 },
    insurance: { status: vendor.name === "Legendary Event Staffing" ? "valid" : "expiring", expires: "03/30/2025" }
  };

  const performanceData = {
    overallScore: vendor.name === "Legendary Event Staffing" ? "A+" : vendor.name === "Instawork" ? "A" : "B+",
    fillRate: vendor.fillRate,
    onTimeRate: vendor.onTimeRate,
    billingAccuracy: vendor.name === "Legendary Event Staffing" ? 99.5 : 96,
    clientSatisfaction: vendor.csat,
    reliability: vendor.name === "Legendary Event Staffing" ? 98 : 91,
    avgHourlyRate: vendor.name === "Legendary Event Staffing" ? 23.50 : vendor.name === "Instawork" ? 22.00 : 21.00,
    vendorFeePercentage: vendor.name === "Legendary Event Staffing" ? 19.6 : vendor.name === "Instawork" ? 20.5 : 22.0,
    employeeWage: vendor.name === "Legendary Event Staffing" ? 18.50 : 17.00,
    totalEmployees: vendor.employees,
    monthlySpend: vendor.spend
  };

  const documents = [
    { name: "COI (Certificate of Insurance)", status: complianceData.coi.status, lastUpdated: "2 days ago", type: "coi" },
    { name: "W9 Forms", status: complianceData.w9.status, lastUpdated: "2 days ago", type: "w9" },
    { name: "Contracts", status: "active", lastUpdated: "2 days ago", type: "contract" },
    { name: "ESG Certification", status: "valid", lastUpdated: "2 days ago", type: "esg" },
    { name: "Policies", status: "updated", lastUpdated: "2 days ago", type: "policy" },
    { name: "Forms & Templates", status: "available", lastUpdated: "2 days ago", type: "forms" }
  ];

  const getScoreColor = (score) => {
    if (score >= 97) return "text-green-600";
    if (score >= 90) return "text-blue-600";
    if (score >= 80) return "text-yellow-600";
    return "text-red-600";
  };

  const getStatusBadge = (status) => {
    const colors = {
      valid: "bg-green-100 text-green-700",
      active: "bg-blue-100 text-blue-700",
      updated: "bg-blue-100 text-blue-700",
      available: "bg-slate-100 text-slate-700",
      expiring: "bg-yellow-100 text-yellow-700",
      expired: "bg-red-100 text-red-700"
    };
    return colors[status] || "bg-gray-100 text-gray-700";
  };

  const getScoreBadgeColor = (score) => {
    if (score >= 95) return "bg-green-100 text-green-700 border-green-200";
    if (score >= 90) return "bg-blue-100 text-blue-700 border-blue-200";
    if (score >= 85) return "bg-amber-100 text-amber-700 border-amber-200";
    return "bg-red-100 text-red-700 border-red-200";
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-6xl max-h-[90vh] overflow-hidden p-0">
        <DialogHeader className="p-0">
          <div className="flex items-start justify-between px-6 pt-6">
            <div className="flex items-center gap-4">
              <div className="w-16 h-16 bg-gradient-to-br from-[#0A39DF] to-[#1C323E] rounded-xl flex items-center justify-center">
                <Building2 className="w-8 h-8 text-white" />
              </div>
              <div>
                <DialogTitle className="text-2xl">{vendor.name}</DialogTitle>
                <div className="flex items-center gap-3 mt-2">
                  <Badge className="bg-blue-100 text-blue-700">
                    {vendor.region}
                  </Badge>
                  <Badge variant="outline">{vendor.specialty}</Badge>
                  {vendor.softwareType === "platform" && (
                    <Badge className="bg-green-100 text-green-700">✅ Full Platform</Badge>
                  )}
                  {vendor.softwareType === "building" && (
                    <Badge className="bg-blue-100 text-blue-700">⚙️ Building Platform</Badge>
                  )}
                </div>
              </div>
            </div>
            <Button variant="outline" onClick={() => onEdit(vendor)}>
              <Edit className="w-4 h-4 mr-2" />
              Edit
            </Button>
          </div>
        </DialogHeader>

        {/* Tabs Navigation */}
        <div className="border-b border-slate-200 bg-white px-6">
          <div className="flex gap-1">
            <button
              onClick={() => { setActiveTab("overview"); setShowCOI(false); setShowW9(false); }}
              className={`px-4 py-3 text-sm font-medium transition-all ${
                activeTab === "overview"
                  ? "text-[#0A39DF] border-b-2 border-[#0A39DF] bg-blue-50"
                  : "text-slate-600 hover:text-slate-900 hover:bg-slate-50"
              }`}
            >
              Overview
            </button>
            <button
              onClick={() => { setActiveTab("compliance"); setShowCOI(false); setShowW9(false); }}
              className={`px-4 py-3 text-sm font-medium transition-all ${
                activeTab === "compliance"
                  ? "text-[#0A39DF] border-b-2 border-[#0A39DF] bg-blue-50"
                  : "text-slate-600 hover:text-slate-900 hover:bg-slate-50"
              }`}
            >
              Compliance
            </button>
            <button
              onClick={() => { setActiveTab("performance"); setShowCOI(false); setShowW9(false); }}
              className={`px-4 py-3 text-sm font-medium transition-all ${
                activeTab === "performance"
                  ? "text-[#0A39DF] border-b-2 border-[#0A39DF] bg-blue-50"
                  : "text-slate-600 hover:text-slate-900 hover:bg-slate-50"
              }`}
            >
              Performance
            </button>
            <button
              onClick={() => { setActiveTab("documents"); setShowCOI(false); setShowW9(false); }}
              className={`px-4 py-3 text-sm font-medium transition-all ${
                activeTab === "documents"
                  ? "text-[#0A39DF] border-b-2 border-[#0A39DF] bg-blue-50"
                  : "text-slate-600 hover:text-slate-900 hover:bg-slate-50"
              }`}
            >
              Documents
            </button>
          </div>
        </div>

        {/* Tab Content */}
        <div className="overflow-y-auto max-h-[calc(90vh-180px)] bg-slate-50 p-6">
          {/* Key Metrics Overview */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
            <Card className="border-slate-200">
              <CardContent className="p-4">
                <div className="flex items-center justify-between mb-2">
                  <Award className="w-5 h-5 text-amber-600" />
                  <span className={`text-2xl font-bold ${performanceData.overallScore === 'A+' ? 'text-green-600' : 'text-blue-600'}`}>
                    {performanceData.overallScore}
                  </span>
                </div>
                <p className="text-xs text-slate-600 font-medium">Overall Score</p>
              </CardContent>
            </Card>

            <Card className="border-slate-200">
              <CardContent className="p-4">
                <div className="flex items-center justify-between mb-2">
                  <Shield className="w-5 h-5 text-green-600" />
                  <span className={`text-2xl font-bold ${getScoreColor(complianceData.overall)}`}>
                    {complianceData.overall}%
                  </span>
                </div>
                <p className="text-xs text-slate-600 font-medium">Compliance</p>
              </CardContent>
            </Card>

            <Card className="border-slate-200">
              <CardContent className="p-4">
                <div className="flex items-center justify-between mb-2">
                  <DollarSign className="w-5 h-5 text-blue-600" />
                  <span className={`text-2xl font-bold ${getScoreColor(performanceData.billingAccuracy)}`}>
                    {performanceData.billingAccuracy}%
                  </span>
                </div>
                <p className="text-xs text-slate-600 font-medium">Billing Accuracy</p>
              </CardContent>
            </Card>

            <Card className="border-slate-200">
              <CardContent className="p-4">
                <div className="flex items-center justify-between mb-2">
                  <TrendingUp className="w-5 h-5 text-emerald-600" />
                  <span className={`text-2xl font-bold ${getScoreColor(performanceData.fillRate)}`}>
                    {performanceData.fillRate}%
                  </span>
                </div>
                <p className="text-xs text-slate-600 font-medium">Fill Rate</p>
              </CardContent>
            </Card>
          </div>

          {/* Overview Tab Content */}
          {activeTab === "overview" && (
            <div className="space-y-4">
              <Card className="border-slate-200">
                <CardHeader>
                  <CardTitle className="text-base">Company Information</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <p className="text-xs text-slate-500 mb-1">Total Staff</p>
                      <div className="flex items-center gap-2">
                        <Users className="w-4 h-4 text-slate-400" />
                        <span className="font-semibold">{vendor.employees.toLocaleString()}</span>
                      </div>
                    </div>
                    <div>
                      <p className="text-xs text-slate-500 mb-1">Region</p>
                      <div className="flex items-center gap-2">
                        <MapPin className="w-4 h-4 text-slate-400" />
                        <span className="font-semibold">{vendor.region}, {vendor.state}</span>
                      </div>
                    </div>
                    <div>
                      <p className="text-xs text-slate-500 mb-1">Email</p>
                      <div className="flex items-center gap-2">
                        <Mail className="w-4 h-4 text-slate-400" />
                        <span className="font-semibold text-sm">contact@{vendor.name.toLowerCase().replace(/\s+/g, '')}.com</span>
                      </div>
                    </div>
                    <div>
                      <p className="text-xs text-slate-500 mb-1">Phone</p>
                      <div className="flex items-center gap-2">
                        <Phone className="w-4 h-4 text-slate-400" />
                        <span className="font-semibold">(555) 123-4567</span>
                      </div>
                    </div>
                  </div>

                  <div className="pt-4 border-t border-slate-200">
                    <p className="text-xs text-slate-500 mb-2">Technology Stack</p>
                    <div className="flex items-center gap-2">
                      {vendor.softwareType === "platform" && (
                        <Badge className="bg-green-100 text-green-700">
                          ✅ {vendor.software}
                        </Badge>
                      )}
                      {vendor.softwareType === "building" && (
                        <Badge className="bg-blue-100 text-blue-700">
                          ⚙️ {vendor.software}
                        </Badge>
                      )}
                      {vendor.softwareType === "partial" && (
                        <Badge className="bg-yellow-100 text-yellow-700">
                          ⚙️ {vendor.software}
                        </Badge>
                      )}
                      {vendor.softwareType === "traditional" && (
                        <Badge className="bg-gray-100 text-gray-700">
                          ❌ {vendor.software}
                        </Badge>
                      )}
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>
          )}

          {/* Compliance Tab Content */}
          {activeTab === "compliance" && (
            <div className="space-y-4">
              <Card className="border-slate-200">
                <CardHeader className="bg-gradient-to-br from-green-50 to-white border-b border-slate-100">
                  <div className="flex items-center justify-between">
                    <CardTitle className="text-base flex items-center gap-2">
                      <Shield className="w-5 h-5 text-green-600" />
                      Compliance Status
                    </CardTitle>
                    <Badge className="bg-green-100 text-green-700 text-lg px-4 py-1">
                      {complianceData.overall}%
                    </Badge>
                  </div>
                </CardHeader>
                <CardContent className="p-6">
                  <div className="grid grid-cols-2 gap-4">
                    <div className="p-4 bg-green-50 rounded-lg border border-green-200">
                      <div className="flex items-center justify-between mb-2">
                        <p className="text-sm font-semibold text-slate-900">COI</p>
                        <Badge className={getStatusBadge(complianceData.coi.status)}>
                          {complianceData.coi.status}
                        </Badge>
                      </div>
                      <p className="text-xs text-slate-600">Expires: {complianceData.coi.expires}</p>
                    </div>

                    <div className="p-4 bg-green-50 rounded-lg border border-green-200">
                      <div className="flex items-center justify-between mb-2">
                        <p className="text-sm font-semibold text-slate-900">W-9 Form</p>
                        <Badge className={getStatusBadge(complianceData.w9.status)}>
                          {complianceData.w9.status}
                        </Badge>
                      </div>
                      <p className="text-xs text-slate-600">Updated: {complianceData.w9.lastUpdated}</p>
                    </div>

                    <div className="p-4 bg-green-50 rounded-lg border border-green-200">
                      <div className="flex items-center justify-between mb-2">
                        <p className="text-sm font-semibold text-slate-900">Background Checks</p>
                        <Badge className="bg-green-100 text-green-700">
                          {complianceData.backgroundChecks.percentage}%
                        </Badge>
                      </div>
                      <p className="text-xs text-slate-600">All staff verified</p>
                    </div>

                    <div className="p-4 bg-green-50 rounded-lg border border-green-200">
                      <div className="flex items-center justify-between mb-2">
                        <p className="text-sm font-semibold text-slate-900">Insurance</p>
                        <Badge className={getStatusBadge(complianceData.insurance.status)}>
                          {complianceData.insurance.status}
                        </Badge>
                      </div>
                      <p className="text-xs text-slate-600">Expires: {complianceData.insurance.expires}</p>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>
          )}

          {/* Performance Tab Content */}
          {activeTab === "performance" && (
            <div className="space-y-6">
              {/* Company Size & Financial Overview */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <Card className="border-slate-200 bg-gradient-to-br from-blue-50 to-white">
                  <CardContent className="p-6">
                    <div className="flex items-center gap-3 mb-3">
                      <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                        <Users className="w-6 h-6 text-blue-600" />
                      </div>
                      <div>
                        <p className="text-xs text-slate-500">Total Employees</p>
                        <p className="text-2xl font-bold text-[#1C323E]">{performanceData.totalEmployees.toLocaleString()}</p>
                      </div>
                    </div>
                    <p className="text-xs text-slate-600">Available workforce</p>
                  </CardContent>
                </Card>

                <Card className="border-slate-200 bg-gradient-to-br from-emerald-50 to-white">
                  <CardContent className="p-6">
                    <div className="flex items-center gap-3 mb-3">
                      <div className="w-12 h-12 bg-emerald-100 rounded-lg flex items-center justify-center">
                        <DollarSign className="w-6 h-6 text-emerald-600" />
                      </div>
                      <div>
                        <p className="text-xs text-slate-500">Monthly Spend</p>
                        <p className="text-2xl font-bold text-[#1C323E]">{performanceData.monthlySpend}</p>
                      </div>
                    </div>
                    <p className="text-xs text-slate-600">Average monthly cost</p>
                  </CardContent>
                </Card>

                <Card className="border-slate-200 bg-gradient-to-br from-purple-50 to-white">
                  <CardContent className="p-6">
                    <div className="flex items-center gap-3 mb-3">
                      <div className="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                        <Award className="w-6 h-6 text-purple-600" />
                      </div>
                      <div>
                        <p className="text-xs text-slate-500">Performance Grade</p>
                        <p className="text-2xl font-bold text-[#1C323E]">{performanceData.overallScore}</p>
                      </div>
                    </div>
                    <p className="text-xs text-slate-600">Overall rating</p>
                  </CardContent>
                </Card>
              </div>

              {/* Rates & Fees Breakdown */}
              <Card className="border-slate-200">
                <CardHeader className="bg-gradient-to-br from-slate-50 to-white border-b border-slate-100">
                  <CardTitle className="text-base flex items-center gap-2">
                    <DollarSign className="w-5 h-5 text-[#0A39DF]" />
                    Rates & Fee Structure
                  </CardTitle>
                </CardHeader>
                <CardContent className="p-6">
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <div className="p-5 bg-slate-50 rounded-xl border border-slate-200">
                      <p className="text-xs text-slate-500 mb-2">Average Hourly Rate</p>
                      <div className="flex items-baseline gap-2">
                        <p className="text-3xl font-bold text-[#0A39DF]">${performanceData.avgHourlyRate.toFixed(2)}</p>
                        <p className="text-sm text-slate-600">/hr</p>
                      </div>
                      <p className="text-xs text-slate-600 mt-2">Client billing rate</p>
                    </div>

                    <div className="p-5 bg-slate-50 rounded-xl border border-slate-200">
                      <p className="text-xs text-slate-500 mb-2">Employee Wage</p>
                      <div className="flex items-baseline gap-2">
                        <p className="text-3xl font-bold text-emerald-600">${performanceData.employeeWage.toFixed(2)}</p>
                        <p className="text-sm text-slate-600">/hr</p>
                      </div>
                      <p className="text-xs text-slate-600 mt-2">Worker take-home rate</p>
                    </div>

                    <div className="p-5 bg-slate-50 rounded-xl border border-slate-200">
                      <p className="text-xs text-slate-500 mb-2">Vendor Fee</p>
                      <div className="flex items-baseline gap-2">
                        <p className="text-3xl font-bold text-purple-600">{performanceData.vendorFeePercentage}%</p>
                      </div>
                      <p className="text-xs text-slate-600 mt-2">${(performanceData.avgHourlyRate - performanceData.employeeWage).toFixed(2)}/hr markup</p>
                    </div>
                  </div>

                  {/* Visual breakdown */}
                  <div className="mt-6 p-4 bg-blue-50 rounded-lg border border-blue-200">
                    <p className="text-sm font-semibold text-[#1C323E] mb-3">Cost Breakdown</p>
                    <div className="flex items-center gap-2 mb-2">
                      <div className="flex-1 bg-slate-200 rounded-full h-8 overflow-hidden flex">
                        <div 
                          className="bg-emerald-500 flex items-center justify-center text-xs font-semibold text-white"
                          style={{ width: `${(performanceData.employeeWage / performanceData.avgHourlyRate) * 100}%` }}
                        >
                          ${performanceData.employeeWage}
                        </div>
                        <div 
                          className="bg-purple-500 flex items-center justify-center text-xs font-semibold text-white"
                          style={{ width: `${((performanceData.avgHourlyRate - performanceData.employeeWage) / performanceData.avgHourlyRate) * 100}%` }}
                        >
                          ${(performanceData.avgHourlyRate - performanceData.employeeWage).toFixed(2)}
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center justify-between text-xs text-slate-600">
                      <div className="flex items-center gap-2">
                        <div className="w-3 h-3 bg-emerald-500 rounded"></div>
                        <span>Employee Wage ({((performanceData.employeeWage / performanceData.avgHourlyRate) * 100).toFixed(1)}%)</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <div className="w-3 h-3 bg-purple-500 rounded"></div>
                        <span>Vendor Fee ({performanceData.vendorFeePercentage}%)</span>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* Performance Metrics Grid */}
              <Card className="border-slate-200">
                <CardHeader className="bg-gradient-to-br from-slate-50 to-white border-b border-slate-100">
                  <CardTitle className="text-base flex items-center gap-2">
                    <TrendingUp className="w-5 h-5 text-[#0A39DF]" />
                    Key Performance Indicators
                  </CardTitle>
                </CardHeader>
                <CardContent className="p-6">
                  <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                    {[
                      { label: "Fill Rate", value: performanceData.fillRate, icon: Target },
                      { label: "On-Time Rate", value: performanceData.onTimeRate, icon: Clock },
                      { label: "Billing Accuracy", value: performanceData.billingAccuracy, icon: DollarSign },
                      { label: "Client Satisfaction", value: (performanceData.clientSatisfaction * 20).toFixed(0), icon: Award, suffix: "", display: `${performanceData.clientSatisfaction}/5.0` },
                      { label: "Reliability Score", value: performanceData.reliability, icon: Shield },
                      { label: "Compliance", value: complianceData.overall, icon: CheckCircle2 },
                    ].map((metric, idx) => {
                      const Icon = metric.icon;
                      return (
                        <div key={idx} className="p-4 bg-slate-50 rounded-lg border border-slate-200">
                          <div className="flex items-center justify-between mb-3">
                            <Icon className="w-5 h-5 text-slate-400" />
                            <Badge className={getScoreBadgeColor(metric.value)}>
                              {metric.display || `${metric.value}${metric.suffix || '%'}`}
                            </Badge>
                          </div>
                          <p className="text-xs font-medium text-slate-700">{metric.label}</p>
                        </div>
                      );
                    })}
                  </div>
                </CardContent>
              </Card>
            </div>
          )}

          {/* Documents Tab Content */}
          {activeTab === "documents" && (
            <div className="space-y-4">
              {showCOI ? (
                <COIViewer vendor={vendor} onClose={() => setShowCOI(false)} />
              ) : showW9 ? (
                <W9FormViewer vendor={vendor} onClose={() => setShowW9(false)} />
              ) : (
                <Card className="border-slate-200">
                  <CardHeader>
                    <CardTitle className="text-base flex items-center gap-2">
                      <FileText className="w-5 h-5 text-[#0A39DF]" />
                      Document Center
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    {documents.map((doc, idx) => (
                      <div 
                        key={idx}
                        className="flex items-center justify-between p-4 border border-slate-200 rounded-lg hover:border-[#0A39DF] hover:shadow-md transition-all cursor-pointer"
                        onClick={() => {
                          if (doc.type === "coi") setShowCOI(true);
                          else if (doc.type === "w9") setShowW9(true);
                          // Add handlers for other document types as needed
                        }}
                      >
                        <div className="flex items-center gap-3">
                          <div className="w-12 h-12 bg-blue-50 rounded-lg flex items-center justify-center">
                            <FileText className="w-6 h-6 text-[#0A39DF]" />
                          </div>
                          <div>
                            <p className="font-semibold text-[#1C323E] text-sm">{doc.name}</p>
                            <p className="text-xs text-slate-500">Last updated: {doc.lastUpdated}</p>
                          </div>
                        </div>
                        <div className="flex items-center gap-3">
                          <Badge className={getStatusBadge(doc.status)}>
                            {doc.status}
                          </Badge>
                          <Button 
                            variant="ghost" 
                            size="icon" 
                            className="text-slate-600 hover:text-[#0A39DF]"
                            onClick={(e) => {
                              // Prevent the parent div's onClick from firing when download button is clicked
                              e.stopPropagation(); 
                              // Implement actual download logic here
                              console.log(`Downloading ${doc.name}`);
                            }}
                          >
                            <Download className="w-4 h-4" />
                          </Button>
                        </div>
                      </div>
                    ))}
                  </CardContent>
                </Card>
              )}
            </div>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}
