
import React, { useState, useMemo } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery } from "@tanstack/react-query";
import { Link } from "react-router-dom";
import { createPageUrl } from "@/utils";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Briefcase, Plus, Search, MapPin, DollarSign, Edit, Building2, TrendingUp, AlertTriangle, CheckCircle2, Users, Target, LayoutGrid, List } from "lucide-react";
import PageHeader from "../components/common/PageHeader";

export default function PartnerManagement() {
  const [searchTerm, setSearchTerm] = useState("");
  const [viewMode, setViewMode] = useState("grid"); // New state for view mode

  const { data: partners = [], isLoading: partnersLoading } = useQuery({
    queryKey: ['partners'],
    queryFn: () => base44.entities.Partner.list('-created_date'),
    initialData: [],
  });

  const { data: businesses = [], isLoading: businessesLoading } = useQuery({
    queryKey: ['businesses'],
    queryFn: () => base44.entities.Business.list('-created_date'),
    initialData: [],
  });

  const { data: sectors = [] } = useQuery({
    queryKey: ['sectors'],
    queryFn: () => base44.entities.Sector.list('-created_date'),
    initialData: [],
  });

  const { data: enterprises = [] } = useQuery({
    queryKey: ['enterprises'],
    queryFn: () => base44.entities.Enterprise.list('-created_date'),
    initialData: [],
  });

  // Consolidate businesses by company name
  const consolidatedBusinesses = useMemo(() => {
    const grouped = {};
    
    businesses.forEach(business => {
      let companyName = business.business_name;
      
      // Extract company name (remove hub suffix if present)
      const dashIndex = companyName.indexOf(' - ');
      if (dashIndex > 0) {
        companyName = companyName.substring(0, dashIndex).trim();
      }
      
      if (!grouped[companyName]) {
        grouped[companyName] = {
          company_name: companyName,
          partner_type: "Corporate",
          hubs: [],
          primary_contact: business.contact_name,
          primary_email: business.email,
          primary_phone: business.phone,
          sector: business.sector || business.area || '',
          total_hubs: 0,
          company_logo: business.company_logo || null,
        };
      }
      
      grouped[companyName].hubs.push({
        id: business.id,
        hub_name: business.business_name,
        contact_name: business.contact_name,
        email: business.email,
        phone: business.phone,
        address: business.address,
        city: business.city,
        area: business.area,
        rate_group: business.rate_group,
        company_logo: business.company_logo,
      });
      grouped[companyName].total_hubs++;
      
      // Use the first hub's logo if available
      if (business.company_logo && !grouped[companyName].company_logo) {
        grouped[companyName].company_logo = business.company_logo;
      }
    });
    
    return Object.values(grouped);
  }, [businesses]);

  // Operator coverage data
  const operatorMetrics = {
    totalCoverage: 94,
    activeIncidents: 2,
    clientSatisfaction: 4.8,
    forecastAccuracy: 91
  };

  const hubCoverageData = [
    { hub: 'San Jose', enterprise: 'Compass', sector: 'Bon Appétit', coverage: 97, incidents: 0, satisfaction: 4.9, partners: 12 },
    { hub: 'San Francisco', enterprise: 'Compass', sector: 'Eurest', coverage: 92, incidents: 1, satisfaction: 4.7, partners: 8 },
    { hub: 'Oakland', enterprise: 'Compass', sector: 'Bon Appétit', coverage: 89, incidents: 2, satisfaction: 4.5, partners: 6 },
    { hub: 'Sacramento', enterprise: 'Compass', sector: 'Chartwells', coverage: 95, incidents: 1, satisfaction: 4.8, partners: 10 },
  ];

  const filteredPartners = partners.filter(p =>
    !searchTerm ||
    p.partner_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    p.partner_number?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const filteredBusinesses = consolidatedBusinesses.filter(b =>
    !searchTerm ||
    b.company_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    b.primary_contact?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const totalPartnerCount = filteredPartners.length + filteredBusinesses.length;
  const totalHubCount = filteredBusinesses.reduce((sum, b) => sum + b.total_hubs, 0) + 
                        filteredPartners.reduce((sum, p) => sum + (p.sites?.length || 0), 0);

  const isLoading = partnersLoading || businessesLoading;

  return (
    <div className="p-4 md:p-8 bg-slate-50 min-h-screen">
      <div className="max-w-7xl mx-auto">
        <PageHeader
          title="Partners & Operators"
          subtitle={`${totalPartnerCount} partners • ${totalHubCount} total hubs • ${sectors.length} sectors • ${enterprises.length} enterprises`}
          actions={
            <div className="flex gap-2">
              <Link to={createPageUrl("AddPartner")}>
                <Button className="bg-[#0A39DF] hover:bg-[#0A39DF]/90">
                  <Plus className="w-4 h-4 mr-2" />
                  Add Partner
                </Button>
              </Link>
              <Link to={createPageUrl("Business")}>
                <Button variant="outline" className="border-slate-300">
                  <Building2 className="w-4 h-4 mr-2" />
                  Business Directory
                </Button>
              </Link>
            </div>
          }
        />

        {/* Operator Key Metrics */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
          <Card className="border-slate-200 shadow-lg">
            <CardContent className="p-6">
              <div className="flex items-center justify-between mb-2">
                <Target className="w-8 h-8 text-[#0A39DF]" />
                <Badge className="bg-emerald-100 text-emerald-700">+5%</Badge>
              </div>
              <p className="text-sm text-slate-500">Coverage Rate</p>
              <p className="text-3xl font-bold text-[#1C323E]">{operatorMetrics.totalCoverage}%</p>
            </CardContent>
          </Card>

          <Card className="border-slate-200 shadow-lg">
            <CardContent className="p-6">
              <div className="flex items-center justify-between mb-2">
                <AlertTriangle className="w-8 h-8 text-amber-600" />
                <Badge className="bg-green-100 text-green-700">Low</Badge>
              </div>
              <p className="text-sm text-slate-500">Active Incidents</p>
              <p className="text-3xl font-bold text-[#1C323E]">{operatorMetrics.activeIncidents}</p>
            </CardContent>
          </Card>

          <Card className="border-slate-200 shadow-lg">
            <CardContent className="p-6">
              <div className="flex items-center justify-between mb-2">
                <CheckCircle2 className="w-8 h-8 text-emerald-600" />
                <Badge className="bg-blue-100 text-blue-700">{operatorMetrics.clientSatisfaction}/5.0</Badge>
              </div>
              <p className="text-sm text-slate-500">Client Satisfaction</p>
              <p className="text-3xl font-bold text-[#1C323E]">{operatorMetrics.clientSatisfaction}</p>
            </CardContent>
          </Card>

          <Card className="border-slate-200 shadow-lg">
            <CardContent className="p-6">
              <div className="flex items-center justify-between mb-2">
                <TrendingUp className="w-8 h-8 text-purple-600" />
                <Badge className="bg-purple-100 text-purple-700">{operatorMetrics.forecastAccuracy}%</Badge>
              </div>
              <p className="text-sm text-slate-500">Forecast Accuracy</p>
              <p className="text-3xl font-bold text-[#1C323E]">{operatorMetrics.forecastAccuracy}%</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 partners or businesses..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
          </CardContent>
        </Card>

        {/* Live Operator Coverage Map */}
        <Card className="border-slate-200 shadow-lg mb-8">
          <CardHeader className="bg-gradient-to-br from-blue-50 to-white border-b border-slate-100">
            <CardTitle className="text-base flex items-center gap-2">
              <MapPin className="w-5 h-5 text-[#0A39DF]" />
              Live Operator Coverage Map
            </CardTitle>
            <p className="text-sm text-slate-500 mt-1">Real-time coverage across all hubs and sectors</p>
          </CardHeader>
          <CardContent className="p-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {hubCoverageData.map((hub, index) => (
                <div 
                  key={index} 
                  className="p-6 rounded-xl border-2 border-slate-200 hover:border-[#0A39DF] hover:shadow-lg transition-all bg-white"
                >
                  <div className="flex items-center justify-between mb-4">
                    <div className="flex items-center gap-3">
                      <div className={`w-12 h-12 rounded-xl flex items-center justify-center ${
                        hub.coverage >= 95 ? 'bg-emerald-100' :
                        hub.coverage >= 90 ? 'bg-blue-100' :
                        'bg-amber-100'
                      }`}>
                        <MapPin className={`w-6 h-6 ${
                          hub.coverage >= 95 ? 'text-emerald-600' :
                          hub.coverage >= 90 ? 'text-blue-600' :
                          'text-amber-600'
                        }`} />
                      </div>
                      <div>
                        <h4 className="font-bold text-[#1C323E]">{hub.hub}</h4>
                        <p className="text-xs text-slate-500">{hub.enterprise} • {hub.sector}</p>
                      </div>
                    </div>
                    <Badge className={`${
                      hub.coverage >= 95 ? 'bg-emerald-100 text-emerald-700' :
                      hub.coverage >= 90 ? 'bg-blue-100 text-blue-700' :
                      'bg-amber-100 text-amber-700'
                    } text-lg px-3 py-1 font-bold`}>
                      {hub.coverage}%
                    </Badge>
                  </div>
                  
                  <div className="grid grid-cols-3 gap-4 text-sm mb-4">
                    <div className="p-3 bg-slate-50 rounded-lg">
                      <p className="text-xs text-slate-500 mb-1">Partners</p>
                      <p className="font-bold text-[#0A39DF]">{hub.partners}</p>
                    </div>
                    <div className="p-3 bg-slate-50 rounded-lg">
                      <p className="text-xs text-slate-500 mb-1">Incidents</p>
                      <p className={`font-bold ${hub.incidents > 0 ? 'text-red-600' : 'text-emerald-600'}`}>
                        {hub.incidents}
                      </p>
                    </div>
                    <div className="p-3 bg-slate-50 rounded-lg">
                      <p className="text-xs text-slate-500 mb-1">Rating</p>
                      <p className="font-bold text-amber-600">{hub.satisfaction}/5.0</p>
                    </div>
                  </div>

                  <div className="w-full bg-slate-200 rounded-full h-2">
                    <div 
                      className={`h-2 rounded-full ${
                        hub.coverage >= 95 ? 'bg-gradient-to-r from-emerald-500 to-emerald-600' :
                        hub.coverage >= 90 ? 'bg-gradient-to-r from-blue-500 to-blue-600' :
                        'bg-gradient-to-r from-amber-500 to-amber-600'
                      }`}
                      style={{ width: `${hub.coverage}%` }}
                    />
                  </div>
                </div>
              ))}
            </div>

            {/* Organizational Hierarchy */}
            <div className="mt-8 pt-6 border-t border-slate-200">
              <h3 className="text-base font-bold text-[#1C323E] mb-4 flex items-center gap-2">
                <Building2 className="w-5 h-5 text-[#0A39DF]" />
                Enterprise & Sector Overview
              </h3>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div className="p-5 bg-gradient-to-br from-indigo-50 to-white rounded-xl border-2 border-slate-200">
                  <div className="flex items-center gap-2 mb-3">
                    <div className="w-10 h-10 bg-indigo-100 rounded-lg flex items-center justify-center">
                      <Building2 className="w-5 h-5 text-indigo-600" />
                    </div>
                    <div>
                      <p className="text-xs text-slate-500">Enterprises</p>
                      <p className="text-2xl font-bold text-[#1C323E]">{enterprises.length}</p>
                    </div>
                  </div>
                  <Link to={createPageUrl("EnterpriseManagement")}>
                    <Button variant="outline" size="sm" className="w-full text-xs border-slate-300">
                      Manage Enterprises
                    </Button>
                  </Link>
                </div>

                <div className="p-5 bg-gradient-to-br from-purple-50 to-white rounded-xl border-2 border-slate-200">
                  <div className="flex items-center gap-2 mb-3">
                    <div className="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
                      <MapPin className="w-5 h-5 text-purple-600" />
                    </div>
                    <div>
                      <p className="text-xs text-slate-500">Sectors</p>
                      <p className="text-2xl font-bold text-[#1C323E]">{sectors.length}</p>
                    </div>
                  </div>
                  <Link to={createPageUrl("SectorManagement")}>
                    <Button variant="outline" size="sm" className="w-full text-xs border-slate-300">
                      Manage Sectors
                    </Button>
                  </Link>
                </div>

                <div className="p-5 bg-gradient-to-br from-green-50 to-white rounded-xl border-2 border-slate-200">
                  <div className="flex items-center gap-2 mb-3">
                    <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
                      <Briefcase className="w-5 h-5 text-green-600" />
                    </div>
                    <div>
                      <p className="text-xs text-slate-500">Partners</p>
                      <p className="text-2xl font-bold text-[#1C323E]">{totalPartnerCount}</p>
                    </div>
                  </div>
                  <Button 
                    variant="outline" 
                    size="sm" 
                    className="w-full text-xs border-slate-300"
                    onClick={() => {
                      const partnersSection = document.getElementById('partners-section');
                      partnersSection?.scrollIntoView({ behavior: 'smooth' });
                    }}
                  >
                    View Partners
                  </Button>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Partners Grid/List */}
        <div id="partners-section">
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-2xl font-bold text-[#1C323E] flex items-center gap-2">
              <Briefcase className="w-6 h-6 text-[#0A39DF]" />
              Partner Directory
            </h2>
            <div className="flex items-center gap-2">
              <Button 
                variant={viewMode === "grid" ? "default" : "outline"} 
                size="icon" 
                onClick={() => setViewMode("grid")}
                className={viewMode === "grid" ? "bg-[#0A39DF] hover:bg-[#0A39DF]/90" : "border-slate-300 text-slate-500 hover:text-[#0A39DF]"}
              >
                <LayoutGrid className="w-5 h-5" />
              </Button>
              <Button 
                variant={viewMode === "list" ? "default" : "outline"} 
                size="icon" 
                onClick={() => setViewMode("list")}
                className={viewMode === "list" ? "bg-[#0A39DF] hover:bg-[#0A39DF]/90" : "border-slate-300 text-slate-500 hover:text-[#0A39DF]"}
              >
                <List className="w-5 h-5" />
              </Button>
            </div>
          </div>
          {isLoading ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {[...Array(6)].map((_, i) => (
                <div key={i} className="h-64 bg-slate-100 animate-pulse rounded-xl" />
              ))}
            </div>
          ) : (filteredPartners.length > 0 || filteredBusinesses.length > 0) ? (
            <>
              {/* Grid View */}
              {viewMode === "grid" && (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  {/* Display Businesses from Business Directory */}
                  {filteredBusinesses.map((business, idx) => (
                    <Card key={`business-${idx}`} className="border-2 border-slate-200 hover:border-[#0A39DF] hover:shadow-xl transition-all">
                      <CardContent className="p-6">
                        <div className="flex items-start gap-4 mb-4">
                          <div className="w-14 h-14 rounded-xl flex items-center justify-center overflow-hidden bg-white border-2 border-slate-200 flex-shrink-0">
                            {business.company_logo ? (
                              <img 
                                src={business.company_logo} 
                                alt={business.company_name}
                                className="w-full h-full object-contain p-2"
                              />
                            ) : (
                              <div className="w-full h-full bg-gradient-to-br from-green-500 to-green-700 rounded-lg flex items-center justify-center text-white font-bold text-xl">
                                {business.company_name?.charAt(0) || 'B'}
                              </div>
                            )}
                          </div>
                          <div className="flex-1 min-w-0">
                            <h3 className="font-bold text-xl text-[#1C323E] mb-1 truncate">
                              {business.company_name}
                            </h3>
                            <p className="text-sm text-slate-500">PN-{String(idx + 1000).padStart(4, '0')}</p>
                          </div>
                          <Link to={createPageUrl("Business")}>
                            <Button variant="ghost" size="icon" className="text-slate-400 hover:text-[#0A39DF] hover:bg-blue-50 flex-shrink-0">
                              <Edit className="w-4 h-4" />
                            </Button>
                          </Link>
                        </div>

                        <div className="space-y-2">
                          <div className="flex items-center justify-between py-1">
                            <span className="text-sm text-slate-600">Type</span>
                            <span className="font-semibold text-sm text-[#1C323E]">{business.partner_type}</span>
                          </div>
                          
                          <div className="flex items-center justify-between py-1">
                            <span className="text-sm text-slate-600">Sector</span>
                            <span className="font-semibold text-sm text-[#1C323E]">{business.sector || '—'}</span>
                          </div>

                          <div className="flex items-center justify-between py-1">
                            <span className="text-sm text-slate-600 flex items-center gap-1">
                              <MapPin className="w-3 h-3" />
                              Sites
                            </span>
                            <span className="font-semibold text-[#1C323E]">{business.total_hubs}</span>
                          </div>

                          <div className="flex items-center justify-between py-1">
                            <span className="text-sm text-slate-600 flex items-center gap-1">
                              <DollarSign className="w-3 h-3" />
                              Terms
                            </span>
                            <span className="font-semibold text-[#1C323E]">Net 30</span>
                          </div>
                        </div>

                        <div className="pt-3 mt-3 border-t border-slate-200">
                          <Badge className="bg-green-100 text-green-700">
                            Active
                          </Badge>
                        </div>
                      </CardContent>
                    </Card>
                  ))}

                  {/* Display Traditional Partners */}
                  {filteredPartners.map((partner) => (
                    <Card key={partner.id} className="border-2 border-slate-200 hover:border-[#0A39DF] hover:shadow-xl transition-all">
                      <CardContent className="p-6">
                        <div className="flex items-start gap-4 mb-4">
                          <div className="w-14 h-14 bg-gradient-to-br from-green-500 to-green-700 rounded-xl flex items-center justify-center text-white flex-shrink-0">
                            <Briefcase className="w-7 h-7" />
                          </div>
                          <div className="flex-1 min-w-0">
                            <h3 className="font-bold text-xl text-[#1C323E] mb-1 truncate">
                              {partner.partner_name}
                            </h3>
                            <p className="text-sm text-slate-500">{partner.partner_number}</p>
                          </div>
                          <Link to={createPageUrl(`EditPartner?id=${partner.id}`)}>
                            <Button variant="ghost" size="icon" className="text-slate-400 hover:text-[#0A39DF] hover:bg-blue-50 flex-shrink-0">
                              <Edit className="w-4 h-4" />
                            </Button>
                          </Link>
                        </div>

                        <div className="space-y-2">
                          <div className="flex items-center justify-between py-1">
                            <span className="text-sm text-slate-600">Type</span>
                            <span className="font-semibold text-sm text-[#1C323E]">{partner.partner_type}</span>
                          </div>

                          <div className="flex items-center justify-between py-1">
                            <span className="text-sm text-slate-600">Sector</span>
                            <span className="font-semibold text-sm text-[#1C323E]">{partner.sector_name || '—'}</span>
                          </div>

                          <div className="flex items-center justify-between py-1">
                            <span className="text-sm text-slate-600 flex items-center gap-1">
                              <MapPin className="w-3 h-3" />
                              Sites
                            </span>
                            <span className="font-semibold text-[#1C323E]">{partner.sites?.length || 0}</span>
                          </div>

                          <div className="flex items-center justify-between py-1">
                            <span className="text-sm text-slate-600 flex items-center gap-1">
                              <DollarSign className="w-3 h-3" />
                              Terms
                            </span>
                            <span className="font-semibold text-[#1C323E]">{partner.payment_terms || 'Net 30'}</span>
                          </div>
                        </div>

                        <div className="pt-3 mt-3 border-t border-slate-200">
                          <Badge className={partner.is_active ? "bg-green-100 text-green-700" : "bg-slate-100 text-slate-700"}>
                            {partner.is_active ? "Active" : "Inactive"}
                          </Badge>
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              )}

              {/* List View */}
              {viewMode === "list" && (
                <Card className="border-slate-200 shadow-lg">
                  <CardContent className="p-0">
                    <div className="overflow-x-auto">
                      <table className="w-full">
                        <thead className="bg-slate-50 border-b-2 border-slate-200">
                          <tr>
                            <th className="text-left py-4 px-4 font-semibold text-sm text-slate-700">Partner Name</th>
                            <th className="text-left py-4 px-4 font-semibold text-sm text-slate-700">Type</th>
                            <th className="text-left py-4 px-4 font-semibold text-sm text-slate-700">Sector</th>
                            <th className="text-center py-4 px-4 font-semibold text-sm text-slate-700">Hubs/Sites</th>
                            <th className="text-left py-4 px-4 font-semibold text-sm text-slate-700">Contact</th>
                            <th className="text-center py-4 px-4 font-semibold text-sm text-slate-700">Status</th>
                            <th className="text-center py-4 px-4 font-semibold text-sm text-slate-700">Actions</th>
                          </tr>
                        </thead>
                        <tbody>
                          {/* Display Businesses from Business Directory */}
                          {filteredBusinesses.map((business, idx) => (
                            <tr key={`business-${idx}`} className="border-b border-slate-100 hover:bg-slate-50 transition-colors">
                              <td className="py-4 px-4">
                                <div className="flex items-center gap-3">
                                  <div className="w-10 h-10 rounded-lg flex items-center justify-center overflow-hidden bg-white border-2 border-slate-200 flex-shrink-0">
                                    {business.company_logo ? (
                                      <img 
                                        src={business.company_logo} 
                                        alt={business.company_name}
                                        className="w-full h-full object-contain p-1"
                                      />
                                    ) : (
                                      <div className="w-full h-full bg-gradient-to-br from-blue-500 to-blue-700 rounded-lg flex items-center justify-center text-white font-bold text-sm">
                                        {business.company_name?.charAt(0) || 'B'}
                                      </div>
                                    )}
                                  </div>
                                  <div>
                                    <p className="font-semibold text-[#1C323E]">{business.company_name}</p>
                                    <Badge variant="outline" className="text-xs mt-1">From Business Directory</Badge>
                                  </div>
                                </div>
                              </td>
                              <td className="py-4 px-4 text-sm text-slate-700">{business.partner_type}</td>
                              <td className="py-4 px-4 text-sm text-slate-700">{business.sector || '—'}</td>
                              <td className="py-4 px-4 text-center">
                                <Badge className="bg-blue-100 text-blue-700 font-semibold">
                                  {business.total_hubs}
                                </Badge>
                              </td>
                              <td className="py-4 px-4 text-sm text-slate-700">{business.primary_contact || '—'}</td>
                              <td className="py-4 px-4 text-center">
                                <Badge className="bg-green-100 text-green-700">Active</Badge>
                              </td>
                              <td className="py-4 px-4 text-center">
                                <Link to={createPageUrl("Business")}>
                                  <Button variant="outline" size="sm">
                                    <Edit className="w-4 h-4 mr-2" />
                                    Edit
                                  </Button>
                                </Link>
                              </td>
                            </tr>
                          ))}

                          {/* Display Traditional Partners */}
                          {filteredPartners.map((partner) => (
                            <tr key={partner.id} className="border-b border-slate-100 hover:bg-slate-50 transition-colors">
                              <td className="py-4 px-4">
                                <div className="flex items-center gap-3">
                                  <div className="w-10 h-10 bg-gradient-to-br from-green-500 to-green-700 rounded-lg flex items-center justify-center text-white flex-shrink-0">
                                    <Briefcase className="w-5 h-5" />
                                  </div>
                                  <div>
                                    <p className="font-semibold text-[#1C323E]">{partner.partner_name}</p>
                                    <p className="text-xs text-slate-500">{partner.partner_number}</p>
                                  </div>
                                </div>
                              </td>
                              <td className="py-4 px-4 text-sm text-slate-700">{partner.partner_type}</td>
                              <td className="py-4 px-4 text-sm text-slate-700">{partner.sector_name || '—'}</td>
                              <td className="py-4 px-4 text-center">
                                <Badge className="bg-purple-100 text-purple-700 font-semibold">
                                  {partner.sites?.length || 0}
                                </Badge>
                              </td>
                              <td className="py-4 px-4 text-sm text-slate-700">{partner.primary_contact_name || '—'}</td>
                              <td className="py-4 px-4 text-center">
                                <Badge className={partner.is_active ? "bg-green-100 text-green-700" : "bg-slate-100 text-slate-700"}>
                                  {partner.is_active ? "Active" : "Inactive"}
                                </Badge>
                              </td>
                              <td className="py-4 px-4 text-center">
                                <Link to={createPageUrl(`EditPartner?id=${partner.id}`)}>
                                  <Button variant="outline" size="sm">
                                    <Edit className="w-4 h-4 mr-2" />
                                    Edit
                                  </Button>
                                </Link>
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </CardContent>
                </Card>
              )}
            </>
          ) : (
            <Card className="border-slate-200">
              <CardContent className="p-12 text-center">
                <Briefcase className="w-16 h-16 mx-auto text-slate-300 mb-4" />
                <h3 className="text-xl font-semibold text-slate-700 mb-2">No Partners Found</h3>
                <p className="text-slate-500 mb-6">Add your first partner client</p>
                <Link to={createPageUrl("AddPartner")}>
                  <Button className="bg-[#0A39DF] hover:bg-[#0A39DF]/90">
                    <Plus className="w-4 h-4 mr-2" />
                    Add First Partner
                  </Button>
                </Link>
              </CardContent>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}
