
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 { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Plus, Building2, Mail, Phone, MapPin, Search, Eye, Trash2, ChevronDown, ChevronRight } from "lucide-react";
import { Link, useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";
import PageHeader from "@/components/common/PageHeader";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";
import CreateBusinessModal from "@/components/business/CreateBusinessModal";

export default function Business() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("active");
  const [expandedCompanies, setExpandedCompanies] = useState({});
  const [createModalOpen, setCreateModalOpen] = useState(false);

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

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

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

  const createBusinessMutation = useMutation({
    mutationFn: (businessData) => base44.entities.Business.create(businessData),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['businesses'] });
      setCreateModalOpen(false);
    },
  });

  const handleCreateBusiness = (businessData) => {
    createBusinessMutation.mutate(businessData);
  };

  // Consolidate businesses by company name
  const consolidatedBusinesses = useMemo(() => {
    const grouped = {};
    
    businesses.forEach(business => {
      // Extract company name (remove hub suffix if present)
      let companyName = business.business_name;
      
      // Handle cases like "Google - BVG300" or "Nvidia - Building S"
      const dashIndex = companyName.indexOf(' - ');
      if (dashIndex > 0) {
        companyName = companyName.substring(0, dashIndex).trim();
      }
      
      // Initialize company if not exists
      if (!grouped[companyName]) {
        grouped[companyName] = {
          company_name: companyName,
          hubs: [],
          primary_contact: business.contact_name,
          primary_email: business.email,
          primary_phone: business.phone,
          sector: business.notes?.includes('Sector:') ? business.notes.split('Sector:')[1].trim() : '',
        };
      }
      
      // Add hub
      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,
        notes: business.notes,
      });
    });
    
    return Object.values(grouped);
  }, [businesses]);

  const filteredBusinesses = consolidatedBusinesses.filter(company => {
    const matchesSearch = !searchTerm || 
      company.company_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      company.hubs.some(hub => 
        hub.hub_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        hub.contact_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        hub.address?.toLowerCase().includes(searchTerm.toLowerCase())
      );
    
    return matchesSearch;
  });

  const toggleCompany = (companyName) => {
    setExpandedCompanies(prev => ({
      ...prev,
      [companyName]: !prev[companyName]
    }));
  };

  const canAddBusiness = ["admin", "procurement", "operator", "vendor"].includes(userRole);

  const totalHubs = filteredBusinesses.reduce((sum, company) => sum + company.hubs.length, 0);

  return (
    <div className="p-4 md:p-8 bg-slate-50 min-h-screen">
      <div className="max-w-7xl mx-auto">
        <PageHeader 
          title="Business Directory"
          subtitle={`${filteredBusinesses.length} ${filteredBusinesses.length === 1 ? 'company' : 'companies'} • ${totalHubs} total hubs`}
          actions={
            canAddBusiness ? (
              <Button 
                onClick={() => setCreateModalOpen(true)}
                className="bg-gradient-to-r from-[#0A39DF] to-[#1C323E] hover:from-[#0A39DF]/90 hover:to-[#1C323E]/90 text-white shadow-lg"
              >
                <Plus className="w-5 h-5 mr-2" />
                Add Business
              </Button>
            ) : null
          }
        />

        {/* Status Tabs */}
        <Tabs value={statusFilter} onValueChange={setStatusFilter} className="mb-6">
          <TabsList className="bg-white border border-slate-200">
            <TabsTrigger value="active" className="data-[state=active]:bg-[#0A39DF] data-[state=active]:text-white">
              Active
              <Badge variant="secondary" className="ml-2 bg-slate-100 text-slate-700">
                {filteredBusinesses.length}
              </Badge>
            </TabsTrigger>
            <TabsTrigger value="pending">
              Pending
              <Badge variant="secondary" className="ml-2 bg-slate-100 text-slate-700">
                0
              </Badge>
            </TabsTrigger>
            <TabsTrigger value="deactivated">
              Deactivated
              <Badge variant="secondary" className="ml-2 bg-slate-100 text-slate-700">
                0
              </Badge>
            </TabsTrigger>
          </TabsList>
        </Tabs>

        {/* Search Bar */}
        <div className="mb-6">
          <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 companies, hubs, or contacts..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10 bg-white border-slate-200"
            />
          </div>
        </div>

        {/* Consolidated Business List */}
        {filteredBusinesses.length > 0 ? (
          <div className="space-y-4">
            {filteredBusinesses.map((company) => (
              <Card key={company.company_name} className="border-slate-200 shadow-sm overflow-hidden">
                <Collapsible 
                  open={expandedCompanies[company.company_name]}
                  onOpenChange={() => toggleCompany(company.company_name)}
                >
                  <div className="bg-gradient-to-r from-slate-50 to-white border-b border-slate-200">
                    <CollapsibleTrigger className="w-full">
                      <div className="p-6 flex items-center justify-between hover:bg-slate-50/50 transition-colors">
                        <div className="flex items-center gap-4">
                          {expandedCompanies[company.company_name] ? (
                            <ChevronDown className="w-5 h-5 text-slate-400" />
                          ) : (
                            <ChevronRight className="w-5 h-5 text-slate-400" />
                          )}
                          <div className="w-12 h-12 bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl flex items-center justify-center text-white font-bold text-xl">
                            {company.company_name?.charAt(0) || 'B'}
                          </div>
                          <div className="text-left">
                            <h3 className="text-xl font-bold text-[#1C323E]">{company.company_name}</h3>
                            <div className="flex items-center gap-4 mt-1 text-sm text-slate-500">
                              <span className="flex items-center gap-1">
                                <Building2 className="w-4 h-4" />
                                {company.hubs.length} {company.hubs.length === 1 ? 'hub' : 'hubs'}
                              </span>
                              {company.sector && (
                                <Badge variant="outline" className="text-xs">
                                  {company.sector}
                                </Badge>
                              )}
                            </div>
                          </div>
                        </div>
                        <div className="text-right">
                          <div className="text-sm font-medium text-slate-700">
                            {company.primary_contact || '—'}
                          </div>
                          {company.primary_email && (
                            <div className="text-xs text-slate-500 flex items-center justify-end gap-1 mt-1">
                              <Mail className="w-3 h-3" />
                              {company.primary_email}
                            </div>
                          )}
                          {company.primary_phone && (
                            <div className="text-xs text-slate-500 flex items-center justify-end gap-1 mt-1">
                              <Phone className="w-3 h-3" />
                              {company.primary_phone}
                            </div>
                          )}
                        </div>
                      </div>
                    </CollapsibleTrigger>
                  </div>

                  <CollapsibleContent>
                    <div className="bg-white">
                      <table className="w-full">
                        <thead className="bg-slate-50 border-b border-slate-200">
                          <tr>
                            <th className="text-left py-3 px-6 font-semibold text-xs text-slate-600">Hub Name</th>
                            <th className="text-left py-3 px-6 font-semibold text-xs text-slate-600">Contact</th>
                            <th className="text-left py-3 px-6 font-semibold text-xs text-slate-600">Address</th>
                            <th className="text-left py-3 px-6 font-semibold text-xs text-slate-600">City</th>
                            <th className="text-center py-3 px-6 font-semibold text-xs text-slate-600">Actions</th>
                          </tr>
                        </thead>
                        <tbody>
                          {company.hubs.map((hub, idx) => (
                            <tr 
                              key={hub.id}
                              className={`border-b border-slate-100 hover:bg-slate-50 transition-colors ${
                                idx % 2 === 0 ? 'bg-white' : 'bg-slate-50/30'
                              }`}
                            >
                              <td className="py-4 px-6">
                                <div className="flex items-center gap-2">
                                  <MapPin className="w-4 h-4 text-blue-500" />
                                  <span className="font-medium text-sm text-slate-900">{hub.hub_name}</span>
                                </div>
                              </td>
                              <td className="py-4 px-6">
                                <div className="text-sm">
                                  <p className="font-medium text-slate-900">{hub.contact_name || '—'}</p>
                                  {hub.email && (
                                    <p className="text-xs text-slate-500 flex items-center gap-1 mt-0.5">
                                      <Mail className="w-3 h-3" />
                                      {hub.email}
                                    </p>
                                  )}
                                  {hub.phone && (
                                    <p className="text-xs text-slate-500 flex items-center gap-1 mt-0.5">
                                      <Phone className="w-3 h-3" />
                                      {hub.phone}
                                    </p>
                                  )}
                                </div>
                              </td>
                              <td className="py-4 px-6">
                                <p className="text-sm text-slate-600">{hub.address || '—'}</p>
                              </td>
                              <td className="py-4 px-6">
                                <p className="text-sm text-slate-600">{hub.city || '—'}</p>
                              </td>
                              <td className="py-4 px-6">
                                <div className="flex items-center justify-center gap-2">
                                  <Button
                                    variant="ghost"
                                    size="icon"
                                    onClick={() => navigate(createPageUrl(`EditBusiness?id=${hub.id}`))}
                                    className="text-slate-400 hover:text-blue-600 hover:bg-blue-50 h-8 w-8"
                                    title="View/Edit Hub"
                                  >
                                    <Eye className="w-4 h-4" />
                                  </Button>
                                  <Button
                                    variant="ghost"
                                    size="icon"
                                    className="text-slate-400 hover:text-red-600 hover:bg-red-50 h-8 w-8"
                                    title="Delete Hub"
                                  >
                                    <Trash2 className="w-4 h-4" />
                                  </Button>
                                </div>
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </CollapsibleContent>
                </Collapsible>
              </Card>
            ))}
          </div>
        ) : (
          <div className="text-center py-16 bg-white rounded-xl border border-slate-200">
            <Building2 className="w-16 h-16 mx-auto text-slate-300 mb-4" />
            <h3 className="text-xl font-semibold text-slate-900 mb-2">
              {searchTerm ? "No businesses found" : "No business clients yet"}
            </h3>
            <p className="text-slate-600 mb-6">
              {searchTerm ? "Try adjusting your search" : "Get started by adding your first business"}
            </p>
            {canAddBusiness && !searchTerm && (
              <Button 
                onClick={() => setCreateModalOpen(true)}
                className="bg-gradient-to-r from-[#0A39DF] to-[#1C323E] hover:from-[#0A39DF]/90 hover:to-[#1C323E]/90 text-white"
              >
                <Plus className="w-4 h-4 mr-2" />
                Add First Business
              </Button>
            )}
          </div>
        )}
      </div>
      {/* Create Business Modal */}
      <CreateBusinessModal
        open={createModalOpen}
        onOpenChange={setCreateModalOpen}
        onSubmit={handleCreateBusiness}
        isSubmitting={createBusinessMutation.isPending}
      />
    </div>
  );
}
