import { useState, useEffect } from 'react';
import { ApplicationStatus, Application } from '@/lib/mock-data';
import { masterService } from '@/services/master.service';
import { onboardingService } from '@/services/onboarding.service';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import { Calendar as CalendarPicker } from '@/components/ui/calendar';
import { format } from 'date-fns';
import { cn } from '@/components/ui/utils';
import {
  Pagination,
  PaginationContent,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination";
import {
  Search,
  Download,
  CheckCircle,
  Mail,
  Grid3x3,
  List,
  Loader2,
  Calendar,
  ArrowUpDown
} from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableHead,
  TableHeader,
  TableRow,
  TableCell
} from '@/components/ui/table';
import { Progress } from '@/components/ui/progress';
import { Checkbox } from '@/components/ui/checkbox';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { formatDateTime } from '@/components/ui/utils';
import { toast } from 'sonner';
import { ApplicationCard } from '@/features/onboarding/components/ApplicationCard';


interface OpportunityRequestsPageProps {
  onViewDetails: (id: string) => void;
}

export function OpportunityRequestsPage({ onViewDetails }: OpportunityRequestsPageProps) {
  const [viewMode, setViewMode] = useState<'grid' | 'table'>('table');
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [locationFilter, setLocationFilter] = useState<string>('all');
  const [stateFilter, setStateFilter] = useState<string>('all');
  const [fromDate, setFromDate] = useState<string>('');
  const [toDate, setToDate] = useState<string>('');
  const [sortBy, setSortBy] = useState<string>('date-desc');
  const [currentPage, setCurrentPage] = useState(1);
  const [paginationMeta, setPaginationMeta] = useState<any>(null);
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [isSendingReminders, setIsSendingReminders] = useState(false);
  const [showShortlistModal, setShowShortlistModal] = useState(false);
  const [shortlistRemark, setShortlistRemark] = useState('');

  // Assignee Selection
  const [states, setStates] = useState<string[]>([]);
  const [locations, setLocations] = useState<string[]>([]);

  // Real data integration
  const [applicationsData, setApplicationsData] = useState<Application[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchApplications();
  }, [fromDate, toDate, statusFilter, searchQuery, currentPage, locationFilter, stateFilter]);

  useEffect(() => {
    setCurrentPage(1);
  }, [fromDate, toDate, statusFilter, searchQuery, locationFilter, stateFilter]);

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

  const fetchStates = async () => {
    try {
      const response = await masterService.getStates();
      // Standardize data extraction
      const statesData = Array.isArray(response) ? response : ((response as any)?.data || (response as any)?.states || []);
      const stateNames = statesData.map((s: any) => typeof s === 'string' ? s : (s.name || s.stateName)).filter(Boolean);
      setStates(stateNames);
    } catch (error) {
      console.error('Failed to fetch states:', error);
    }
  };


  const fetchApplications = async () => {
    try {
      setLoading(true);
      const opportunityStatuses = ['Questionnaire Pending', 'Questionnaire Completed', 'Shortlisted'];
      const response = await onboardingService.getApplications({
        fromDate,
        toDate,
        status: statusFilter === 'all' ? opportunityStatuses.join(',') : statusFilter,
        location: locationFilter !== 'all' ? locationFilter : undefined,
        state: stateFilter !== 'all' ? stateFilter : undefined,
        ddLeadShortlisted: 'false',
        isShortlisted: 'true',
        search: searchQuery,
        page: currentPage,
        limit: 10
      });
      const rawData = response.data || [];
      setPaginationMeta(response.meta);

      // Map backend data to Application interface
      const mappedApps: Application[] = rawData.map((app: any) => ({
        id: app.id,
        registrationNumber: app.applicationId || 'N/A',
        name: app.applicantName,
        email: app.email,
        phone: app.phone,
        age: app.age,
        education: app.education,
        residentialAddress: app.address || app.city || '',
        businessAddress: app.address || '',
        preferredLocation: app.preferredLocation,
        state: app.state,
        ownsBike: app.ownRoyalEnfield === 'yes',
        pastExperience: app.experienceYears ? `${app.experienceYears} years` : (app.description || ''),
        status: app.overallStatus as ApplicationStatus,
        questionnaireMarks: app.score || app.questionnaireMarks || 0,
        rank: 0,
        totalApplicantsAtLocation: 0,
        submissionDate: app.createdAt,
        assignedUsers: [],
        progress: app.progressPercentage || 0,
        isShortlisted: app.isShortlisted,
        ddLeadShortlisted: app.ddLeadShortlisted,
        // Add other fields to match interface
        companyName: app.companyName,
        source: app.source,
        existingDealer: app.existingDealer,
        royalEnfieldModel: app.royalEnfieldModel,
        description: app.description,
        pincode: app.pincode,
        locationType: app.locationType,
        ownRoyalEnfield: app.ownRoyalEnfield,
        address: app.address
      }));

      setApplicationsData(mappedApps);

      // Extract unique locations and states from the returned data
      // Note: This appends new ones to the existing list to ensure all found locations are selectable
      const newLocations = Array.from(new Set(mappedApps.map(app => app.preferredLocation))).filter(Boolean) as string[];
      setLocations(prev => Array.from(new Set([...prev, ...newLocations])));
      
      const newStates = Array.from(new Set(mappedApps.map(app => app.state))).filter(Boolean) as string[];
      setStates(prev => Array.from(new Set([...prev, ...newStates])));
    } catch (error) {
      console.error('Failed to fetch applications:', error);
      toast.error('Failed to load opportunity requests');
    } finally {
      setLoading(false);
    }
  };

  // Filter applications that match preferred locations (opportunity requests)
  // These are applications where we are currently offering dealerships
  // Shows applications shortlisted by DD but NOT yet shortlisted by DD Lead
  // IMPORTANT: Only shows applications in early stages (before they enter full workflow)
  // UPDATED LOGIC: Opportunities start at 'Questionnaire Pending'. 'Submitted' means Non-Opportunity.
  const filteredApplications = applicationsData.sort((a, b) => {
    if (sortBy === 'score-desc') return (b.questionnaireMarks || 0) - (a.questionnaireMarks || 0);
    if (sortBy === 'score-asc') return (a.questionnaireMarks || 0) - (b.questionnaireMarks || 0);
    if (sortBy === 'date-desc') return new Date(b.submissionDate).getTime() - new Date(a.submissionDate).getTime();
    if (sortBy === 'date-asc') return new Date(a.submissionDate).getTime() - new Date(b.submissionDate).getTime();
    return 0;
  });

  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedIds(filteredApplications.map(app => app.id));
    } else {
      setSelectedIds([]);
    }
  };

  const handleSelectOne = (id: string, checked: boolean) => {
    if (checked) {
      setSelectedIds([...selectedIds, id]);
    } else {
      setSelectedIds(selectedIds.filter(selectedId => selectedId !== id));
    }
  };

  const handleShortlist = () => {
    if (selectedIds.length === 0) {
      toast.error('Please select at least one application to shortlist');
      return;
    }
    setShowShortlistModal(true);
  };

  const confirmShortlist = async () => {
    try {
      // Call Backend API - assignedTo is now empty as it's handled automatically
      const response = await onboardingService.shortlistApplications(selectedIds, [], shortlistRemark);

      if (response && response.success) {
        // Refresh data from server to ensure correct filtering and pagination
        await fetchApplications();

        setSelectedIds([]);
        setShowShortlistModal(false);
        setShortlistRemark('');

        toast.success(`${selectedIds.length} application(s) shortlisted successfully. Users will be assigned automatically.`);
      } else {
        throw new Error(response?.message || 'Failed to process shortlisting');
      }
    } catch (error: any) {
      console.error('Failed to shortlist applications:', error);
      toast.error(error.message || 'Failed to process shortlisting');
    }
  };

  const handleBulkReminders = async () => {
    if (selectedIds.length === 0) {
      toast.error('Please select at least one application');
      return;
    }
    
    try {
      setIsSendingReminders(true);
      const res = await onboardingService.sendBulkReminders(selectedIds);
      if (res.success) {
        toast.success(res.message || `Reminder emails sent to ${selectedIds.length} applicant(s)`);
        setSelectedIds([]);
      }
    } catch (error: any) {
      console.error('Failed to send reminders:', error);
      toast.error(error.message || 'Failed to send reminders');
    } finally {
      setIsSendingReminders(false);
    }
  };

  const handleExport = async () => {
    // Exclude 'Questionnaire Pending' from export as they have no responses yet
    const validApplications = filteredApplications.filter(app => app.status !== 'Questionnaire Pending');
    const selectedValidApps = validApplications.filter(app => selectedIds.includes(app.id));

    let idsToExport: string[] = [];

    if (selectedIds.length > 0) {
      if (selectedValidApps.length === 0) {
        toast.error('Selected applications are in "Questionnaire Pending" status and cannot be exported.');
        return;
      }
      idsToExport = selectedValidApps.map(a => a.id);
      if (selectedValidApps.length < selectedIds.length) {
        toast.info(`Skipping ${selectedIds.length - selectedValidApps.length} applications with pending questionnaires.`);
      }
    } else {
      idsToExport = validApplications.map(a => a.id);
    }

    if (idsToExport.length === 0) {
      toast.error('No applications with completed questionnaires available for export');
      return;
    }

    try {
      const loadingToast = toast.loading('Preparing Excel export...');
      const data = await onboardingService.exportResponses(idsToExport);
      toast.dismiss(loadingToast);

      if (!data || data.length === 0) {
        toast.error('No response data found');
        return;
      }

      // Convert JSON to CSV (Excel compatible)
      const headers = Object.keys(data[0]);
      const csvRows = [
        headers.join(','), // Header row
        ...data.map((row: any) =>
          headers.map(header => {
            const val = row[header] ?? '';
            // Escape quotes and wrap in quotes for CSV safety
            return `"${String(val).replace(/"/g, '""')}"`;
          }).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);
      // Using .xlsx extension to satisfy requirement, though format is CSV
      link.setAttribute('download', `onboarding_responses_${new Date().toISOString().split('T')[0]}.xlsx`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      toast.success(`Exported ${idsToExport.length} records to Excel successfully`);
    } catch (error: any) {
      console.error('Export failed:', error);
      toast.error(error.message || 'Failed to export responses');
    }
  };

  // For Opportunity Requests, only show early-stage statuses
  // These applications haven't entered the full dealership approval workflow yet
  const statusOptions: ApplicationStatus[] = [
    'Questionnaire Pending',
    'Questionnaire Completed',
    'Shortlisted'
  ];

  const getStatusColor = (status: ApplicationStatus) => {
    const colors: Record<ApplicationStatus, string> = {
      'Submitted': 'bg-blue-100 text-blue-800',
      'Questionnaire Pending': 'bg-yellow-100 text-yellow-800',
      'Questionnaire Completed': 'bg-cyan-100 text-cyan-800',
      'Shortlisted': 'bg-purple-100 text-purple-800',
      'Level 1 Interview Pending': 'bg-orange-100 text-orange-800',
      'Level 1 Approved': 'bg-green-100 text-green-800',
      'Level 2 Interview Pending': 'bg-orange-100 text-orange-800',
      'Level 2 Approved': 'bg-green-100 text-green-800',
      'Level 2 Recommended': 'bg-teal-100 text-teal-800',
      'Level 3 Interview Pending': 'bg-orange-100 text-orange-800',
      'FDD Verification': 'bg-indigo-100 text-indigo-800',
      'Payment Pending': 'bg-amber-100 text-amber-800',
      'LOI Issued': 'bg-sky-100 text-sky-800',
      'Dealer Code Generation': 'bg-purple-100 text-purple-800',
      'Architecture Team Assigned': 'bg-blue-100 text-blue-800',
      'Architecture Document Upload': 'bg-blue-100 text-blue-800',
      'Architecture Team Completion': 'bg-blue-100 text-blue-800',
      'Statutory GST': 'bg-emerald-100 text-emerald-800',
      'Statutory PAN': 'bg-emerald-100 text-emerald-800',
      'Statutory Nodal': 'bg-emerald-100 text-emerald-800',
      'Statutory Check': 'bg-emerald-100 text-emerald-800',
      'Statutory Partnership': 'bg-emerald-100 text-emerald-800',
      'Statutory Firm Reg': 'bg-emerald-100 text-emerald-800',
      'Statutory Rental': 'bg-emerald-100 text-emerald-800',
      'Statutory Virtual Code': 'bg-emerald-100 text-emerald-800',
      'Statutory Domain': 'bg-emerald-100 text-emerald-800',
      'Statutory MSD': 'bg-emerald-100 text-emerald-800',
      'Statutory LOI Ack': 'bg-emerald-100 text-emerald-800',
      'EOR In Progress': 'bg-violet-100 text-violet-800',
      'LOA Pending': 'bg-pink-100 text-pink-800',
      'Inauguration': 'bg-green-100 text-green-800',
      'Approved': 'bg-green-100 text-green-800',
      'Rejected': 'bg-red-100 text-red-800',
      'Disqualified': 'bg-gray-100 text-gray-800',
      'In Review': 'bg-slate-100 text-slate-800',
      'Level 3 Approved': 'bg-green-100 text-green-800',
      'LOI In Progress': 'bg-sky-50 text-sky-700',
      'LOI Approved': 'bg-green-100 text-green-800',
      'Security Details In Progress': 'bg-blue-50 text-blue-700',
      'Security Details Approved': 'bg-green-100 text-green-800',
      'Security Details': 'bg-blue-100 text-blue-800',
      'LOI Issued In Progress': 'bg-sky-50 text-sky-700',
      'Statutory Work In Progress': 'bg-emerald-50 text-emerald-700',
      'Statutory Work Completed': 'bg-green-100 text-green-800',
      'Architecture Work In Progress': 'bg-blue-50 text-blue-700',
      'Architecture Work Completed': 'bg-green-100 text-green-800',
      'Dealer Code Generation In Progress': 'bg-purple-50 text-purple-700',
      'Dealer Code Generated': 'bg-green-100 text-green-800',
      'LOA Issued': 'bg-pink-100 text-pink-800',
      'EOR Complete': 'bg-violet-100 text-violet-800',
      'Onboarded': 'bg-green-200 text-green-900'
    };
    return colors[status] || 'bg-gray-100 text-gray-800';
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center h-96">
        <Loader2 className="w-8 h-8 animate-spin text-amber-600" />
      </div>
    );
  }

  return (
    <div className="space-y-6">

      {/* Header with Filters */}
      <div className="bg-white rounded-lg border border-slate-200 p-6">
        <div className="flex flex-col gap-4">
          {/* Search and Primary Filters */}
          <div className="flex flex-col md:flex-row gap-4">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
              <Input
                type="text"
                placeholder="Search by name or registration number..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10"
                data-testid="onboarding-opp-requests-search-input"
              />
            </div>

            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-full md:w-48" data-testid="onboarding-opp-requests-status-select">
                <SelectValue placeholder="Filter by status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Statuses</SelectItem>
                {statusOptions.map((status) => (
                  <SelectItem key={status} value={status}>{status}</SelectItem>
                ))}
              </SelectContent>
            </Select>

            <Button
              variant="ghost"
              size="sm"
              className="text-slate-500 hover:text-slate-700 h-9"
              onClick={() => {
                setFromDate('');
                setToDate('');
                setStatusFilter('all');
                setLocationFilter('all');
                setStateFilter('all');
                setSearchQuery('');
              }}
              data-testid="onboarding-opp-requests-clear-filters"
            >
              Clear Filters
            </Button>

            <Select value={stateFilter} onValueChange={setStateFilter}>
              <SelectTrigger className="w-full md:w-48" data-testid="onboarding-opp-requests-state-select">
                <SelectValue placeholder="Filter by state" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All States</SelectItem>
                {states.map((state) => (
                  <SelectItem key={state} value={state}>{state}</SelectItem>
                ))}
              </SelectContent>
            </Select>

            <Select value={locationFilter} onValueChange={setLocationFilter}>
              <SelectTrigger className="w-full md:w-48" data-testid="onboarding-opp-requests-location-select">
                <SelectValue placeholder="Filter by location" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Locations</SelectItem>
                {locations.map((location) => (
                  <SelectItem key={location} value={location}>{location}</SelectItem>
                ))}
              </SelectContent>
            </Select>

            <div className="flex items-center gap-2 flex-1 md:flex-none">
              <Popover>
                <PopoverTrigger asChild>
                  <Button
                    variant="outline"
                    className={cn(
                      "w-full md:w-40 justify-start text-left font-normal h-9 px-3",
                      !fromDate && "text-muted-foreground"
                    )}
                    data-testid="onboarding-opp-requests-from-date-trigger"
                  >
                    <Calendar className="mr-2 h-4 w-4 text-slate-400" />
                    {fromDate ? format(new Date(fromDate), "PPP") : <span className="text-xs">From Date</span>}
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-auto p-0" align="start">
                  <CalendarPicker
                    mode="single"
                    selected={fromDate ? new Date(fromDate) : undefined}
                    onSelect={(date) => setFromDate(date ? date.toISOString().split('T')[0] : '')}
                    initialFocus
                  />
                </PopoverContent>
              </Popover>

              <span className="text-slate-400">to</span>

              <Popover>
                <PopoverTrigger asChild>
                  <Button
                    variant="outline"
                    className={cn(
                      "w-full md:w-40 justify-start text-left font-normal h-9 px-3",
                      !toDate && "text-muted-foreground"
                    )}
                    data-testid="onboarding-opp-requests-to-date-trigger"
                  >
                    <Calendar className="mr-2 h-4 w-4 text-slate-400" />
                    {toDate ? format(new Date(toDate), "PPP") : <span className="text-xs">To Date</span>}
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-auto p-0" align="start">
                  <CalendarPicker
                    mode="single"
                    selected={toDate ? new Date(toDate) : undefined}
                    onSelect={(date) => setToDate(date ? date.toISOString().split('T')[0] : '')}
                    initialFocus
                  />
                </PopoverContent>
              </Popover>
            </div>

            <Select value={sortBy} onValueChange={setSortBy}>
              <SelectTrigger className="w-full md:w-48" data-testid="onboarding-opp-requests-sort-select">
                <div className="flex items-center gap-2">
                  <ArrowUpDown className="w-4 h-4 text-slate-400" />
                  <SelectValue placeholder="Sort by" />
                </div>
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="date-desc">Newest Applied</SelectItem>
                <SelectItem value="date-asc">Oldest Applied</SelectItem>
                <SelectItem value="score-desc">Highest Score</SelectItem>
                <SelectItem value="score-asc">Lowest Score</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* Action Buttons */}
          <div className="flex flex-wrap items-center gap-3">
            <div className="flex gap-2">
              <Button
                variant={viewMode === 'grid' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setViewMode('grid')}
                className={viewMode === 'grid' ? 'bg-amber-600 hover:bg-amber-700' : ''}
                data-testid="onboarding-opp-requests-view-grid-btn"
              >
                <Grid3x3 className="w-4 h-4 mr-2" />
                Grid
              </Button>
              <Button
                variant={viewMode === 'table' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setViewMode('table')}
                className={viewMode === 'table' ? 'bg-amber-600 hover:bg-amber-700' : ''}
                data-testid="onboarding-opp-requests-view-table-btn"
              >
                <List className="w-4 h-4 mr-2" />
                Table
              </Button>
            </div>

            <Button variant="outline" size="sm" onClick={handleExport} data-testid="onboarding-opp-requests-export-btn">
              <Download className="w-4 h-4 mr-2" />
              Export
            </Button>

            {selectedIds.length > 0 && (
              <>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleBulkReminders}
                  disabled={isSendingReminders}
                  data-testid="onboarding-opp-requests-bulk-reminder-btn"
                >
                  {isSendingReminders ? (
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  ) : (
                    <Mail className="w-4 h-4 mr-2" />
                  )}
                  Send Reminders ({selectedIds.length})
                </Button>

                <Button
                  size="sm"
                  onClick={handleShortlist}
                  className="bg-green-600 hover:bg-green-700"
                  data-testid="onboarding-opp-requests-bulk-shortlist-btn"
                >
                  <CheckCircle className="w-4 h-4 mr-2" />
                  Shortlist ({selectedIds.length})
                </Button>
              </>
            )}

            <div className="ml-auto">
              <Badge variant="outline" className="text-slate-600" data-testid="onboarding-opp-requests-pending-count">
                {paginationMeta?.total || filteredApplications.length} pending shortlisting
              </Badge>
            </div>
          </div>
        </div>
      </div>

      {/* Applications Grid/Table */}
      {viewMode === 'grid' ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4" data-testid="onboarding-opp-requests-grid">
          {filteredApplications.map((app, idx) => (
            <div key={app.id} className="relative" data-testid={`onboarding-opp-requests-grid-item-${idx}`}>
              <div className="absolute top-4 left-4 z-10">
                <Checkbox
                  checked={selectedIds.includes(app.id)}
                  onCheckedChange={(checked) => handleSelectOne(app.id, checked as boolean)}
                  className="bg-white"
                  data-testid={`onboarding-opp-requests-grid-checkbox-${idx}`}
                />
              </div>
              <ApplicationCard
                application={app}
                onViewDetails={onViewDetails}
              />
            </div>
          ))}
          {filteredApplications.length === 0 && (
            <div className="col-span-full text-center py-12 text-slate-500 bg-white rounded-lg border border-slate-200" data-testid="onboarding-opp-requests-grid-empty">
              <CheckCircle className="w-12 h-12 mx-auto mb-4 text-slate-400" />
              <p className="text-lg mb-2">No opportunity requests found</p>
              <p className="text-sm">Try adjusting your filters</p>
            </div>
          )}
        </div>
      ) : (
        <div className="bg-white rounded-lg border border-slate-200" data-testid="onboarding-opp-requests-table-container">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-12">
                  <Checkbox
                    checked={selectedIds.length === filteredApplications.length && filteredApplications.length > 0}
                    onCheckedChange={handleSelectAll}
                    data-testid="onboarding-opp-requests-table-select-all"
                  />
                </TableHead>
                <TableHead data-testid="onboarding-opp-requests-th-reg">Registration</TableHead>
                <TableHead data-testid="onboarding-opp-requests-th-name">Name</TableHead>
                <TableHead data-testid="onboarding-opp-requests-th-pref-loc">Preferred Location</TableHead>
                <TableHead data-testid="onboarding-opp-requests-th-status">Status</TableHead>
                <TableHead data-testid="onboarding-opp-requests-th-score">Score</TableHead>
                <TableHead data-testid="onboarding-opp-requests-th-app-loc">Applicant Location</TableHead>
                <TableHead data-testid="onboarding-opp-requests-th-shortlisted">Shortlisted</TableHead>
                <TableHead data-testid="onboarding-opp-requests-th-progress">Progress</TableHead>
                <TableHead data-testid="onboarding-opp-requests-th-date">Applied On</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredApplications.map((app, idx) => (
                <TableRow
                  key={app.id}
                  className="cursor-pointer hover:bg-slate-50"
                  onClick={() => onViewDetails(app.id)}
                  data-testid={`onboarding-opp-requests-row-${idx}`}
                >
                  <TableCell onClick={(e) => e.stopPropagation()}>
                    <Checkbox
                      checked={selectedIds.includes(app.id)}
                      onCheckedChange={(checked) => handleSelectOne(app.id, checked as boolean)}
                      data-testid={`onboarding-opp-requests-table-select-item-${app.id}`}
                    />
                  </TableCell>
                  <TableCell>
                    <span className="text-slate-900" data-testid={`onboarding-opp-requests-reg-${idx}`}>{app.registrationNumber}</span>
                  </TableCell>
                  <TableCell>
                    <span className="text-slate-900" data-testid={`onboarding-opp-requests-name-${idx}`}>{app.name}</span>
                  </TableCell>
                  <TableCell>
                    <span className="text-slate-600" data-testid={`onboarding-opp-requests-pref-loc-${idx}`}>{app.preferredLocation}</span>
                  </TableCell>
                  <TableCell>
                    <Badge className={getStatusColor(app.status)} data-testid={`onboarding-opp-requests-status-${idx}`}>
                      {app.status}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <span className="font-semibold text-slate-900" data-testid={`onboarding-opp-requests-score-${idx}`}>
                      {app.questionnaireMarks}
                    </span>
                  </TableCell>
                  <TableCell>
                    <span className="text-slate-600" data-testid={`onboarding-opp-requests-app-loc-${idx}`}>{app.businessAddress}</span>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline" data-testid={`onboarding-opp-requests-shortlisted-badge-${idx}`}>No</Badge>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2" data-testid={`onboarding-opp-requests-progress-container-${idx}`}>
                      <Progress value={app.progress} className="w-20" />
                      <span className="text-slate-600">{app.progress}%</span>
                    </div>
                  </TableCell>
                  <TableCell>
                    <span className="text-slate-600" data-testid={`onboarding-opp-requests-date-${idx}`}>{formatDateTime(app.submissionDate)}</span>
                  </TableCell>
                </TableRow>
              ))}
              {filteredApplications.length === 0 && (
                <TableRow>
                  <TableCell colSpan={9} className="text-center py-12 text-slate-500" data-testid="onboarding-opp-requests-table-empty">
                    <CheckCircle className="w-12 h-12 mx-auto mb-4 text-slate-400" />
                    <p className="text-lg mb-2">No opportunity requests found</p>
                    <p className="text-sm">Try adjusting your filters</p>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>

          {/* Pagination */}
          {paginationMeta && paginationMeta.totalPages > 1 && (
            <div className="py-4 border-t border-slate-200">
              <Pagination>
                <PaginationContent>
                  <PaginationItem>
                    <PaginationPrevious
                      onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                      className={currentPage === 1 ? "pointer-events-none opacity-50" : "cursor-pointer"}
                    />
                  </PaginationItem>

                  {[...Array(paginationMeta.totalPages)].map((_, i) => {
                    const pageNum = i + 1;
                    // Simple pagination: show first, last, and current +/- 1
                    if (
                      pageNum === 1 ||
                      pageNum === paginationMeta.totalPages ||
                      (pageNum >= currentPage - 1 && pageNum <= currentPage + 1)
                    ) {
                      return (
                        <PaginationItem key={pageNum}>
                          <PaginationLink
                            isActive={currentPage === pageNum}
                            onClick={() => setCurrentPage(pageNum)}
                            className="cursor-pointer"
                          >
                            {pageNum}
                          </PaginationLink>
                        </PaginationItem>
                      );
                    } else if (
                      pageNum === currentPage - 2 ||
                      pageNum === currentPage + 2
                    ) {
                      return (
                        <PaginationItem key={pageNum}>
                          <PaginationEllipsis />
                        </PaginationItem>
                      );
                    }
                    return null;
                  })}

                  <PaginationItem>
                    <PaginationNext
                      onClick={() => setCurrentPage(p => Math.min(paginationMeta.totalPages, p + 1))}
                      className={currentPage === paginationMeta.totalPages ? "pointer-events-none opacity-50" : "cursor-pointer"}
                    />
                  </PaginationItem>
                </PaginationContent>
              </Pagination>
            </div>
          )}
        </div>
      )}

      {/* Shortlist Modal with Multi-User Assignment */}
      <Dialog open={showShortlistModal} onOpenChange={setShowShortlistModal}>
        <DialogContent className="overflow-visible" data-testid="onboarding-opp-requests-shortlist-modal">
          <DialogHeader>
            <DialogTitle data-testid="onboarding-opp-requests-shortlist-modal-title">Shortlist Applications</DialogTitle>
            <DialogDescription>
              You are about to shortlist {selectedIds.length} application(s). These applications will be moved to the Dealership Requests page and users will be assigned automatically based on the applied location.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">

            <div>
              <Label>Shortlisting Remark (Optional)</Label>
              <Textarea
                placeholder="Enter reason for shortlisting these applications..."
                value={shortlistRemark}
                onChange={(e) => setShortlistRemark(e.target.value)}
                className="mt-2"
                rows={4}
                data-testid="onboarding-opp-requests-remark-textarea"
              />
            </div>

            <div className="flex gap-3">
              <Button
                variant="outline"
                className="flex-1"
                onClick={() => {
                  setShowShortlistModal(false);
                  setShortlistRemark('');
                }}
                data-testid="onboarding-opp-requests-shortlist-cancel-btn"
              >
                Cancel
              </Button>
              <Button
                className="flex-1 bg-green-600 hover:bg-green-700"
                onClick={confirmShortlist}
                data-testid="onboarding-opp-requests-shortlist-confirm-btn"
              >
                Confirm Shortlist
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

    </div>
  );
}
