import React, { useState, useMemo } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Progress } from "@/components/ui/progress";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { 
  ShieldCheck, Search, Plus, Clock, CheckCircle2, XCircle, AlertTriangle,
  Upload, Eye, Activity, Filter, Users, Award, FileText, Bell, Send, Sparkles, AlertOctagon
} from "lucide-react";
import { format, differenceInDays, parseISO } from "date-fns";
import { useToast } from "@/components/ui/use-toast";

const COMPLIANCE_TYPES = ["Background Check", "Food Handler", "RBS"];

const COMPLIANCE_CONFIG = {
  "Background Check": { 
    color: "bg-purple-400", 
    icon: ShieldCheck, 
    label: "BG Check",
    gradient: "from-purple-500 to-purple-600"
  },
  "Food Handler": { 
    color: "bg-emerald-400", 
    icon: FileText, 
    label: "Food",
    gradient: "from-emerald-500 to-emerald-600"
  },
  "RBS": { 
    color: "bg-blue-400", 
    icon: Award, 
    label: "RBS",
    gradient: "from-blue-500 to-blue-600"
  },
};

const STATUS_CONFIG = {
  current: { color: "bg-cyan-400", textColor: "text-white", label: "Current" },
  expiring_soon: { color: "bg-amber-300", textColor: "text-amber-800", label: "Expiring" },
  expired: { color: "bg-red-400", textColor: "text-white", label: "Expired" },
  pending: { color: "bg-yellow-200", textColor: "text-yellow-800", label: "Pending" },
  missing: { color: "bg-slate-200", textColor: "text-slate-500", label: "Missing" },
};

