'use client';

import { useState, useEffect, useCallback } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { ProtectedLayout } from '@/components/protected-layout';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useToast } from '@/hooks/use-toast';
import {
  Building2,
  Plus,
  Search,
  Edit2,
  Trash2,
  Mail,
  Phone,
  User,
  Calendar,
  TrendingUp,
  DollarSign,
  FileText,
  Send,
  Settings,
  BarChart3,
  Loader2,
  Upload,
  UserPlus,
  CheckCircle,
  AlertCircle,
  FileSpreadsheet
} from 'lucide-react';

interface Client {
  id: string;
  name: string;
  email: string;
  phone?: string;
  contactPerson?: string;
  address?: string;
  isActive: boolean;
  dailyReportEnabled: boolean;
  dailyReportTime: string;
  dailyReportEmail: boolean;
  dailyReportSms: boolean;
  monthlyReportEnabled: boolean;
  createdAt: string;
  stats: {
    totalAccounts: number;
    totalToCollect: number;
    totalOutstanding: number;
    totalCollected: number;
    collectionRate: string;
    activeBatches: number;
  };
  _count: {
    reports: number;
    dailyDigests: number;
  };
}

interface Agent {
  id: string;
  name: string;
  email: string;
  role: string;
}

interface UploadResult {
  success: boolean;
  message: string;
  successCount: number;
  failedCount: number;
  errors: { row: number; error: string }[];
}

