import React, { useState } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery } from "@tanstack/react-query";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Shield, Search, CheckCircle2, AlertTriangle, XCircle, DollarSign, Award, FileText } from "lucide-react";

export default function WorkforceCompliance() {
  const [searchTerm, setSearchTerm] = useState("");

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

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

  // Calculate compliance metrics
  const totalStaff = staff.length;
  const backgroundCheckCompliant = staff.filter(s => s.background_check_status === "cleared").length;
  const wageCompliant = rates.filter(r => r.employee_wage >= 16.50).length;
  const certifiedStaff = staff.filter(s => s.certifications?.length > 0).length;

  const complianceRate = totalStaff > 0 ? ((backgroundCheckCompliant / totalStaff) * 100).toFixed(1) : 0;
  const wageComplianceRate = rates.length > 0 ? ((wageCompliant / rates.length) * 100).toFixed(1) : 0;

  const filteredStaff = staff.filter(member =>
    !searchTerm ||
    member.employee_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    member.vendor_name?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div className="p-4 md:p-8 bg-slate-50 min-h-screen">
      <div className="max-w-7xl mx-auto">
        <div className="mb-6">
          <h1 className="text-3xl font-bold text-[#1C323E] mb-2">Workforce Compliance</h1>
          <p className="text-slate-600">Monitor background checks, certifications, and fair wage compliance</p>
        </div>

        {/* Compliance Overview */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
          <Card className="border-slate-200">
            <CardContent className="p-6">
              <div className="flex items-center justify-between mb-2">
                <Shield className="w-8 h-8 text-green-600" />
                <Badge className={complianceRate >= 95 ? "bg-green-100 text-green-700" : "bg-amber-100 text-amber-700"}>
                  {complianceRate}%
                </Badge>
              </div>
              <p className="text-sm text-slate-500">Background Checks</p>
              <p className="text-3xl font-bold text-[#1C323E]">{backgroundCheckCompliant}/{totalStaff}</p>
            </CardContent>
          </Card>

          <Card className="border-slate-200">
            <CardContent className="p-6">
              <div className="flex items-center justify-between mb-2">
                <DollarSign className="w-8 h-8 text-blue-600" />
                <Badge className={wageComplianceRate >= 100 ? "bg-green-100 text-green-700" : "bg-red-100 text-red-700"}>
                  {wageComplianceRate}%
                </Badge>
              </div>
              <p className="text-sm text-slate-500">Fair Wage Compliance</p>
              <p className="text-3xl font-bold text-[#1C323E]">{wageCompliant}/{rates.length}</p>
            </CardContent>
          </Card>

          <Card className="border-slate-200">
            <CardContent className="p-6">
              <div className="flex items-center justify-between mb-2">
                <Award className="w-8 h-8 text-purple-600" />
              </div>
              <p className="text-sm text-slate-500">Certified Staff</p>
              <p className="text-3xl font-bold text-[#1C323E]">{certifiedStaff}</p>
            </CardContent>
          </Card>

          <Card className="border-slate-200">
            <CardContent className="p-6">
              <div className="flex items-center justify-between mb-2">
                <FileText className="w-8 h-8 text-amber-600" />
              </div>
              <p className="text-sm text-slate-500">Active Workforce</p>
              <p className="text-3xl font-bold text-[#1C323E]">{totalStaff}</p>
            </CardContent>
          </Card>
        </div>

        {/* Search */}
        <Card className="mb-6 border-slate-200">
          <CardContent className="p-4">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-slate-400" />
              <Input
                placeholder="Search by staff name or vendor..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
          </CardContent>
        </Card>

        {/* Staff Compliance List */}
        <Card className="border-slate-200">
          <CardHeader className="bg-gradient-to-br from-slate-50 to-white border-b">
            <CardTitle>Workforce Compliance Status</CardTitle>
          </CardHeader>
          <CardContent className="p-6">
            <div className="space-y-4">
              {filteredStaff.map((member) => {
                const hasBackgroundCheck = member.background_check_status === "cleared";
                const hasCertifications = member.certifications?.length > 0;
                
                return (
                  <div key={member.id} className="p-4 border border-slate-200 rounded-lg hover:border-[#0A39DF] transition-colors">
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-3 mb-2">
                          <h4 className="font-semibold text-[#1C323E]">{member.employee_name}</h4>
                          <Badge variant="outline" className="text-xs">{member.vendor_name || "N/A"}</Badge>
                        </div>
                        <p className="text-sm text-slate-600 mb-3">{member.position || "Staff Member"}</p>
                        <div className="flex items-center gap-4 flex-wrap">
                          {hasBackgroundCheck ? (
                            <div className="flex items-center gap-1 text-green-700">
                              <CheckCircle2 className="w-4 h-4" />
                              <span className="text-sm font-medium">Background Check ✓</span>
                            </div>
                          ) : (
                            <div className="flex items-center gap-1 text-red-700">
                              <XCircle className="w-4 h-4" />
                              <span className="text-sm font-medium">No Background Check</span>
                            </div>
                          )}
                          {hasCertifications ? (
                            <div className="flex items-center gap-1 text-blue-700">
                              <Award className="w-4 h-4" />
                              <span className="text-sm font-medium">Certified</span>
                            </div>
                          ) : (
                            <div className="flex items-center gap-1 text-slate-500">
                              <Award className="w-4 h-4" />
                              <span className="text-sm font-medium">No Certifications</span>
                            </div>
                          )}
                        </div>
                      </div>
                      <Badge className={hasBackgroundCheck && hasCertifications ? "bg-green-100 text-green-700" : "bg-amber-100 text-amber-700"}>
                        {hasBackgroundCheck && hasCertifications ? "Compliant" : "Review Required"}
                      </Badge>
                    </div>
                  </div>
                );
              })}
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}