export default function VendorCompliance() {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [searchTerm, setSearchTerm] = useState("");
  const [showUploadModal, setShowUploadModal] = useState(false);
  const [selectedCell, setSelectedCell] = useState(null);
  const [showActivityPanel, setShowActivityPanel] = useState(false);
  const [statusFilter, setStatusFilter] = useState("all");
  const [certTypeFilter, setCertTypeFilter] = useState("all");

  const { data: user } = useQuery({
    queryKey: ['current-user-compliance'],
    queryFn: () => base44.auth.me(),
  });

  const { data: certifications = [] } = useQuery({
    queryKey: ['certifications'],
    queryFn: () => base44.entities.Certification.list(),
    initialData: [],
  });

  const { data: staff = [] } = useQuery({
    queryKey: ['staff-for-compliance'],
    queryFn: () => base44.entities.Staff.list(),
    initialData: [],
  });

  const userRole = user?.user_role || user?.role || "admin";
  const isVendor = userRole === "vendor";

  // Filter staff by vendor
  const filteredStaff = useMemo(() => {
    let result = staff;
    if (isVendor && user?.vendor_id) {
      result = result.filter(s => s.vendor_id === user.vendor_id);
    }
    if (searchTerm) {
      result = result.filter(s => 
        s.employee_name?.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }
    return result;
  }, [staff, isVendor, user, searchTerm]);

  // Calculate status from expiry date
  const calculateStatus = (expiryDate) => {
    if (!expiryDate) return "pending";
    const days = differenceInDays(parseISO(expiryDate), new Date());
    if (days < 0) return "expired";
    if (days <= 30) return "expiring_soon";
    return "current";
  };

  // Build compliance matrix
  const complianceMatrix = useMemo(() => {
    const matrix = {};
    
    filteredStaff.forEach(emp => {
      matrix[emp.id] = {
        employee: emp,
        certifications: {},
        completionRate: 0,
        canWork: false,
      };
      
      COMPLIANCE_TYPES.forEach(type => {
        matrix[emp.id].certifications[type] = null;
      });
    });

    certifications.forEach(cert => {
      if (matrix[cert.employee_id] && COMPLIANCE_TYPES.includes(cert.certification_type)) {
        const status = calculateStatus(cert.expiry_date);
        const daysUntilExpiry = cert.expiry_date 
          ? differenceInDays(parseISO(cert.expiry_date), new Date()) 
          : null;
        matrix[cert.employee_id].certifications[cert.certification_type] = { 
          ...cert, 
          status,
          days_until_expiry: daysUntilExpiry
        };
      }
    });

    // Calculate completion rates
    Object.values(matrix).forEach(row => {
      const certs = Object.values(row.certifications);
      const current = certs.filter(c => c && (c.status === "current" || c.status === "expiring_soon")).length;
      const hasExpired = certs.some(c => c && c.status === "expired");
      row.completionRate = Math.round((current / COMPLIANCE_TYPES.length) * 100);
      // Only block if they have an expired certification (not for missing)
      row.canWork = !hasExpired;
    });

    return matrix;
  }, [filteredStaff, certifications]);

  // Stats
  const stats = useMemo(() => {
    let total = 0, current = 0, expiring = 0, expired = 0;
    
    Object.values(complianceMatrix).forEach(row => {
      Object.values(row.certifications).forEach(cert => {
        total++;
        if (!cert) return;
        if (cert.status === "current") current++;
        else if (cert.status === "expiring_soon") expiring++;
        else if (cert.status === "expired") expired++;
      });
    });
    
    const missing = total - current - expiring - expired;
    const compliantEmployees = Object.values(complianceMatrix).filter(row => row.canWork).length;
    return { total, current, expiring, expired, missing, compliantEmployees };
  }, [complianceMatrix]);

  // Save certification
  const saveMutation = useMutation({
    mutationFn: async (data) => {
      if (data.id) {
        return base44.entities.Certification.update(data.id, data);
      }
      return base44.entities.Certification.create(data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['certifications'] });
      setShowUploadModal(false);
      setSelectedCell(null);
      toast({ title: "✅ Certification saved" });
    },
  });

  const handleCellClick = (employeeId, certType, existingCert) => {
    const emp = complianceMatrix[employeeId]?.employee;
    setSelectedCell({
      employee_id: employeeId,
      employee_name: emp?.employee_name,
      vendor_id: emp?.vendor_id,
      vendor_name: emp?.vendor_name,
      certification_type: certType,
      ...existingCert,
    });
    setShowUploadModal(true);
  };

  const renderCell = (cert, employeeId, certType) => {
    const status = cert?.status || "missing";
    const config = STATUS_CONFIG[status];
    const typeConfig = COMPLIANCE_CONFIG[certType];
    
    return (
      <button
        onClick={() => handleCellClick(employeeId, certType, cert)}
        className={`w-full h-14 rounded-lg flex flex-col items-center justify-center transition-all hover:scale-105 hover:shadow-md ${config.color} relative group`}
      >
        {status === "missing" ? (
          <Plus className="w-5 h-5 text-slate-400" />
        ) : status === "current" ? (
          <>
            <div className="flex items-center gap-1">
              <typeConfig.icon className="w-4 h-4 text-white" />
              <span className="text-[9px] text-white font-bold bg-cyan-600 px-1 rounded">✓</span>
            </div>
            {cert?.expiry_date && (
              <span className="text-[9px] text-white/90 mt-0.5 font-medium">
                {format(parseISO(cert.expiry_date), 'MM/dd/yy')}
              </span>
            )}
          </>
        ) : status === "expiring_soon" ? (
          <>
            <Clock className="w-4 h-4 text-amber-700" />
            {cert?.expiry_date && (
              <span className="text-[9px] text-amber-800 mt-0.5 font-bold">
                {cert.days_until_expiry}d left
              </span>
            )}
          </>
        ) : status === "expired" ? (
          <>
            <XCircle className="w-4 h-4 text-white" />
            <span className="text-[9px] text-white/90 mt-0.5 font-medium">Expired</span>
          </>
        ) : (
          <>
            <Clock className="w-4 h-4 text-yellow-700" />
            <span className="text-[9px] text-yellow-800 mt-0.5">Pending</span>
          </>
        )}
        
        {/* Hover tooltip */}
        {cert?.expiry_date && (
          <div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-2 py-1 bg-slate-900 text-white text-xs rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap pointer-events-none z-10">
            Expires: {format(parseISO(cert.expiry_date), 'MMM d, yyyy')}
          </div>
        )}
      </button>
    );
  };

  // Filter matrix by status and cert type
  const filteredMatrix = useMemo(() => {
    let result = { ...complianceMatrix };
    
    // Filter by status
    if (statusFilter !== "all") {
      result = Object.fromEntries(
        Object.entries(result).filter(([empId, row]) => {
          const certs = Object.values(row.certifications);
          if (statusFilter === "current") return certs.some(c => c?.status === "current");
          if (statusFilter === "expiring_soon") return certs.some(c => c?.status === "expiring_soon");
          if (statusFilter === "expired") return certs.some(c => c?.status === "expired");
          if (statusFilter === "missing") return certs.some(c => !c);
          if (statusFilter === "compliant") return row.canWork;
          if (statusFilter === "blocked") return !row.canWork;
          return true;
        })
      );
    }
    
    return result;
  }, [complianceMatrix, statusFilter, certTypeFilter]);

  // Calculate column completion percentages
  const columnStats = useMemo(() => {
    const stats = {};
    COMPLIANCE_TYPES.forEach(type => {
      const total = Object.keys(complianceMatrix).length;
      const current = Object.values(complianceMatrix).filter(
        row => row.certifications[type]?.status === "current"
      ).length;
      stats[type] = total > 0 ? Math.round((current / total) * 100) : 0;
    });
    return stats;
  }, [complianceMatrix]);

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-100 via-blue-50 to-slate-100 p-4 md:p-6">
      <div className="max-w-[1400px] mx-auto">
        {/* Header */}
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 bg-gradient-to-br from-purple-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg">
              <ShieldCheck className="w-6 h-6 text-white" />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-slate-900">Compliance Tracker</h1>
              <p className="text-sm text-slate-500">Background Check, Food Handler & RBS certifications</p>
            </div>
          </div>
          
          <div className="flex items-center gap-3">
            <div className="flex -space-x-2">
              {filteredStaff.slice(0, 3).map((emp) => (
                <Avatar key={emp.id} className="w-8 h-8 border-2 border-white">
                  <AvatarFallback className="bg-gradient-to-br from-purple-400 to-blue-500 text-white text-xs">
                    {emp.employee_name?.charAt(0)}
                  </AvatarFallback>
                </Avatar>
              ))}
              {filteredStaff.length > 3 && (
                <div className="w-8 h-8 rounded-full bg-slate-200 border-2 border-white flex items-center justify-center text-xs font-bold text-slate-600">
                  +{filteredStaff.length - 3}
                </div>
              )}
            </div>
            
            <Button
              variant="outline"
              className={`gap-2 ${showActivityPanel ? 'bg-orange-100 border-orange-300 text-orange-700' : ''}`}
              onClick={() => setShowActivityPanel(!showActivityPanel)}
            >
              <Activity className="w-4 h-4" />
              Activity
            </Button>
          </div>
        </div>

        {/* Stats Bar - Clickable */}
        <div className="grid grid-cols-2 md:grid-cols-6 gap-3 mb-6">
          <Card 
            className={`border-0 shadow-sm bg-white cursor-pointer transition-all hover:shadow-md hover:scale-[1.02] ${statusFilter === 'all' ? 'ring-2 ring-slate-400' : ''}`}
            onClick={() => setStatusFilter('all')}
          >
            <CardContent className="p-3">
              <div className="flex items-center gap-2">
                <div className="w-8 h-8 bg-slate-100 rounded-lg flex items-center justify-center">
                  <Users className="w-4 h-4 text-slate-600" />
                </div>
                <div>
                  <p className="text-lg font-bold text-slate-900">{filteredStaff.length}</p>
                  <p className="text-[10px] text-slate-500">Employees</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card 
            className={`border-0 shadow-sm bg-emerald-50 cursor-pointer transition-all hover:shadow-md hover:scale-[1.02] ${statusFilter === 'compliant' ? 'ring-2 ring-emerald-400' : ''}`}
            onClick={() => setStatusFilter('compliant')}
          >
            <CardContent className="p-3">
              <div className="flex items-center gap-2">
                <div className="w-8 h-8 bg-emerald-400 rounded-lg flex items-center justify-center">
                  <CheckCircle2 className="w-4 h-4 text-white" />
                </div>
                <div>
                  <p className="text-lg font-bold text-emerald-700">{stats.compliantEmployees}</p>
                  <p className="text-[10px] text-emerald-600">Compliant</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card 
            className={`border-0 shadow-sm bg-cyan-50 cursor-pointer transition-all hover:shadow-md hover:scale-[1.02] ${statusFilter === 'current' ? 'ring-2 ring-cyan-400' : ''}`}
            onClick={() => setStatusFilter('current')}
          >
            <CardContent className="p-3">
              <div className="flex items-center gap-2">
                <div className="w-8 h-8 bg-cyan-400 rounded-lg flex items-center justify-center">
                  <CheckCircle2 className="w-4 h-4 text-white" />
                </div>
                <div>
                  <p className="text-lg font-bold text-cyan-700">{stats.current}</p>
                  <p className="text-[10px] text-cyan-600">Current</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card 
            className={`border-0 shadow-sm bg-amber-50 cursor-pointer transition-all hover:shadow-md hover:scale-[1.02] ${statusFilter === 'expiring_soon' ? 'ring-2 ring-amber-400' : ''}`}
            onClick={() => setStatusFilter('expiring_soon')}
          >
            <CardContent className="p-3">
              <div className="flex items-center gap-2">
                <div className="w-8 h-8 bg-amber-400 rounded-lg flex items-center justify-center">
                  <AlertTriangle className="w-4 h-4 text-white" />
                </div>
                <div>
                  <p className="text-lg font-bold text-amber-700">{stats.expiring}</p>
                  <p className="text-[10px] text-amber-600">Expiring 30d</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card 
            className={`border-0 shadow-sm bg-red-50 cursor-pointer transition-all hover:shadow-md hover:scale-[1.02] ${statusFilter === 'expired' ? 'ring-2 ring-red-400' : ''}`}
            onClick={() => setStatusFilter('expired')}
          >
            <CardContent className="p-3">
              <div className="flex items-center gap-2">
                <div className="w-8 h-8 bg-red-400 rounded-lg flex items-center justify-center">
                  <XCircle className="w-4 h-4 text-white" />
                </div>
                <div>
                  <p className="text-lg font-bold text-red-700">{stats.expired}</p>
                  <p className="text-[10px] text-red-600">Expired</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card 
            className={`border-0 shadow-sm bg-slate-50 cursor-pointer transition-all hover:shadow-md hover:scale-[1.02] ${statusFilter === 'missing' ? 'ring-2 ring-slate-400' : ''}`}
            onClick={() => setStatusFilter('missing')}
          >
            <CardContent className="p-3">
              <div className="flex items-center gap-2">
                <div className="w-8 h-8 bg-slate-300 rounded-lg flex items-center justify-center">
                  <Plus className="w-4 h-4 text-slate-600" />
                </div>
                <div>
                  <p className="text-lg font-bold text-slate-700">{stats.missing}</p>
                  <p className="text-[10px] text-slate-500">Missing</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Main Compliance Matrix */}
        <Card className="border-0 shadow-xl rounded-2xl overflow-hidden">
          <CardContent className="p-0">
            {/* Search & Filter Bar */}
            <div className="p-4 border-b border-slate-100 bg-white flex flex-wrap items-center gap-3">
              <div className="relative flex-1 min-w-[200px] max-w-sm">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                <Input
                  placeholder="Search employees..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10 bg-slate-50 border-0 h-10"
                />
              </div>
              
              {/* Status Filter */}
              <Select value={statusFilter} onValueChange={setStatusFilter}>
                <SelectTrigger className="w-[160px] h-10">
                  <SelectValue placeholder="Status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Status</SelectItem>
                  <SelectItem value="current">
                    <div className="flex items-center gap-2">
                      <div className="w-2 h-2 rounded-full bg-cyan-400" />
                      Current
                    </div>
                  </SelectItem>
                  <SelectItem value="expiring_soon">
                    <div className="flex items-center gap-2">
                      <div className="w-2 h-2 rounded-full bg-amber-400" />
                      Expiring Soon
                    </div>
                  </SelectItem>
                  <SelectItem value="expired">
                    <div className="flex items-center gap-2">
                      <div className="w-2 h-2 rounded-full bg-red-400" />
                      Expired
                    </div>
                  </SelectItem>
                  <SelectItem value="missing">
                    <div className="flex items-center gap-2">
                      <div className="w-2 h-2 rounded-full bg-slate-300" />
                      Missing
                    </div>
                  </SelectItem>
                  <SelectItem value="compliant">
                    <div className="flex items-center gap-2">
                      <CheckCircle2 className="w-3 h-3 text-emerald-500" />
                      Compliant
                    </div>
                  </SelectItem>
                  <SelectItem value="blocked">
                    <div className="flex items-center gap-2">
                      <XCircle className="w-3 h-3 text-red-500" />
                      Blocked
                    </div>
                  </SelectItem>
                </SelectContent>
              </Select>

              {/* Certificate Type Filter */}
              <Select value={certTypeFilter} onValueChange={setCertTypeFilter}>
                <SelectTrigger className="w-[180px] h-10">
                  <SelectValue placeholder="Cert Type" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Certificates</SelectItem>
                  <SelectItem value="Background Check">
                    <div className="flex items-center gap-2">
                      <ShieldCheck className="w-3 h-3 text-purple-500" />
                      Background Check
                    </div>
                  </SelectItem>
                  <SelectItem value="Food Handler">
                    <div className="flex items-center gap-2">
                      <FileText className="w-3 h-3 text-emerald-500" />
                      Food Handler
                    </div>
                  </SelectItem>
                  <SelectItem value="RBS">
                    <div className="flex items-center gap-2">
                      <Award className="w-3 h-3 text-blue-500" />
                      RBS
                    </div>
                  </SelectItem>
                </SelectContent>
              </Select>

              {(statusFilter !== "all" || certTypeFilter !== "all") && (
                <Button 
                  variant="ghost" 
                  size="sm" 
                  onClick={() => { setStatusFilter("all"); setCertTypeFilter("all"); }}
                  className="text-slate-500 hover:text-slate-700"
                >
                  Clear filters
                </Button>
              )}

              <Button variant="outline" size="sm" className="gap-2 ml-auto">
                <Send className="w-4 h-4" />
                Send Report
              </Button>
            </div>

            {/* Matrix Table */}
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="bg-slate-50">
                    <th className="text-left p-4 font-semibold text-slate-700 min-w-[220px] sticky left-0 bg-slate-50 z-10">
                      Employees
                    </th>
                    {COMPLIANCE_TYPES.map(type => {
                      const config = COMPLIANCE_CONFIG[type];
                      return (
                        <th key={type} className="p-4 min-w-[140px]">
                          <div className="text-center">
                            <div className="flex items-center justify-center gap-2 mb-2">
                              <div className={`w-6 h-6 rounded-md bg-gradient-to-br ${config.gradient} flex items-center justify-center`}>
                                <config.icon className="w-3.5 h-3.5 text-white" />
                              </div>
                              <p className="font-semibold text-slate-700 text-sm">{type}</p>
                            </div>
                            <div className="flex gap-0.5 justify-center">
                              <div className={`h-1.5 w-6 rounded-full ${columnStats[type] >= 25 ? config.color : 'bg-slate-200'}`} />
                              <div className={`h-1.5 w-6 rounded-full ${columnStats[type] >= 50 ? 'bg-amber-400' : 'bg-slate-200'}`} />
                              <div className={`h-1.5 w-6 rounded-full ${columnStats[type] >= 75 ? 'bg-red-400' : 'bg-slate-200'}`} />
                              <div className={`h-1.5 w-6 rounded-full ${columnStats[type] >= 100 ? 'bg-emerald-400' : 'bg-slate-200'}`} />
                            </div>
                            <p className="text-[10px] text-slate-500 mt-1">{columnStats[type]}% complete</p>
                          </div>
                        </th>
                      );
                    })}
                    <th className="p-4 w-20 text-center">
                      <span className="text-xs font-semibold text-slate-500">Status</span>
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {Object.entries(filteredMatrix).map(([empId, row], idx) => (
                    <tr key={empId} className={`border-t border-slate-100 ${idx % 2 === 0 ? 'bg-white' : 'bg-slate-50/50'}`}>
                      <td className="p-4 sticky left-0 bg-inherit z-10">
                        <div className="flex items-center gap-3">
                          <Avatar className="w-10 h-10 border-2 border-white shadow">
                            <AvatarFallback className="bg-gradient-to-br from-purple-400 to-blue-500 text-white font-bold">
                              {row.employee.employee_name?.charAt(0)}
                            </AvatarFallback>
                          </Avatar>
                          <div className="flex-1 min-w-0">
                            <p className="font-semibold text-slate-900 truncate">{row.employee.employee_name}</p>
                            <div className="flex items-center gap-2">
                              <Progress value={row.completionRate} className="h-1.5 w-16" />
                              <span className="text-xs text-slate-500">{row.completionRate}%</span>
                            </div>
                          </div>
                        </div>
                      </td>
                      {COMPLIANCE_TYPES.map(type => (
                        <td key={type} className={`p-2 ${certTypeFilter !== "all" && certTypeFilter !== type ? 'opacity-30' : ''}`}>
                          {renderCell(row.certifications[type], empId, type)}
                        </td>
                      ))}
                      <td className="p-2 text-center">
                        {row.canWork ? (
                          <Badge className="bg-emerald-100 text-emerald-700 border-0 font-semibold">
                            <CheckCircle2 className="w-3 h-3 mr-1" />
                            Clear
                          </Badge>
                        ) : (
                          <Badge className="bg-red-100 text-red-700 border-0 font-semibold">
                            <XCircle className="w-3 h-3 mr-1" />
                            Blocked
                          </Badge>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>

              {filteredStaff.length === 0 && (
                <div className="p-12 text-center">
                  <ShieldCheck className="w-12 h-12 mx-auto mb-3 text-slate-200" />
                  <p className="text-slate-500">No employees found</p>
                </div>
              )}
            </div>

            {/* Footer */}
            <div className="p-4 border-t border-slate-100 bg-slate-50 text-center">
              <p className="text-sm text-slate-500">
                Hover over cells to see expiration dates • Click to add or update certifications
              </p>
            </div>
          </CardContent>
        </Card>

        {/* Upload Modal */}
        <Dialog open={showUploadModal} onOpenChange={setShowUploadModal}>
          <DialogContent className="max-w-md">
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                <ShieldCheck className="w-5 h-5 text-purple-600" />
                {selectedCell?.id ? 'Update' : 'Add'} Certification
              </DialogTitle>
              {selectedCell?.employee_name && (
                <DialogDescription>For: {selectedCell.employee_name}</DialogDescription>
              )}
            </DialogHeader>
            {selectedCell && (
              <CertificationForm
                data={selectedCell}
                onSave={(data) => saveMutation.mutate(data)}
                onCancel={() => { setShowUploadModal(false); setSelectedCell(null); }}
                isLoading={saveMutation.isPending}
              />
            )}
          </DialogContent>
        </Dialog>

        {/* Activity Panel */}
        {showActivityPanel && (
          <div className="fixed right-0 top-0 h-full w-80 bg-white shadow-2xl border-l border-slate-200 z-50 p-6 overflow-y-auto">
            <div className="flex items-center justify-between mb-6">
              <h3 className="font-bold text-lg">Recent Activity</h3>
              <Button variant="ghost" size="sm" onClick={() => setShowActivityPanel(false)}>
                <XCircle className="w-4 h-4" />
              </Button>
            </div>
            <div className="space-y-4">
              {[1,2,3,4,5].map(i => (
                <div key={i} className="flex items-start gap-3 p-3 bg-slate-50 rounded-lg">
                  <div className="w-8 h-8 rounded-full bg-purple-400 flex items-center justify-center">
                    <ShieldCheck className="w-4 h-4 text-white" />
                  </div>
                  <div>
                    <p className="text-sm font-medium text-slate-900">Certification updated</p>
                    <p className="text-xs text-slate-500">Background Check • 2 hours ago</p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function CertificationForm({ data, onSave, onCancel, isLoading }) {
  const [formData, setFormData] = useState({
    employee_id: data.employee_id || "",
    employee_name: data.employee_name || "",
    vendor_id: data.vendor_id || "",
    vendor_name: data.vendor_name || "",
    certification_type: data.certification_type || "",
    status: data.status || "current",
    expiry_date: data.expiry_date || "",
    issuer: data.issuer || "",
    certificate_number: data.certificate_number || "",
    document_url: data.document_url || "",
    notes: data.notes || "",
    ...data,
  });

  const [uploading, setUploading] = useState(false);
  const [verificationResult, setVerificationResult] = useState(null);
  const [verifying, setVerifying] = useState(false);
  const [isDragging, setIsDragging] = useState(false);

  const processFile = async (file) => {
    if (!file) return;
    
    setUploading(true);
    setVerificationResult(null);
    try {
      const result = await base44.integrations.Core.UploadFile({ file });
      setFormData(prev => ({ ...prev, document_url: result.file_url }));
      
      // Auto-extract data and verify
      setVerifying(true);
      const extraction = await base44.integrations.Core.InvokeLLM({
        prompt: `Analyze this ${formData.certification_type} certificate image. Extract the following information and verify authenticity:

1. Extract the expiration/expiry date (format as YYYY-MM-DD)
2. Extract the issuing authority/organization name
3. Extract the certificate/license number
4. Check for signs of tampering or editing

Return the extracted data and verification results.`,
        file_urls: [result.file_url],
        response_json_schema: {
          type: "object",
          properties: {
            expiry_date: { type: "string", description: "Expiration date in YYYY-MM-DD format, or empty if not found" },
            issuer: { type: "string", description: "Issuing authority name" },
            certificate_number: { type: "string", description: "Certificate or license number" },
            is_authentic: { type: "boolean", description: "Whether document appears authentic" },
            confidence: { type: "number", description: "Confidence score 0-100" },
            risk_level: { type: "string", enum: ["low", "medium", "high"], description: "Risk level of tampering" },
            findings: { type: "array", items: { type: "string" }, description: "List of specific findings" },
            recommendation: { type: "string", description: "Brief recommendation" }
          }
        }
      });
      
      // Auto-fill extracted fields
      setFormData(prev => ({
        ...prev,
        expiry_date: extraction.expiry_date || prev.expiry_date,
        issuer: extraction.issuer || prev.issuer,
        certificate_number: extraction.certificate_number || prev.certificate_number,
      }));
      
      setVerificationResult(extraction);
      setVerifying(false);
    } catch (error) {
      console.error("Upload/verification failed:", error);
      setVerifying(false);
    }
    setUploading(false);
  };

  const handleFileUpload = (e) => {
    processFile(e.target.files?.[0]);
  };

  const handleDrop = (e) => {
    e.preventDefault();
    setIsDragging(false);
    const file = e.dataTransfer.files?.[0];
    if (file && (file.type.includes('image') || file.type === 'application/pdf')) {
      processFile(file);
    }
  };

  const handleDragOver = (e) => {
    e.preventDefault();
    setIsDragging(true);
  };

  const handleDragLeave = (e) => {
    e.preventDefault();
    setIsDragging(false);
  };

  const config = COMPLIANCE_CONFIG[formData.certification_type];

  return (
    <div className="space-y-4">
      <div className={`p-4 rounded-lg bg-gradient-to-r ${config?.gradient || 'from-slate-500 to-slate-600'} text-white`}>
        <div className="flex items-center gap-3">
          {config && <config.icon className="w-6 h-6" />}
          <div>
            <p className="font-bold">{formData.certification_type}</p>
            <p className="text-sm text-white/80">{formData.employee_name}</p>
          </div>
        </div>
      </div>

      {/* Drag & Drop Upload Area */}
      <div>
        <Label className="text-sm font-medium">Upload Certificate</Label>
        <div 
          className={`mt-2 border-2 border-dashed rounded-xl p-6 text-center transition-all cursor-pointer ${
            isDragging 
              ? 'border-purple-500 bg-purple-50 scale-[1.02]' 
              : 'border-slate-300 hover:border-purple-400'
          }`}
          onDrop={handleDrop}
          onDragOver={handleDragOver}
          onDragLeave={handleDragLeave}
          onClick={() => document.getElementById('cert-upload').click()}
        >
          <input
            type="file"
            accept=".pdf,.jpg,.jpeg,.png"
            onChange={handleFileUpload}
            className="hidden"
            id="cert-upload"
          />
          {uploading || verifying ? (
            <div className="animate-pulse">
              <Sparkles className="w-8 h-8 mx-auto text-purple-500 mb-2 animate-spin" />
              <p className="text-sm text-purple-600">{uploading ? 'Uploading...' : 'AI Extracting Data...'}</p>
            </div>
          ) : formData.document_url ? (
            <div className="flex items-center justify-center gap-2 text-green-600">
              <CheckCircle2 className="w-6 h-6" />
              <span>Certificate uploaded</span>
            </div>
          ) : (
            <div>
              <Upload className="w-8 h-8 mx-auto text-slate-400 mb-2" />
              <p className="text-sm text-slate-600 font-medium">Drag & drop or click to upload</p>
              <p className="text-xs text-slate-400 mt-1">PDF, JPG, PNG • AI will auto-extract details</p>
            </div>
          )}
        </div>
      </div>

      {/* Expiry Date - Primary field */}
      <div>
        <Label className="text-sm font-medium">Expiry Date *</Label>
        <Input
          type="date"
          value={formData.expiry_date}
          onChange={(e) => setFormData(prev => ({ ...prev, expiry_date: e.target.value }))}
          className="mt-1.5"
          required
        />
      </div>

      {/* Auto-detected fields */}
      <div className="grid grid-cols-2 gap-4">
        <div>
          <Label className="text-sm font-medium text-slate-600">
            Issuing Authority
            {formData.issuer && verificationResult && <span className="text-purple-500 ml-1 text-xs">(auto-detected)</span>}
          </Label>
          <Input
            value={formData.issuer}
            onChange={(e) => setFormData(prev => ({ ...prev, issuer: e.target.value }))}
            placeholder="Auto-detected from upload"
            className="mt-1.5"
          />
        </div>
        <div>
          <Label className="text-sm font-medium text-slate-600">
            Certificate #
            {formData.certificate_number && verificationResult && <span className="text-purple-500 ml-1 text-xs">(auto-detected)</span>}
          </Label>
          <Input
            value={formData.certificate_number}
            onChange={(e) => setFormData(prev => ({ ...prev, certificate_number: e.target.value }))}
            placeholder="Auto-detected from upload"
            className="mt-1.5"
          />
        </div>
      </div>

      {/* AI Verification Result */}
      {verificationResult && (
        <div className={`p-4 rounded-xl border-2 ${
          verificationResult.risk_level === 'low' ? 'bg-emerald-50 border-emerald-200' :
          verificationResult.risk_level === 'medium' ? 'bg-amber-50 border-amber-200' :
          'bg-red-50 border-red-200'
        }`}>
          <div className="flex items-start gap-3">
            <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${
              verificationResult.risk_level === 'low' ? 'bg-emerald-500' :
              verificationResult.risk_level === 'medium' ? 'bg-amber-500' :
              'bg-red-500'
            }`}>
              {verificationResult.risk_level === 'low' ? (
                <CheckCircle2 className="w-5 h-5 text-white" />
              ) : verificationResult.risk_level === 'medium' ? (
                <AlertTriangle className="w-5 h-5 text-white" />
              ) : (
                <AlertOctagon className="w-5 h-5 text-white" />
              )}
            </div>
            <div className="flex-1">
              <div className="flex items-center gap-2 mb-1">
                <Sparkles className="w-4 h-4 text-purple-600" />
                <span className="text-xs font-semibold text-purple-600">AI Verification</span>
                <span className={`text-xs font-bold px-2 py-0.5 rounded-full ${
                  verificationResult.risk_level === 'low' ? 'bg-emerald-200 text-emerald-800' :
                  verificationResult.risk_level === 'medium' ? 'bg-amber-200 text-amber-800' :
                  'bg-red-200 text-red-800'
                }`}>
                  {verificationResult.confidence}% confidence
                </span>
              </div>
              <p className={`font-semibold ${
                verificationResult.risk_level === 'low' ? 'text-emerald-800' :
                verificationResult.risk_level === 'medium' ? 'text-amber-800' :
                'text-red-800'
              }`}>
                {verificationResult.is_authentic ? 'Document appears authentic' : 'Potential issues detected'}
              </p>
              <p className="text-sm text-slate-600 mt-1">{verificationResult.recommendation}</p>
              
              {verificationResult.findings?.length > 0 && (
                <div className="mt-2 space-y-1">
                  {verificationResult.findings.map((finding, idx) => (
                    <p key={idx} className="text-xs text-slate-500 flex items-start gap-1">
                      <span>•</span> {finding}
                    </p>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      <div className="flex justify-end gap-2 pt-4 border-t">
        <Button variant="outline" onClick={onCancel}>Cancel</Button>
        <Button 
          onClick={() => onSave(formData)} 
          disabled={isLoading || !formData.expiry_date}
          className="bg-purple-600 hover:bg-purple-700"
        >
          {isLoading ? "Saving..." : "Save Certification"}
        </Button>
      </div>
    </div>
  );
}