export default function ClientsPage() {
  const { data: session } = useSession() || {};
  const router = useRouter();
  const { toast } = useToast();

  const [clients, setClients] = useState<Client[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingClient, setEditingClient] = useState<Client | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    contactPerson: '',
    address: '',
    dailyReportEnabled: true,
    dailyReportTime: '08:00',
    dailyReportEmail: true,
    dailyReportSms: false,
    monthlyReportEnabled: true
  });
  const [submitting, setSubmitting] = useState(false);
  const [generatingDigest, setGeneratingDigest] = useState<string | null>(null);
  
  // Upload jobs state
  const [agents, setAgents] = useState<Agent[]>([]);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [selectedAgentId, setSelectedAgentId] = useState<string>('');
  const [batchName, setBatchName] = useState('');
  const [uploading, setUploading] = useState(false);
  const [uploadResult, setUploadResult] = useState<UploadResult | null>(null);
  const [activeDialogTab, setActiveDialogTab] = useState('details');

  const fetchClients = useCallback(async () => {
    try {
      const params = new URLSearchParams();
      if (search) params.append('search', search);
      const res = await fetch(`/api/clients?${params}`);
      if (res.ok) {
        const data = await res.json();
        setClients(data);
      }
    } catch (error) {
      console.error('Error fetching clients:', error);
    } finally {
      setLoading(false);
    }
  }, [search]);

  useEffect(() => {
    fetchClients();
  }, [fetchClients]);

  useEffect(() => {
    if (session?.user?.role === 'AGENT') {
      router.push('/dashboard');
    }
  }, [session, router]);

  // Fetch agents for assignment
  const fetchAgents = useCallback(async () => {
    try {
      const res = await fetch('/api/users');
      if (res.ok) {
        const data = await res.json();
        const agentList = (data.users || []).filter((u: Agent) => u.role === 'AGENT');
        setAgents(agentList);
      }
    } catch (error) {
      console.error('Error fetching agents:', error);
    }
  }, []);

  useEffect(() => {
    if (session?.user?.role === 'ADMIN' || session?.user?.role === 'MANAGER') {
      fetchAgents();
    }
  }, [session, fetchAgents]);

  // Handle file upload with agent assignment
  const handleUploadJobs = async () => {
    if (!selectedFile || !editingClient) {
      toast({
        title: 'Error',
        description: 'Please select a file to upload',
        variant: 'destructive',
      });
      return;
    }

    setUploading(true);
    setUploadResult(null);

    try {
      const uploadFormData = new FormData();
      uploadFormData.append('file', selectedFile);
      uploadFormData.append('clientId', editingClient.id);
      uploadFormData.append('clientName', editingClient.name);
      if (batchName) {
        uploadFormData.append('batchName', batchName);
      }
      if (selectedAgentId && selectedAgentId !== 'none') {
        uploadFormData.append('assignToAgentId', selectedAgentId);
      }

      const res = await fetch('/api/import-excel', {
        method: 'POST',
        body: uploadFormData,
      });

      const data = await res.json();

      if (res.ok) {
        setUploadResult({
          success: true,
          message: data.message || 'Jobs uploaded successfully',
          successCount: data.success || 0,
          failedCount: data.failed || 0,
          errors: data.errors || [],
        });
        toast({
          title: 'Success',
          description: `Uploaded ${data.success || 0} jobs successfully`,
        });
        fetchClients();
      } else {
        setUploadResult({
          success: false,
          message: data.error || 'Upload failed',
          successCount: 0,
          failedCount: 0,
          errors: data.errors || [],
        });
        toast({
          title: 'Error',
          description: data.error || 'Failed to upload jobs',
          variant: 'destructive',
        });
      }
    } catch (error) {
      console.error('Upload error:', error);
      toast({
        title: 'Error',
        description: 'Failed to upload jobs',
        variant: 'destructive',
      });
    } finally {
      setUploading(false);
    }
  };

  const resetUploadState = () => {
    setSelectedFile(null);
    setSelectedAgentId('');
    setBatchName('');
    setUploadResult(null);
  };

  const handleOpenDialog = (client?: Client) => {
    resetUploadState();
    setActiveDialogTab('details');
    if (client) {
      setEditingClient(client);
      setFormData({
        name: client.name,
        email: client.email,
        phone: client.phone || '',
        contactPerson: client.contactPerson || '',
        address: client.address || '',
        dailyReportEnabled: client.dailyReportEnabled,
        dailyReportTime: client.dailyReportTime,
        dailyReportEmail: client.dailyReportEmail,
        dailyReportSms: client.dailyReportSms,
        monthlyReportEnabled: client.monthlyReportEnabled
      });
    } else {
      setEditingClient(null);
      setFormData({
        name: '',
        email: '',
        phone: '',
        contactPerson: '',
        address: '',
        dailyReportEnabled: true,
        dailyReportTime: '08:00',
        dailyReportEmail: true,
        dailyReportSms: false,
        monthlyReportEnabled: true
      });
    }
    setIsDialogOpen(true);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);

    try {
      const method = editingClient ? 'PUT' : 'POST';
      const body = editingClient ? { id: editingClient.id, ...formData } : formData;

      const res = await fetch('/api/clients', {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body)
      });

      if (res.ok) {
        toast({
          title: 'Success',
          description: `Client ${editingClient ? 'updated' : 'created'} successfully`,
        });
        setIsDialogOpen(false);
        fetchClients();
      } else {
        const data = await res.json();
        toast({
          title: 'Error',
          description: data.error || 'Failed to save client',
          variant: 'destructive',
        });
      }
    } catch (error) {
      toast({
        title: 'Error',
        description: 'Failed to save client',
        variant: 'destructive',
      });
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Are you sure you want to delete this client?')) return;

    try {
      const res = await fetch(`/api/clients?id=${id}`, { method: 'DELETE' });
      if (res.ok) {
        toast({
          title: 'Success',
          description: 'Client deleted successfully',
        });
        fetchClients();
      }
    } catch (error) {
      toast({
        title: 'Error',
        description: 'Failed to delete client',
        variant: 'destructive',
      });
    }
  };

  const handleGenerateDigest = async (clientId: string) => {
    setGeneratingDigest(clientId);
    try {
      const res = await fetch('/api/reports/daily-digest', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ clientId, sendNotification: true })
      });

      if (res.ok) {
        toast({
          title: 'Success',
          description: 'Daily digest generated and sent successfully',
        });
      } else {
        throw new Error('Failed to generate digest');
      }
    } catch (error) {
      toast({
        title: 'Error',
        description: 'Failed to generate daily digest',
        variant: 'destructive',
      });
    } finally {
      setGeneratingDigest(null);
    }
  };

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('en-KE', {
      style: 'currency',
      currency: 'KES',
      minimumFractionDigits: 0,
    }).format(amount);
  };

  return (
    <ProtectedLayout>
      <div className="space-y-6">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold tracking-tight">Client Management</h1>
            <p className="text-muted-foreground">
              Manage your clients and their portfolio reporting preferences
            </p>
          </div>
          {session?.user?.role === 'ADMIN' && (
            <Button onClick={() => handleOpenDialog()}>
              <Plus className="mr-2 h-4 w-4" />
              Add Client
            </Button>
          )}
        </div>

        {/* Summary Cards */}
        <div className="grid gap-4 md:grid-cols-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Total Clients</CardTitle>
              <Building2 className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{clients.length}</div>
              <p className="text-xs text-muted-foreground">
                {clients.filter(c => c.isActive).length} active
              </p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Total Portfolio</CardTitle>
              <DollarSign className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {formatCurrency(clients.reduce((sum, c) => sum + c.stats.totalToCollect, 0))}
              </div>
              <p className="text-xs text-muted-foreground">
                {clients.reduce((sum, c) => sum + c.stats.totalAccounts, 0)} accounts
              </p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Total Collected</CardTitle>
              <TrendingUp className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {formatCurrency(clients.reduce((sum, c) => sum + c.stats.totalCollected, 0))}
              </div>
              <p className="text-xs text-muted-foreground">
                Average rate: {(clients.reduce((sum, c) => sum + parseFloat(c.stats.collectionRate), 0) / Math.max(clients.length, 1)).toFixed(1)}%
              </p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Daily Reports</CardTitle>
              <FileText className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {clients.filter(c => c.dailyReportEnabled).length}
              </div>
              <p className="text-xs text-muted-foreground">
                Clients with daily streaming enabled
              </p>
            </CardContent>
          </Card>
        </div>

        {/* Search */}
        <div className="flex items-center gap-4">
          <div className="relative flex-1 max-w-sm">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              placeholder="Search clients..."
              className="pl-10"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
            />
          </div>
        </div>

        {/* Clients Table */}
        <Card>
          <CardHeader>
            <CardTitle>Clients</CardTitle>
            <CardDescription>
              View and manage all client accounts and their reporting preferences
            </CardDescription>
          </CardHeader>
          <CardContent>
            {loading ? (
              <div className="flex items-center justify-center py-8">
                <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
              </div>
            ) : clients.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                No clients found. Add your first client to get started.
              </div>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Client</TableHead>
                    <TableHead>Contact</TableHead>
                    <TableHead>Portfolio</TableHead>
                    <TableHead>Collection Rate</TableHead>
                    <TableHead>Daily Report</TableHead>
                    <TableHead>Monthly Report</TableHead>
                    <TableHead className="text-right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {clients.map((client) => (
                    <TableRow key={client.id}>
                      <TableCell>
                        <div className="flex items-center gap-3">
                          <div className="h-10 w-10 rounded-full bg-blue-100 flex items-center justify-center">
                            <Building2 className="h-5 w-5 text-blue-600" />
                          </div>
                          <div>
                            <div className="font-medium">{client.name}</div>
                            <div className="text-sm text-muted-foreground flex items-center gap-1">
                              <Mail className="h-3 w-3" />
                              {client.email}
                            </div>
                          </div>
                        </div>
                      </TableCell>
                      <TableCell>
                        {client.contactPerson && (
                          <div className="flex items-center gap-1 text-sm">
                            <User className="h-3 w-3" />
                            {client.contactPerson}
                          </div>
                        )}
                        {client.phone && (
                          <div className="flex items-center gap-1 text-sm text-muted-foreground">
                            <Phone className="h-3 w-3" />
                            {client.phone}
                          </div>
                        )}
                      </TableCell>
                      <TableCell>
                        <div className="text-sm">
                          <div className="font-medium">{formatCurrency(client.stats.totalToCollect)}</div>
                          <div className="text-muted-foreground">
                            {client.stats.totalAccounts} accounts • {client.stats.activeBatches} batches
                          </div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <div className="w-16 h-2 bg-gray-200 rounded-full overflow-hidden">
                            <div
                              className="h-full bg-green-500 rounded-full"
                              style={{ width: `${Math.min(parseFloat(client.stats.collectionRate), 100)}%` }}
                            />
                          </div>
                          <span className="text-sm font-medium">{client.stats.collectionRate}%</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge variant={client.dailyReportEnabled ? 'default' : 'secondary'}>
                          {client.dailyReportEnabled ? `${client.dailyReportTime}` : 'Disabled'}
                        </Badge>
                        {client.dailyReportEnabled && (
                          <div className="text-xs text-muted-foreground mt-1">
                            {client.dailyReportEmail && 'Email'}
                            {client.dailyReportEmail && client.dailyReportSms && ' + '}
                            {client.dailyReportSms && 'SMS'}
                          </div>
                        )}
                      </TableCell>
                      <TableCell>
                        <Badge variant={client.monthlyReportEnabled ? 'default' : 'secondary'}>
                          {client.monthlyReportEnabled ? 'Enabled' : 'Disabled'}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex items-center justify-end gap-2">
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleGenerateDigest(client.id)}
                            disabled={generatingDigest === client.id}
                          >
                            {generatingDigest === client.id ? (
                              <Loader2 className="h-4 w-4 animate-spin" />
                            ) : (
                              <Send className="h-4 w-4" />
                            )}
                          </Button>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleOpenDialog(client)}
                          >
                            <Edit2 className="h-4 w-4" />
                          </Button>
                          {session?.user?.role === 'ADMIN' && (
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => handleDelete(client.id)}
                            >
                              <Trash2 className="h-4 w-4 text-red-500" />
                            </Button>
                          )}
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            )}
          </CardContent>
        </Card>

        {/* Client Dialog */}
        <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
          <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>
                {editingClient ? 'Edit Client' : 'Add New Client'}
              </DialogTitle>
              <DialogDescription>
                {editingClient
                  ? 'Update client details and reporting preferences'
                  : 'Add a new client to manage their debt collection portfolio'}
              </DialogDescription>
            </DialogHeader>

            <form onSubmit={handleSubmit}>
              <Tabs value={activeDialogTab} onValueChange={setActiveDialogTab} className="w-full">
                <TabsList className={`grid w-full ${editingClient ? 'grid-cols-3' : 'grid-cols-2'}`}>
                  <TabsTrigger value="details">Client Details</TabsTrigger>
                  <TabsTrigger value="reports">Report Settings</TabsTrigger>
                  {editingClient && (
                    <TabsTrigger value="upload">Upload Jobs</TabsTrigger>
                  )}
                </TabsList>

                <TabsContent value="details" className="space-y-4 mt-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="name">Company Name *</Label>
                      <Input
                        id="name"
                        value={formData.name}
                        onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                        required
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="email">Email *</Label>
                      <Input
                        id="email"
                        type="email"
                        value={formData.email}
                        onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                        required
                      />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="contactPerson">Contact Person</Label>
                      <Input
                        id="contactPerson"
                        value={formData.contactPerson}
                        onChange={(e) => setFormData({ ...formData, contactPerson: e.target.value })}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="phone">Phone</Label>
                      <Input
                        id="phone"
                        value={formData.phone}
                        onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                      />
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="address">Address</Label>
                    <Textarea
                      id="address"
                      value={formData.address}
                      onChange={(e) => setFormData({ ...formData, address: e.target.value })}
                      rows={2}
                    />
                  </div>
                </TabsContent>

                <TabsContent value="reports" className="space-y-6 mt-4">
                  {/* Daily Report Settings */}
                  <Card>
                    <CardHeader>
                      <CardTitle className="text-lg flex items-center gap-2">
                        <Calendar className="h-5 w-5" />
                        Daily Report Streaming
                      </CardTitle>
                      <CardDescription>
                        Configure daily portfolio status updates for this client
                      </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="flex items-center justify-between">
                        <div>
                          <Label>Enable Daily Reports</Label>
                          <p className="text-sm text-muted-foreground">Send daily portfolio updates</p>
                        </div>
                        <Switch
                          checked={formData.dailyReportEnabled}
                          onCheckedChange={(checked) => setFormData({ ...formData, dailyReportEnabled: checked })}
                        />
                      </div>
                      {formData.dailyReportEnabled && (
                        <>
                          <div className="space-y-2">
                            <Label htmlFor="dailyReportTime">Send Time</Label>
                            <Input
                              id="dailyReportTime"
                              type="time"
                              value={formData.dailyReportTime}
                              onChange={(e) => setFormData({ ...formData, dailyReportTime: e.target.value })}
                            />
                          </div>
                          <div className="flex items-center gap-6">
                            <div className="flex items-center gap-2">
                              <Switch
                                checked={formData.dailyReportEmail}
                                onCheckedChange={(checked) => setFormData({ ...formData, dailyReportEmail: checked })}
                              />
                              <Label>Email</Label>
                            </div>
                            <div className="flex items-center gap-2">
                              <Switch
                                checked={formData.dailyReportSms}
                                onCheckedChange={(checked) => setFormData({ ...formData, dailyReportSms: checked })}
                              />
                              <Label>SMS</Label>
                            </div>
                          </div>
                        </>
                      )}
                    </CardContent>
                  </Card>

                  {/* Monthly Report Settings */}
                  <Card>
                    <CardHeader>
                      <CardTitle className="text-lg flex items-center gap-2">
                        <BarChart3 className="h-5 w-5" />
                        Monthly Reports
                      </CardTitle>
                      <CardDescription>
                        Comprehensive monthly progress reports sent on the last day of each month
                      </CardDescription>
                    </CardHeader>
                    <CardContent>
                      <div className="flex items-center justify-between">
                        <div>
                          <Label>Enable Monthly Reports</Label>
                          <p className="text-sm text-muted-foreground">Automatically generate monthly reports</p>
                        </div>
                        <Switch
                          checked={formData.monthlyReportEnabled}
                          onCheckedChange={(checked) => setFormData({ ...formData, monthlyReportEnabled: checked })}
                        />
                      </div>
                    </CardContent>
                  </Card>
                </TabsContent>

                {/* Upload Jobs Tab - Only show for existing clients */}
                {editingClient && (
                  <TabsContent value="upload" className="space-y-4 mt-4">
                    <Card>
                      <CardHeader>
                        <CardTitle className="text-lg flex items-center gap-2">
                          <Upload className="h-5 w-5" />
                          Upload Collection Jobs
                        </CardTitle>
                        <CardDescription>
                          Upload an Excel file with collection jobs for {editingClient.name} and optionally assign them to an agent
                        </CardDescription>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        {/* Batch Name */}
                        <div className="space-y-2">
                          <Label htmlFor="batchName">Batch Name (Optional)</Label>
                          <Input
                            id="batchName"
                            placeholder={`e.g., ${editingClient.name} - February 2026`}
                            value={batchName}
                            onChange={(e) => setBatchName(e.target.value)}
                          />
                          <p className="text-xs text-muted-foreground">
                            A batch helps organize and track jobs uploaded together
                          </p>
                        </div>

                        {/* Agent Assignment */}
                        <div className="space-y-2">
                          <Label>Assign to Agent (Optional)</Label>
                          <Select value={selectedAgentId} onValueChange={setSelectedAgentId}>
                            <SelectTrigger>
                              <SelectValue placeholder="Select an agent to assign all jobs" />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="none">
                                <span className="text-muted-foreground">Don&apos;t assign (assign later)</span>
                              </SelectItem>
                              {agents.map((agent) => (
                                <SelectItem key={agent.id} value={agent.id}>
                                  <div className="flex items-center gap-2">
                                    <UserPlus className="h-4 w-4" />
                                    {agent.name}
                                    <span className="text-muted-foreground text-xs">({agent.email})</span>
                                  </div>
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                          {selectedAgentId && selectedAgentId !== 'none' && (
                            <p className="text-xs text-green-600 flex items-center gap-1">
                              <CheckCircle className="h-3 w-3" />
                              All uploaded jobs will be assigned to this agent
                            </p>
                          )}
                        </div>

                        {/* File Upload */}
                        <div className="space-y-2">
                          <Label>Excel File</Label>
                          <div className="border-2 border-dashed rounded-lg p-6 text-center hover:border-primary/50 transition-colors">
                            <input
                              type="file"
                              accept=".xlsx,.xls"
                              onChange={(e) => {
                                const file = e.target.files?.[0];
                                if (file) setSelectedFile(file);
                              }}
                              className="hidden"
                              id="job-file-upload"
                            />
                            <label htmlFor="job-file-upload" className="cursor-pointer">
                              <FileSpreadsheet className="h-10 w-10 mx-auto text-muted-foreground mb-2" />
                              {selectedFile ? (
                                <div>
                                  <p className="font-medium text-green-600">{selectedFile.name}</p>
                                  <p className="text-xs text-muted-foreground">
                                    {(selectedFile.size / 1024).toFixed(1)} KB
                                  </p>
                                </div>
                              ) : (
                                <div>
                                  <p className="font-medium">Click to select Excel file</p>
                                  <p className="text-xs text-muted-foreground">
                                    Supports .xlsx and .xls formats
                                  </p>
                                </div>
                              )}
                            </label>
                          </div>
                        </div>

                        {/* Expected Format */}
                        <div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
                          <p className="text-sm font-medium text-blue-800 mb-1">Expected Excel Format:</p>
                          <p className="text-xs text-blue-700">
                            NAME/Borrower NAME, ID NUMBER, PHONE No., APPL_AMT/Allocation Amount, BALANCE, 
                            10%COMM (optional), 16% VAT (optional), TOTAL TO BE COLLECTED (optional)
                          </p>
                        </div>

                        {/* Upload Button */}
                        <Button
                          type="button"
                          onClick={handleUploadJobs}
                          disabled={!selectedFile || uploading}
                          className="w-full"
                        >
                          {uploading ? (
                            <>
                              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                              Uploading...
                            </>
                          ) : (
                            <>
                              <Upload className="mr-2 h-4 w-4" />
                              Upload Jobs {selectedAgentId && selectedAgentId !== 'none' && '& Assign to Agent'}
                            </>
                          )}
                        </Button>

                        {/* Upload Results */}
                        {uploadResult && (
                          <div className={`rounded-lg p-4 ${uploadResult.success ? 'bg-green-50 border border-green-200' : 'bg-red-50 border border-red-200'}`}>
                            <div className="flex items-center gap-2 mb-2">
                              {uploadResult.success ? (
                                <CheckCircle className="h-5 w-5 text-green-600" />
                              ) : (
                                <AlertCircle className="h-5 w-5 text-red-600" />
                              )}
                              <p className={`font-medium ${uploadResult.success ? 'text-green-800' : 'text-red-800'}`}>
                                {uploadResult.message}
                              </p>
                            </div>
                            <div className="text-sm">
                              <p className="text-green-700">✓ {uploadResult.successCount} jobs uploaded successfully</p>
                              {uploadResult.failedCount > 0 && (
                                <p className="text-red-700">✗ {uploadResult.failedCount} jobs failed</p>
                              )}
                            </div>
                            {uploadResult.errors.length > 0 && (
                              <div className="mt-2 max-h-32 overflow-y-auto">
                                <p className="text-xs font-medium text-red-800 mb-1">Errors:</p>
                                {uploadResult.errors.slice(0, 5).map((err, idx) => (
                                  <p key={idx} className="text-xs text-red-700">
                                    Row {err.row}: {err.error}
                                  </p>
                                ))}
                                {uploadResult.errors.length > 5 && (
                                  <p className="text-xs text-red-600">
                                    ...and {uploadResult.errors.length - 5} more errors
                                  </p>
                                )}
                              </div>
                            )}
                          </div>
                        )}
                      </CardContent>
                    </Card>
                  </TabsContent>
                )}
              </Tabs>

              <div className="flex justify-end gap-2 mt-6">
                <Button type="button" variant="outline" onClick={() => setIsDialogOpen(false)}>
                  Cancel
                </Button>
                <Button type="submit" disabled={submitting}>
                  {submitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  {editingClient ? 'Update Client' : 'Create Client'}
                </Button>
              </div>
            </form>
          </DialogContent>
        </Dialog>
      </div>
    </ProtectedLayout>
  );
}
