import { Button } from "@/common/components/ui/button";
import { Card, CardContent } from "@/common/components/ui/card";
import { Input } from "@/common/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/common/components/ui/select";
import { Badge } from "@/common/components/ui/badge";
import DashboardLayout from "@/features/layouts/DashboardLayout";
import {
  Building2,
  Plus,
  Search,
  ExternalLink,
  Layers,
  Activity
} from "lucide-react";
import { useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useSelector } from "react-redux";
import type { RootState } from "@/store/store";
import { useListBusinesses, useListTeamHubs, useListOrders } from "@/dataconnect-generated/react";
import { dataConnect } from "@/features/auth/firebase";
import { format } from "date-fns";

export default function ClientList() {
  const navigate = useNavigate();
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [industryFilter, setIndustryFilter] = useState("all");
  
  const { user } = useSelector((state: RootState) => state.auth);
  const isAdmin = user?.userRole === 'admin' || user?.userRole === 'ADMIN';

  const { data: businessData, isLoading: loadingBusinesses } = useListBusinesses(dataConnect);
  const { data: hubData, isLoading: loadingHubs } = useListTeamHubs(dataConnect);
  const { data: orderData, isLoading: loadingOrders } = useListOrders(dataConnect);

  const isLoading = loadingBusinesses || loadingHubs || loadingOrders;

  const businesses = businessData?.businesses || [];
  const hubs = hubData?.teamHubs || [];
  const orders = orderData?.orders || [];

  const industries = useMemo(() => {
    return [...new Set(businesses.map(b => b.sector).filter(Boolean))];
  }, [businesses]);

  const processedClients = useMemo(() => {
    return businesses.map(business => {
      const businessHubs = hubs.filter(h => h.teamId === business.id);
      const businessOrders = orders.filter(o => o.businessId === business.id);
      const lastOrder = businessOrders.length > 0 
        ? [...businessOrders].sort((a, b) => {
            const timeA = a.createdAt ? new Date(a.createdAt).getTime() : 0;
            const timeB = b.createdAt ? new Date(b.createdAt).getTime() : 0;
            return timeB - timeA;
          })[0]
        : null;

      return {
        ...business,
        hubCount: businessHubs.length,
        lastOrderDate: lastOrder ? lastOrder.createdAt : null
      };
    });
  }, [businesses, hubs, orders]);

  const filteredClients = useMemo(() => {
    return processedClients.filter(client => {
      const matchesSearch = client.businessName?.toLowerCase().includes(searchTerm.toLowerCase());
      const matchesStatus = statusFilter === "all" || client.status === statusFilter;
      const matchesIndustry = industryFilter === "all" || client.sector === industryFilter;
      return matchesSearch && matchesStatus && matchesIndustry;
    });
  }, [processedClients, searchTerm, statusFilter, industryFilter]);

  if (!isAdmin) {
    return (
      <DashboardLayout title="Access Denied" subtitle="Unauthorized Access">
        <div className="flex flex-col items-center justify-center min-h-[40vh] text-center">
          <div className="w-16 h-16 bg-destructive/10 rounded-full flex items-center justify-center text-destructive mb-4">
            <Activity className="w-8 h-8" />
          </div>
          <h2 className="text-2xl font-bold">Restricted Access</h2>
          <p className="text-muted-foreground mt-2 max-w-sm">Only administrators are authorized to view and manage business client records.</p>
          <Button onClick={() => navigate("/")} variant="outline" className="mt-6 rounded-xl font-bold">
            Return to Dashboard
          </Button>
        </div>
      </DashboardLayout>
    );
  }

  return (
    <DashboardLayout
      title="Business Clients"
      subtitle="Manage and monitor all business accounts"
      actions={
        <Button
          onClick={() => navigate("/clients/add")}
          leadingIcon={<Plus />}
        >
          Add Client
        </Button>
      }
    >
      <div className="space-y-6">
        {/* KPI Summary */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <Card className="bg-card/50 backdrop-blur-sm border-border/50">
            <CardContent className="p-6">
              <div className="flex items-center gap-4">
                <div className="p-3 bg-primary/10 rounded-xl text-primary">
                  <Building2 className="w-6 h-6" />
                </div>
                <div>
                  <p className="text-sm text-muted-foreground font-medium">Total Clients</p>
                  <p className="text-2xl font-bold">{businesses.length}</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card className="bg-card/50 backdrop-blur-sm border-border/50">
            <CardContent className="p-6">
              <div className="flex items-center gap-4">
                <div className="p-3 bg-emerald-500/10 rounded-xl text-emerald-600">
                  <Activity className="w-6 h-6" />
                </div>
                <div>
                  <p className="text-sm text-muted-foreground font-medium">Active Hubs</p>
                  <p className="text-2xl font-bold">{hubs.length}</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card className="bg-card/50 backdrop-blur-sm border-border/50">
            <CardContent className="p-6">
              <div className="flex items-center gap-4">
                <div className="p-3 bg-blue-500/10 rounded-xl text-blue-600">
                  <Layers className="w-6 h-6" />
                </div>
                <div>
                  <p className="text-sm text-muted-foreground font-medium">Total Orders</p>
                  <p className="text-2xl font-bold">{orders.length}</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Filters */}
        <div className="flex flex-col md:flex-row gap-4 items-center">
          <div className="relative flex-1 w-full">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <Input
              placeholder="Search by business name..."
              className="pl-10"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
          </div>
          <div className="flex gap-2 w-full md:w-auto">
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-[150px]">
                <SelectValue placeholder="Status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Statuses</SelectItem>
                <SelectItem value="ACTIVE">Active</SelectItem>
                <SelectItem value="PENDING">Pending</SelectItem>
                <SelectItem value="SUSPENDED">Suspended</SelectItem>
              </SelectContent>
            </Select>
            <Select value={industryFilter} onValueChange={setIndustryFilter}>
              <SelectTrigger className="w-[180px]">
                <SelectValue placeholder="Industry" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Industries</SelectItem>
                {industries.map(industry => (
                  <SelectItem key={industry} value={industry}>{industry}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>

        {/* Table View */}
        <div className="bg-card/50 backdrop-blur-sm border border-border rounded-2xl overflow-hidden shadow-sm">
          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="border-b border-border bg-muted/30">
                  <th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-muted-foreground">Business Name</th>
                  <th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-muted-foreground text-center">Logo</th>
                  <th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-muted-foreground">Industry</th>
                  <th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-muted-foreground">Status</th>
                  <th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-muted-foreground text-center">Hubs</th>
                  <th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-muted-foreground">Last Order</th>
                  <th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-muted-foreground text-right">Action</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {isLoading ? (
                  <tr>
                    <td colSpan={7} className="px-6 py-12 text-center">
                      <div className="flex flex-col items-center gap-3">
                        <div className="w-8 h-8 border-4 border-primary border-t-transparent rounded-full animate-spin" />
                        <p className="text-sm text-muted-foreground font-medium">Loading clients...</p>
                      </div>
                    </td>
                  </tr>
                ) : filteredClients.length > 0 ? (
                  filteredClients.map((client) => (
                    <tr 
                      key={client.id} 
                      className="hover:bg-muted/40 cursor-pointer transition-colors group"
                      onClick={() => navigate(`/clients/${client.id}/edit`)}
                    >
                      <td className="px-6 py-4">
                        <div className="font-bold text-foreground group-hover:text-primary transition-colors">
                          {client.businessName}
                        </div>
                        <div className="text-xs text-muted-foreground">{client.email}</div>
                      </td>
                      <td className="px-6 py-4">
                        <div className="flex justify-center">
                          <div className="w-10 h-10 rounded-lg bg-muted border border-border overflow-hidden flex items-center justify-center">
                            {client.companyLogoUrl ? (
                              <img src={client.companyLogoUrl} alt={client.businessName} className="w-full h-full object-cover" />
                            ) : (
                              <Building2 className="w-5 h-5 text-muted-foreground" />
                            )}
                          </div>
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        <div className="text-sm font-medium">{client.sector || 'N/A'}</div>
                      </td>
                      <td className="px-6 py-4">
                        <Badge variant={client.status === 'ACTIVE' ? 'success' : client.status === 'INACTIVE' ? 'destructive' : 'secondary'} className="font-bold uppercase text-[10px]">
                          {client.status?.toLowerCase() || 'PENDING'}
                        </Badge>
                      </td>
                      <td className="px-6 py-4 text-center">
                        <div className="text-sm font-bold bg-muted/50 w-8 h-8 rounded-full flex items-center justify-center mx-auto border border-border">
                          {client.hubCount}
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        <div className="text-sm font-medium">
                          {client.lastOrderDate ? format(new Date(client.lastOrderDate), 'MMM d, yyyy') : 'No orders'}
                        </div>
                      </td>
                      <td className="px-6 py-4 text-right">
                        <Button variant="ghost" size="sm" className="rounded-lg h-8 w-8 p-0">
                          <ExternalLink className="w-4 h-4" />
                        </Button>
                      </td>
                    </tr>
                  ))
                ) : (
                  <tr>
                    <td colSpan={7} className="px-6 py-12 text-center">
                      <p className="text-muted-foreground">No business clients found matching your search.</p>
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </DashboardLayout>
  );
}
