import React, { useState, useMemo, useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
import { 
  Users, 
  Plus, 
  Search, 
  Filter, 
  MoreHorizontal, 
  Building2, 
  Mail, 
  Phone, 
  Globe,
  ExternalLink,
  Briefcase,
  DollarSign,
  UserCheck,
  X,
  Edit,
  Trash2,
  LayoutGrid,
  List,
  ChevronRight,
  Calendar,
  Clock,
  CheckCircle2,
  AlertCircle,
  Download,
  Upload
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { useApp, Client, Project, ClientContact } from '@/context/AppContext';
import { useAuth } from '@/context/AuthContext';
import { motion, AnimatePresence } from 'framer-motion';

export function Clients() {
  const [searchParams] = useSearchParams();
  const { clients, projects, tasks, addClient, updateClient, deleteClient } = useApp();
  const { hasPermission } = useAuth();
  const [searchQuery, setSearchQuery] = useState(searchParams.get('search') || '');
  
  useEffect(() => {
    const search = searchParams.get('search');
    if (search) {
      setSearchQuery(search);
    }
  }, [searchParams]);

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [viewMode, setViewMode] = useState<'grid' | 'table'>('grid');
  const [selectedClient, setSelectedClient] = useState<Client | null>(null);
  const [editingClient, setEditingClient] = useState<Client | null>(null);
  const [statusFilter, setStatusFilter] = useState<string>('All');
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [clientToDelete, setClientToDelete] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  
  const [newClient, setNewClient] = useState<Partial<Client>>({
    name: '',
    industry: '',
    contactPerson: '',
    email: '',
    phone: '',
    status: 'Onboarding',
    projects: 0,
    revenue: 0,
    website: '',
    contacts: []
  });

  // Calculate dynamic data for clients
  const handleExportCSV = () => {
    if (clients.length === 0) {
      toast.error('No clients to export');
      return;
    }

    const headers = ['ID', 'Name', 'Industry', 'Contact Person', 'Email', 'Phone', 'Status', 'Website'];
    const csvRows = [
      headers.join(','),
      ...clients.map(c => [
        `"${c.id}"`,
        `"${c.name}"`,
        `"${c.industry}"`,
        `"${c.contactPerson}"`,
        `"${c.email}"`,
        `"${c.phone}"`,
        `"${c.status}"`,
        `"${c.website || ''}"`
      ].join(','))
    ];

    const csvContent = csvRows.join('\n');
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.setAttribute('href', url);
    link.setAttribute('download', `clients_export_${new Date().toISOString().split('T')[0]}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    toast.success('Clients exported successfully');
  };

  const handleImportCSV = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file || isSubmitting) return;

    setIsSubmitting(true);
    const reader = new FileReader();
    reader.onload = async (event) => {
      try {
        const text = event.target?.result as string;
        const rows = text.split('\n').filter(row => row.trim() !== '');
        if (rows.length < 2) {
          toast.error('Invalid CSV file format');
          return;
        }

        const newClients: any[] = [];
        for (let i = 1; i < rows.length; i++) {
          const matches = rows[i].match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g);
          if (!matches || matches.length < 7) continue;

          const clean = (val: string) => val.replace(/^"|"$/g, '').trim();
          
          const client = {
            id: clean(matches[0]),
            name: clean(matches[1]),
            industry: clean(matches[2]),
            contactPerson: clean(matches[3]),
            email: clean(matches[4]),
            phone: clean(matches[5]),
            status: clean(matches[6]) as any,
            website: matches[7] ? clean(matches[7]) : '',
            projects: 0,
            revenue: 0,
            contacts: []
          };
          newClients.push(client);
        }

        if (newClients.length === 0) {
          toast.error('No valid data found in CSV');
          return;
        }

        const existingIds = new Set(clients.map(c => c.id));
        const uniqueNew = newClients.filter(c => !existingIds.has(c.id));
        
        if (uniqueNew.length === 0) {
          toast.info('All records in CSV already exist');
        } else {
          for (const client of uniqueNew) {
            await addClient(client);
          }
          toast.success(`Successfully imported ${uniqueNew.length} new clients`);
        }
      } catch (error) {
        console.error('Import error:', error);
        toast.error('Failed to parse CSV file');
      } finally {
        setIsSubmitting(false);
        if (e.target) e.target.value = '';
      }
    };
    reader.readAsText(file);
  };

  const clientsWithData = useMemo(() => {
    return clients.map(client => {
      const clientProjects = projects.filter(p => p.client === client.name);
      const totalRevenue = clientProjects.reduce((sum, p) => sum + (p.clientTotalAmount || 0), 0);
      
      return {
        ...client,
        projectsCount: clientProjects.length,
        actualRevenue: totalRevenue > 0 ? totalRevenue : client.revenue
      };
    });
  }, [clients, projects]);

  const filteredClients = clientsWithData.filter(c => {
    const matchesSearch = c.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         c.industry.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         c.id.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesStatus = statusFilter === 'All' || c.status === statusFilter;
    return matchesSearch && matchesStatus;
  });

  const stats = useMemo(() => {
    const totalClients = clients.length;
    const activeProjects = projects.filter(p => p.status !== 'Completed' && p.status !== 'Cancelled').length;
    const totalRevenue = projects.reduce((acc, p) => acc + (p.clientTotalAmount || 0), 0);
    const activeClients = clients.filter(c => c.status === 'Active').length;
    const retentionRate = totalClients > 0 ? Math.round((activeClients / totalClients) * 100) : 0;

    return { totalClients, activeProjects, totalRevenue, retentionRate };
  }, [clients, projects]);

  const handleAddClient = async (e: React.FormEvent) => {
    e.preventDefault();
    if (isSubmitting) return;
    
    setIsSubmitting(true);
    try {
      if (editingClient) {
        await updateClient(editingClient.id, newClient);
        toast.success('Client updated successfully');
      } else {
        const client: Client = {
          id: `CL-${Math.floor(Math.random() * 10000).toString().padStart(3, '0')}`,
          name: newClient.name || 'New Client',
          industry: newClient.industry || 'Consulting',
          contactPerson: newClient.contactPerson || '',
          email: newClient.email || '',
          phone: newClient.phone || '',
          status: (newClient.status as any) || 'Onboarding',
          projects: 0,
          revenue: Number(newClient.revenue) || 0,
          website: newClient.website,
          contacts: []
        };
        await addClient(client);
        toast.success('Client added successfully');
      }

      setIsModalOpen(false);
      setEditingClient(null);
      setNewClient({
        name: '',
        industry: '',
        contactPerson: '',
        email: '',
        phone: '',
        status: 'Onboarding',
        projects: 0,
        revenue: 0,
        website: '',
        contacts: []
      });
    } catch (error) {
      console.error('Save client error:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleEdit = (client: Client) => {
    // Strip calculated fields added by useMemo before setting to state
    const { projectsCount, actualRevenue, ...clientData } = client as any;
    setEditingClient(clientData);
    setNewClient(clientData);
    setIsModalOpen(true);
  };

  const handleDeleteClick = (id: string) => {
    setClientToDelete(id);
    setIsDeleteModalOpen(true);
  };

  const confirmDelete = async () => {
    if (clientToDelete && !isSubmitting) {
      setIsSubmitting(true);
      try {
        await deleteClient(clientToDelete);
        toast.success('Client deleted');
        if (selectedClient?.id === clientToDelete) setSelectedClient(null);
        setIsDeleteModalOpen(false);
        setClientToDelete(null);
      } catch (error) {
        console.error('Delete client error:', error);
      } finally {
        setIsSubmitting(false);
      }
    }
  };

  return (
    <div className="space-y-6 pb-12">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Client Management</h1>
          <p className="text-muted-foreground">Maintain relationships and track client-specific metrics.</p>
        </div>
        <div className="flex items-center gap-3">
          {hasPermission('crm.create') && (
            <div className="relative">
              <input 
                type="file" 
                accept=".csv"
                className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                onChange={handleImportCSV}
              />
              <button className="flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors">
                <Upload size={18} />
                Import CSV
              </button>
            </div>
          )}
          {hasPermission('crm.export') && (
            <button 
              onClick={handleExportCSV}
              className="flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
            >
              <Download size={18} />
              Export CSV
            </button>
          )}
          {hasPermission('crm.create') && (
            <button 
              onClick={() => setIsModalOpen(true)}
              className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors w-fit shadow-sm"
            >
              <Plus size={18} />
              Add New Client
            </button>
          )}
        </div>
      </div>

      {/* Stats Overview */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard 
          title="Total Clients" 
          value={stats.totalClients.toString()} 
          icon={Users} 
          trend="Total registered" 
          trendColor="text-muted-foreground"
        />
        <StatCard 
          title="Active Projects" 
          value={stats.activeProjects.toString()} 
          icon={Briefcase} 
          trend="Current workload" 
        />
        <StatCard 
          title="Total Revenue" 
          value={`$${stats.totalRevenue.toLocaleString()}`} 
          icon={DollarSign} 
          trend="+12% from Q3" 
          trendColor="text-green-500"
        />
        <StatCard 
          title="Retention Rate" 
          value={`${stats.retentionRate}%`} 
          icon={UserCheck} 
          trend="Active status ratio" 
          trendColor="text-blue-500"
        />
      </div>

      {/* Filters & Search */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center justify-between bg-card p-4 rounded-xl border border-border shadow-sm">
        <div className="flex flex-1 items-center gap-4 max-w-2xl">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={18} />
            <input
              type="text"
              placeholder="Search by name, industry, or ID..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="h-10 w-full rounded-lg border border-border bg-background pl-10 pr-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
            />
          </div>
          <select 
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
            className="h-10 rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 appearance-none cursor-pointer min-w-[120px]"
          >
            <option value="All">All Status</option>
            <option value="Active">Active</option>
            <option value="Onboarding">Onboarding</option>
            <option value="Inactive">Inactive</option>
          </select>
        </div>
        
        <div className="flex items-center gap-2 border-l border-border pl-4 ml-4">
          <button 
            onClick={() => setViewMode('grid')}
            className={cn(
              "p-2 rounded-lg transition-colors",
              viewMode === 'grid' ? "bg-primary text-primary-foreground" : "hover:bg-accent text-muted-foreground"
            )}
            title="Grid View"
          >
            <LayoutGrid size={20} />
          </button>
          <button 
            onClick={() => setViewMode('table')}
            className={cn(
              "p-2 rounded-lg transition-colors",
              viewMode === 'table' ? "bg-primary text-primary-foreground" : "hover:bg-accent text-muted-foreground"
            )}
            title="Table View"
          >
            <List size={20} />
          </button>
        </div>
      </div>

      {/* Clients Content */}
      {viewMode === 'grid' ? (
        <div className="grid gap-6 md:grid-cols-2 xl:grid-cols-3">
          {filteredClients.map((client) => (
            <motion.div 
              layout
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              key={client.id} 
              className="group relative rounded-xl border border-border bg-card p-6 shadow-sm hover:shadow-md transition-all"
            >
              <div className="flex items-start justify-between mb-4">
                <div className="flex items-center gap-4">
                  <div className="h-12 w-12 rounded-lg bg-primary/10 flex items-center justify-center text-primary">
                    <Building2 size={24} />
                  </div>
                  <div>
                    <h3 className="font-bold group-hover:text-primary transition-colors">{client.name}</h3>
                    <p className="text-xs text-muted-foreground">{client.industry}</p>
                  </div>
                </div>
                <div className="flex items-center gap-1">
                  {hasPermission('crm.edit') && (
                    <button 
                      onClick={(e) => { e.stopPropagation(); handleEdit(client); }}
                      className="p-1.5 hover:bg-accent rounded-md text-muted-foreground transition-colors"
                    >
                      <Edit size={16} />
                    </button>
                  )}
                  {hasPermission('crm.delete') && (
                    <button 
                      onClick={(e) => { e.stopPropagation(); handleDeleteClick(client.id); }}
                      className="p-1.5 hover:bg-destructive/10 rounded-md text-destructive transition-colors"
                    >
                      <Trash2 size={16} />
                    </button>
                  )}
                </div>
              </div>

              <div className="space-y-3 mb-6">
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <Mail size={14} />
                  <span className="truncate">{client.email}</span>
                </div>
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <Phone size={14} />
                  <span>{client.phone}</span>
                </div>
                {client.website && (
                  <div className="flex items-center gap-2 text-sm text-muted-foreground">
                    <Globe size={14} />
                    <a 
                      href={client.website.startsWith('http') ? client.website : `https://${client.website}`} 
                      target="_blank" 
                      rel="noopener noreferrer"
                      className="text-primary hover:underline flex items-center gap-1"
                      onClick={(e) => e.stopPropagation()}
                    >
                      Website <ExternalLink size={12} />
                    </a>
                  </div>
                )}
              </div>

              <div className="grid grid-cols-2 gap-4 pt-4 border-t border-border">
                <div>
                  <p className="text-xs text-muted-foreground mb-1">Projects</p>
                  <p className="font-semibold text-lg">{client.projectsCount}</p>
                </div>
                <div>
                  <p className="text-xs text-muted-foreground mb-1">Revenue</p>
                  <p className="font-semibold text-lg">${client.actualRevenue.toLocaleString()}</p>
                </div>
              </div>

              <div className="mt-4 flex items-center justify-between">
                <span className={cn(
                  "inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium",
                  client.status === 'Active' ? "bg-green-500/10 text-green-500" :
                  client.status === 'Onboarding' ? "bg-blue-500/10 text-blue-500" :
                  "bg-muted text-muted-foreground"
                )}>
                  {client.status}
                </span>
                <button 
                  onClick={() => setSelectedClient(client)}
                  className="text-xs font-medium text-primary hover:underline flex items-center gap-1"
                >
                  View Details
                  <ChevronRight size={14} />
                </button>
              </div>
            </motion.div>
          ))}
        </div>
      ) : (
        <div className="rounded-xl border border-border bg-card overflow-hidden shadow-sm">
          <div className="overflow-x-auto">
            <table className="w-full text-left text-sm">
              <thead className="bg-muted/50 border-b border-border">
                <tr>
                  <th className="px-4 py-3 font-medium">Client</th>
                  <th className="px-4 py-3 font-medium">Industry</th>
                  <th className="px-4 py-3 font-medium">Contact</th>
                  <th className="px-4 py-3 font-medium">Projects</th>
                  <th className="px-4 py-3 font-medium">Revenue</th>
                  <th className="px-4 py-3 font-medium">Status</th>
                  <th className="px-4 py-3 font-medium text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {filteredClients.map((client) => (
                  <tr 
                    key={client.id} 
                    className="hover:bg-accent/30 transition-colors cursor-pointer group"
                    onClick={() => setSelectedClient(client)}
                  >
                    <td className="px-4 py-4">
                      <div className="flex items-center gap-3">
                        <div className="h-8 w-8 rounded bg-primary/10 flex items-center justify-center text-primary">
                          <Building2 size={16} />
                        </div>
                        <span className="font-medium">{client.name}</span>
                      </div>
                    </td>
                    <td className="px-4 py-4 text-muted-foreground">{client.industry}</td>
                    <td className="px-4 py-4">
                      <div className="flex flex-col">
                        <span>{client.contactPerson}</span>
                        <span className="text-xs text-muted-foreground">{client.email}</span>
                      </div>
                    </td>
                    <td className="px-4 py-4 font-medium">{client.projectsCount}</td>
                    <td className="px-4 py-4 font-medium">${client.actualRevenue.toLocaleString()}</td>
                    <td className="px-4 py-4">
                      <span className={cn(
                        "inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-medium",
                        client.status === 'Active' ? "bg-green-500/10 text-green-500" :
                        client.status === 'Onboarding' ? "bg-blue-500/10 text-blue-500" :
                        "bg-muted text-muted-foreground"
                      )}>
                        {client.status}
                      </span>
                    </td>
                    <td className="px-4 py-4 text-right">
                      <div className="flex items-center justify-end gap-2" onClick={(e) => e.stopPropagation()}>
                        {hasPermission('crm.edit') && (
                          <button 
                            onClick={() => handleEdit(client)}
                            className="p-1.5 hover:bg-accent rounded-md text-muted-foreground transition-colors"
                          >
                            <Edit size={16} />
                          </button>
                        )}
                        {hasPermission('crm.delete') && (
                          <button 
                            onClick={() => handleDeleteClick(client.id)}
                            className="p-1.5 hover:bg-destructive/10 rounded-md text-destructive transition-colors"
                          >
                            <Trash2 size={16} />
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Client Details Slide-over */}
      <AnimatePresence>
        {selectedClient && (
          <>
            <motion.div 
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setSelectedClient(null)}
              className="fixed inset-0 bg-background/80 backdrop-blur-sm z-[110]"
            />
            <motion.div 
              initial={{ x: '100%' }}
              animate={{ x: 0 }}
              exit={{ x: '100%' }}
              transition={{ type: 'spring', damping: 25, stiffness: 200 }}
              className="fixed right-0 top-0 bottom-0 w-full max-w-xl bg-card border-l border-border z-[120] shadow-2xl overflow-y-auto"
            >
              <div className="p-6">
                <div className="flex items-center justify-between mb-8">
                  <div className="flex items-center gap-4">
                    <div className="h-14 w-14 rounded-xl bg-primary/10 flex items-center justify-center text-primary">
                      <Building2 size={32} />
                    </div>
                    <div>
                      <h2 className="text-2xl font-bold">{selectedClient.name}</h2>
                      <p className="text-muted-foreground">{selectedClient.industry}</p>
                    </div>
                  </div>
                  <button 
                    onClick={() => setSelectedClient(null)}
                    className="p-2 hover:bg-accent rounded-full text-muted-foreground transition-colors"
                  >
                    <X size={24} />
                  </button>
                </div>

                <div className="grid grid-cols-2 gap-6 mb-8">
                  <div className="space-y-4">
                    <h3 className="text-sm font-bold uppercase tracking-wider text-muted-foreground">Contact Information</h3>
                    <div className="space-y-3">
                      <div className="flex items-center gap-3 text-sm">
                        <UserCheck size={16} className="text-primary" />
                        <span>{selectedClient.contactPerson}</span>
                      </div>
                      <div className="flex items-center gap-3 text-sm">
                        <Mail size={16} className="text-primary" />
                        <span>{selectedClient.email}</span>
                      </div>
                      <div className="flex items-center gap-3 text-sm">
                        <Phone size={16} className="text-primary" />
                        <span>{selectedClient.phone}</span>
                      </div>
                      {selectedClient.website && (
                        <div className="flex items-center gap-3 text-sm">
                          <Globe size={16} className="text-primary" />
                          <a href={`https://${selectedClient.website}`} target="_blank" rel="noreferrer" className="text-primary hover:underline">
                            {selectedClient.website}
                          </a>
                        </div>
                      )}
                    </div>
                  </div>
                  <div className="space-y-4">
                    <h3 className="text-sm font-bold uppercase tracking-wider text-muted-foreground">Account Status</h3>
                    <div className="space-y-3 text-sm">
                      <div className="flex items-center justify-between">
                        <span className="text-muted-foreground">Status</span>
                        <span className={cn(
                          "px-2 py-0.5 rounded-full text-xs font-medium",
                          selectedClient.status === 'Active' ? "bg-green-500/10 text-green-500" : "bg-muted text-muted-foreground"
                        )}>{selectedClient.status}</span>
                      </div>
                      <div className="flex items-center justify-between">
                        <span className="text-muted-foreground">Total Revenue</span>
                        <span className="font-bold text-lg">${projects.filter(p => p.client === selectedClient.name).reduce((sum, p) => sum + (p.clientTotalAmount || 0), 0).toLocaleString()}</span>
                      </div>
                      <div className="flex items-center justify-between">
                        <span className="text-muted-foreground">Client Since</span>
                        <span className="font-medium">Jan 2024</span>
                      </div>
                    </div>
                  </div>
                </div>

                <div className="space-y-6 mb-8">
                  <div className="flex items-center justify-between">
                    <h3 className="text-lg font-bold">Client Contacts</h3>
                    {hasPermission('crm.edit') && (
                      <button 
                        disabled={isSubmitting}
                        onClick={async () => {
                          if (isSubmitting) return;
                          const name = prompt('Contact Name:');
                          if (!name) return;
                          const role = prompt('Role:');
                          const email = prompt('Email:');
                          const phone = prompt('Phone:');
                          if (name && email) {
                            setIsSubmitting(true);
                            const newContact: ClientContact = {
                              id: `CON-${Math.random().toString(36).substr(2, 5).toUpperCase()}`,
                              name, role: role || '', email, phone: phone || ''
                            };
                            const updatedContacts = [...(selectedClient.contacts || []), newContact];
                            try {
                              await updateClient(selectedClient.id, { contacts: updatedContacts });
                              setSelectedClient({ ...selectedClient, contacts: updatedContacts });
                              toast.success('Contact added');
                            } catch (error) {
                              console.error('Add contact error:', error);
                            } finally {
                              setIsSubmitting(false);
                            }
                          }
                        }}
                        className="flex items-center gap-1 text-xs font-medium text-primary hover:underline disabled:opacity-50"
                      >
                        <Plus size={14} />
                        {isSubmitting ? 'Adding...' : 'Add Contact'}
                      </button>
                    )}
                  </div>
                  
                  <div className="grid gap-3">
                    <div className="p-3 rounded-lg border border-primary/20 bg-primary/5">
                      <div className="flex items-center justify-between mb-1">
                        <p className="text-sm font-bold">{selectedClient.contactPerson}</p>
                        <span className="text-[10px] px-1.5 py-0.5 rounded bg-primary text-primary-foreground font-bold uppercase">Primary</span>
                      </div>
                      <p className="text-xs text-muted-foreground">{selectedClient.email}</p>
                      <p className="text-xs text-muted-foreground">{selectedClient.phone}</p>
                    </div>
                    
                    {selectedClient.contacts?.map(contact => (
                      <div key={contact.id} className="p-3 rounded-lg border border-border bg-muted/20 group">
                        <div className="flex items-center justify-between mb-1">
                          <div>
                            <p className="text-sm font-bold">{contact.name}</p>
                            <p className="text-[10px] text-muted-foreground">{contact.role}</p>
                          </div>
                          {hasPermission('crm.edit') && (
                            <button 
                              disabled={isSubmitting}
                              onClick={async () => {
                                if (isSubmitting) return;
                                const updatedContacts = selectedClient.contacts?.filter(c => c.id !== contact.id);
                                setIsSubmitting(true);
                                try {
                                  await updateClient(selectedClient.id, { contacts: updatedContacts });
                                  setSelectedClient({ ...selectedClient, contacts: updatedContacts });
                                  toast.error('Contact removed');
                                } catch (error) {
                                  console.error('Remove contact error:', error);
                                } finally {
                                  setIsSubmitting(false);
                                }
                              }}
                              className="opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded text-destructive transition-all disabled:opacity-50"
                            >
                              <Trash2 size={12} />
                            </button>
                          )}
                        </div>
                        <p className="text-xs text-muted-foreground">{contact.email}</p>
                        <p className="text-xs text-muted-foreground">{contact.phone}</p>
                      </div>
                    ))}
                  </div>
                </div>

                <div className="space-y-6">
                  <div className="flex items-center justify-between">
                    <h3 className="text-lg font-bold">Associated Projects</h3>
                    <span className="text-xs font-medium bg-muted px-2 py-1 rounded-md">
                      {projects.filter(p => p.client === selectedClient.name).length} Total
                    </span>
                  </div>
                  
                  <div className="space-y-3">
                    {projects.filter(p => p.client === selectedClient.name).length > 0 ? (
                      projects.filter(p => p.client === selectedClient.name).map(project => (
                        <div key={project.id} className="p-4 rounded-xl border border-border bg-accent/20 hover:bg-accent/40 transition-colors">
                          <div className="flex items-start justify-between mb-2">
                            <div>
                              <p className="font-bold text-sm">{project.name}</p>
                              <p className="text-[10px] text-muted-foreground">{project.id}</p>
                            </div>
                            <span className={cn(
                              "text-[10px] px-2 py-0.5 rounded-full font-medium",
                              project.status === 'Completed' ? "bg-green-500/10 text-green-500" : "bg-blue-500/10 text-blue-500"
                            )}>{project.status}</span>
                          </div>
                          <div className="flex items-center justify-between text-xs text-muted-foreground">
                            <div className="flex items-center gap-1">
                              <Calendar size={12} />
                              <span>Due {project.deadline}</span>
                            </div>
                            <div className="flex items-center gap-1">
                              <DollarSign size={12} />
                              <span className="font-medium text-foreground">${(project.clientTotalAmount || 0).toLocaleString()}</span>
                            </div>
                          </div>
                        </div>
                      ))
                    ) : (
                      <div className="text-center py-12 border-2 border-dashed border-border rounded-xl">
                        <Briefcase className="mx-auto text-muted-foreground mb-2" size={32} />
                        <p className="text-sm text-muted-foreground">No projects found for this client.</p>
                      </div>
                    )}
                  </div>
                </div>

                <div className="mt-12 pt-6 border-t border-border flex items-center gap-4">
                  {hasPermission('crm.edit') && (
                    <button 
                      onClick={() => handleEdit(selectedClient)}
                      className="flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-lg border border-border hover:bg-accent transition-colors text-sm font-medium"
                    >
                      <Edit size={16} />
                      Edit Profile
                    </button>
                  )}
                  {hasPermission('crm.delete') && (
                    <button 
                      onClick={() => handleDeleteClick(selectedClient.id)}
                      className="flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-lg border border-destructive/20 text-destructive hover:bg-destructive/10 transition-colors text-sm font-medium"
                    >
                      <Trash2 size={16} />
                      Delete Client
                    </button>
                  )}
                </div>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>

      {/* Add/Edit Client Modal */}
      {isModalOpen && (
        <div className="fixed inset-0 z-[200] flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm">
          <div className="w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-2xl animate-in fade-in zoom-in duration-200">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-xl font-bold">{editingClient ? 'Edit Client' : 'Add New Client'}</h2>
              <button 
                onClick={() => {
                  setIsModalOpen(false);
                  setEditingClient(null);
                  setNewClient({
                    name: '',
                    industry: '',
                    contactPerson: '',
                    email: '',
                    phone: '',
                    status: 'Onboarding',
                    projects: 0,
                    revenue: 0,
                    website: ''
                  });
                }}
                className="rounded-md p-1 hover:bg-accent text-muted-foreground transition-colors"
              >
                <X size={20} />
              </button>
            </div>

            <form onSubmit={handleAddClient} className="space-y-4">
              <div className="space-y-2">
                <label className="text-sm font-medium">Company Name *</label>
                <input 
                  type="text" 
                  placeholder="e.g. TechFlow Solutions"
                  value={newClient.name || ''}
                  onChange={(e) => setNewClient({...newClient, name: e.target.value})}
                  className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  required
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Industry *</label>
                  <input 
                    type="text" 
                    placeholder="e.g. Technology"
                    value={newClient.industry || ''}
                    onChange={(e) => setNewClient({...newClient, industry: e.target.value})}
                    className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                    required
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Contact Person *</label>
                  <input 
                    type="text" 
                    placeholder="e.g. John Doe"
                    value={newClient.contactPerson || ''}
                    onChange={(e) => setNewClient({...newClient, contactPerson: e.target.value})}
                    className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                    required
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Email *</label>
                  <input 
                    type="email" 
                    placeholder="contact@company.com"
                    value={newClient.email || ''}
                    onChange={(e) => setNewClient({...newClient, email: e.target.value})}
                    className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                    required
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Phone *</label>
                  <input 
                    type="tel" 
                    placeholder="+1 (555) 000-0000"
                    value={newClient.phone || ''}
                    onChange={(e) => setNewClient({...newClient, phone: e.target.value})}
                    className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                    required
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Status</label>
                  <select 
                    value={newClient.status || 'Onboarding'}
                    onChange={(e) => setNewClient({...newClient, status: e.target.value as any})}
                    className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 appearance-none cursor-pointer"
                  >
                    <option value="Active">Active</option>
                    <option value="Onboarding">Onboarding</option>
                    <option value="Inactive">Inactive</option>
                  </select>
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Initial Revenue ($)</label>
                  <input 
                    type="number" 
                    placeholder="0.00"
                    value={newClient.revenue ?? 0}
                    onChange={(e) => setNewClient({...newClient, revenue: parseFloat(e.target.value) || 0})}
                    className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <label className="text-sm font-medium">Website</label>
                <input 
                  type="text" 
                  placeholder="www.company.com"
                  value={newClient.website || ''}
                  onChange={(e) => setNewClient({...newClient, website: e.target.value})}
                  className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                />
              </div>

              <div className="pt-4 flex items-center gap-3">
                <button 
                  type="button"
                  onClick={() => {
                    setIsModalOpen(false);
                    setEditingClient(null);
                    setNewClient({
                      name: '',
                      industry: '',
                      contactPerson: '',
                      email: '',
                      phone: '',
                      status: 'Onboarding',
                      projects: 0,
                      revenue: 0,
                      website: ''
                    });
                  }}
                  className="flex-1 px-4 py-2 text-sm font-medium border border-border rounded-lg hover:bg-accent transition-colors"
                >
                  Cancel
                </button>
                <button 
                  type="submit"
                  disabled={isSubmitting}
                  className="flex-1 bg-primary px-4 py-2 text-sm font-medium text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors shadow-sm disabled:opacity-50 flex items-center justify-center gap-2"
                >
                  {isSubmitting ? (
                    <>
                      <div className="h-4 w-4 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent" />
                      Processing...
                    </>
                  ) : (
                    editingClient ? 'Update Client' : 'Add Client'
                  )}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Delete Confirmation Modal */}
      {isDeleteModalOpen && (
        <div className="fixed inset-0 z-[300] flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm">
          <div className="w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-2xl animate-in fade-in zoom-in duration-200">
            <div className="flex items-center gap-3 mb-4 text-destructive">
              <div className="p-2 rounded-full bg-destructive/10">
                <AlertCircle size={24} />
              </div>
              <h2 className="text-xl font-bold">Confirm Deletion</h2>
            </div>
            <p className="text-sm text-muted-foreground mb-6">
              Are you sure you want to delete this client? This will not delete their associated projects, but the client record will be permanently removed.
            </p>
            <div className="flex items-center gap-3">
              <button 
                onClick={() => {
                  setIsDeleteModalOpen(false);
                  setClientToDelete(null);
                }}
                className="flex-1 px-4 py-2 text-sm font-medium border border-border rounded-lg hover:bg-accent transition-colors"
              >
                Cancel
              </button>
              <button 
                onClick={confirmDelete}
                disabled={isSubmitting}
                className="flex-1 bg-destructive px-4 py-2 text-sm font-medium text-destructive-foreground rounded-lg hover:bg-destructive/90 transition-colors shadow-sm disabled:opacity-50 flex items-center justify-center gap-2"
              >
                {isSubmitting ? (
                  <>
                    <div className="h-4 w-4 animate-spin rounded-full border-2 border-destructive-foreground border-t-transparent" />
                    Deleting...
                  </>
                ) : (
                  'Delete'
                )}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function StatCard({ title, value, icon: Icon, trend, trendColor = "text-muted-foreground" }: { title: string, value: string, icon: any, trend: string, trendColor?: string }) {
  return (
    <div className="rounded-xl border border-border bg-card p-4 shadow-sm">
      <div className="flex items-center justify-between mb-2">
        <div className="p-2 rounded-lg bg-accent text-muted-foreground">
          <Icon size={18} />
        </div>
      </div>
      <div>
        <p className="text-sm text-muted-foreground">{title}</p>
        <p className="text-2xl font-bold">{value}</p>
        <p className={cn("text-xs mt-1", trendColor)}>{trend}</p>
      </div>
    </div>
  );
}
