import { useState, useEffect } from 'react';
import { toast } from 'sonner';
import { ApplicationStatus, Application } from '@/lib/mock-data';
import { formatDateTime } from '@/components/ui/utils';
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 {
  Search,
  Download,
  Mail,
  Loader2
} from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Progress } from '@/components/ui/progress';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { useSelector } from 'react-redux';
import { RootState } from '@/store';
import {
  Pagination,
  PaginationContent,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination";

interface ApplicationsPageProps {
  onViewDetails: (id: string) => void;
  initialFilter?: string;
}

export function ApplicationsPage({ onViewDetails, initialFilter }: ApplicationsPageProps) {
  const { user: currentUser } = useSelector((state: RootState) => state.auth);
  const [searchQuery, setSearchQuery] = useState('');
  const [locationFilter, setLocationFilter] = useState<string>('all');
  const [statusFilter, setStatusFilter] = useState<string>(initialFilter || 'all');

  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [isSendingReminders, setIsSendingReminders] = useState(false);
  const [sortBy, setSortBy] = useState<'date'>('date');
  const [showNewApplicationModal, setShowNewApplicationModal] = useState(false);
  const [showMyAssignments, setShowMyAssignments] = useState(false);

  // Real Data Integration
  const [applications, setApplications] = useState<Application[]>([]);
  const [locations, setLocations] = useState<string[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [paginationMeta, setPaginationMeta] = useState<any>(null);
  const itemsPerPage = 10;

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

  const fetchApplications = async () => {
    try {
      const response = await onboardingService.getApplications({
        page: currentPage,
        limit: itemsPerPage,
        status: statusFilter !== 'all' ? statusFilter : undefined,
        location: locationFilter !== 'all' ? locationFilter : undefined,
        search: searchQuery || undefined,
        ddLeadShortlisted: 'true',
        isShortlisted: 'true',
        assignedTo: showMyAssignments ? currentUser?.id : undefined
      });
      
      const applicationsData = response.data || [];
      setPaginationMeta(response.meta);

      // Map backend data to frontend Application interface
      const mappedApps = applicationsData.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: 0,
        rank: 0,
        totalApplicantsAtLocation: 0,
        submissionDate: app.createdAt,
        assignedUsers: [],
        assignedTo: app.assignedTo,
        progress: app.progressPercentage || 0,
        isShortlisted: app.ddLeadShortlisted || app.isShortlisted || false,
        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
      }));
      setApplications(mappedApps);
      
      // Extract unique locations for filtering - could be optimized to fetch once
      if (locations.length === 0) {
          const uniqueLocations = Array.from(new Set(mappedApps.map((app: Application) => app.preferredLocation))).filter(Boolean) as string[];
          setLocations(uniqueLocations);
      }
    } catch (error) {
      console.error('Failed to fetch applications', error);
    } finally {
      // setLoading(false);
    }
  };

  const filteredApplications = applications.sort((a, b) => {
    if (sortBy === 'date') {
      return new Date(b.submissionDate).getTime() - new Date(a.submissionDate).getTime();
    }
    return 0;
  });

  const toggleSelection = (id: string) => {
    setSelectedIds(prev =>
      prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id]
    );
  };

  const toggleSelectAll = () => {
    if (selectedIds.length === filteredApplications.length) {
      setSelectedIds([]);
    } else {
      setSelectedIds(filteredApplications.map(app => app.id));
    }
  };

  const handleBulkReminders = async () => {
    if (selectedIds.length === 0) 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 = () => {
    alert('Exporting applications to CSV...');
  };

  const getStatusColor = (status: string) => {
    const statusColors: Record<string, string> = {
      'Submitted': 'bg-slate-500',
      'Questionnaire Pending': 'bg-orange-500',
      'Questionnaire Completed': 'bg-blue-500',
      'Shortlisted': 'bg-cyan-500',
      'Level 1 Pending': 'bg-amber-500',
      'Level 1 Approved': 'bg-green-500',
      'Level 2 Pending': 'bg-purple-500',
      'Level 2 Approved': 'bg-green-600',
      'Level 2 Recommended': 'bg-teal-500',
      'Level 3 Pending': 'bg-indigo-500',
      'FDD Verification': 'bg-violet-500',
      'Payment Pending': 'bg-yellow-500',
      'LOI Issued': 'bg-lime-500',
      'Dealer Code Generation': 'bg-fuchsia-500',
      'Architecture Team Assigned': 'bg-blue-500',
      'Architecture Document Upload': 'bg-blue-500',
      'Architecture Team Completion': 'bg-blue-500',
      'Statutory GST': 'bg-emerald-500',
      'Statutory PAN': 'bg-emerald-500',
      'Statutory Nodal': 'bg-emerald-500',
      'Statutory Check': 'bg-emerald-500',
      'Statutory Partnership': 'bg-emerald-500',
      'Statutory Firm Reg': 'bg-emerald-500',
      'Statutory Virtual Code': 'bg-emerald-500',
      'Statutory Domain': 'bg-emerald-500',
      'Statutory MSD': 'bg-emerald-500',
      'Statutory LOI Ack': 'bg-emerald-500',
      'EOR In Progress': 'bg-sky-500',
      'LOA Pending': 'bg-emerald-500',
      'Approved': 'bg-green-700',
      'Rejected': 'bg-red-500',
      'Disqualified': 'bg-red-700'
    };
    return statusColors[status] || 'bg-slate-500';
  };

  return (
    <div className="space-y-6">
      <div className="bg-white rounded-lg border border-slate-200 p-4">
        <div className="flex flex-col lg:flex-row gap-4">
          <div className="flex-1 relative">
            <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, ID, or email..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10"
              data-testid="onboarding-applications-search-input"
            />
          </div>

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

          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger className="w-full lg:w-48" data-testid="onboarding-applications-status-filter">
              <SelectValue placeholder="All Statuses" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Statuses</SelectItem>
              <SelectItem value="Questionnaire Pending">Questionnaire Pending</SelectItem>
              <SelectItem value="Shortlisted">Shortlisted</SelectItem>
              <SelectItem value="Level 1 Pending">Level 1 Pending</SelectItem>
              <SelectItem value="Level 2 Pending">Level 2 Pending</SelectItem>
              <SelectItem value="Level 3 Pending">Level 3 Pending</SelectItem>
              <SelectItem value="EOR In Progress">EOR In Progress</SelectItem>
              <SelectItem value="Approved">Approved</SelectItem>
              <SelectItem value="Rejected">Rejected</SelectItem>
            </SelectContent>
          </Select>

          <div className="flex items-center space-x-2">
            <Checkbox
              id="my-assignments"
              checked={showMyAssignments}
              onCheckedChange={(checked) => setShowMyAssignments(checked as boolean)}
              data-testid="onboarding-applications-assignments-checkbox"
            />
            <Label htmlFor="my-assignments" data-testid="onboarding-applications-assignments-label">My Assignments Only</Label>
          </div>

          <Select value={sortBy} onValueChange={(v) => setSortBy(v as any)}>
            <SelectTrigger className="w-full lg:w-40" data-testid="onboarding-applications-sort-select">
              <SelectValue placeholder="Sort By" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="date">Date</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div className="flex flex-wrap items-center gap-3 mt-4">
          <Button
            variant="outline"
            size="sm"
            onClick={handleExport}
            data-testid="onboarding-applications-export-button"
          >
            <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-applications-reminders-button"
            >
              {isSendingReminders ? (
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
              ) : (
                <Mail className="w-4 h-4 mr-2" />
              )}
              Send Reminders ({selectedIds.length})
            </Button>
          )}

          <div className="ml-auto text-slate-600" data-testid="onboarding-applications-count-text">
            {paginationMeta ? paginationMeta.total : filteredApplications.length} application{paginationMeta?.total !== 1 ? 's' : ''}
          </div>
        </div>
      </div>

      <div className="bg-white rounded-lg border border-slate-200">
        <Table data-testid="onboarding-applications-table">
          <TableHeader>
            <TableRow>
              <TableHead className="w-12">
                <Checkbox
                  checked={selectedIds.length === filteredApplications.length && filteredApplications.length > 0}
                  onCheckedChange={toggleSelectAll}
                  data-testid="onboarding-applications-header-checkbox"
                />
              </TableHead>
              <TableHead>ID</TableHead>
              <TableHead>Name</TableHead>
              <TableHead>Preferred Location</TableHead>
              <TableHead>Status</TableHead>
              <TableHead>Applicant Location</TableHead>
              <TableHead>Progress</TableHead>
              <TableHead>Applied On</TableHead>
              <TableHead>Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredApplications.map((app, idx) => (
              <TableRow key={app.id} data-testid={`onboarding-application-row-${idx}`}>
                <TableCell>
                  <Checkbox
                    checked={selectedIds.includes(app.id)}
                    onCheckedChange={() => toggleSelection(app.id)}
                    data-testid={`onboarding-application-checkbox-${idx}`}
                  />
                </TableCell>
                <TableCell data-testid={`onboarding-application-id-${idx}`}>{app.registrationNumber}</TableCell>
                <TableCell data-testid={`onboarding-application-name-${idx}`}>{app.name}</TableCell>
                <TableCell data-testid={`onboarding-application-pref-location-${idx}`}>{app.preferredLocation}</TableCell>
                <TableCell>
                  <Badge className={getStatusColor(app.status)} data-testid={`onboarding-application-status-${idx}`}>
                    {app.status}
                  </Badge>
                </TableCell>
                <TableCell className="text-slate-600 max-w-xs truncate" data-testid={`onboarding-application-addr-${idx}`}>
                  {app.residentialAddress}
                </TableCell>
                <TableCell>
                  <div className="flex items-center gap-2">
                    <Progress value={app.progress} className="h-2 w-20" data-testid={`onboarding-application-progress-bar-${idx}`} />
                    <span className="text-slate-600" data-testid={`onboarding-application-progress-text-${idx}`}>{app.progress}%</span>
                  </div>
                </TableCell>
                <TableCell data-testid={`onboarding-application-date-${idx}`}>
                  {formatDateTime(app.submissionDate)}
                </TableCell>
                <TableCell>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => onViewDetails(app.id)}
                    data-testid={`onboarding-application-view-btn-${idx}`}
                  >
                    View
                  </Button>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
        
        {paginationMeta && paginationMeta.totalPages > 1 && (
          <div className="py-4 border-t px-4 flex justify-center">
            <Pagination>
              <PaginationContent>
                <PaginationItem>
                  <PaginationPrevious 
                    onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                    className={currentPage === 1 ? "pointer-events-none opacity-50" : "cursor-pointer"}
                  />
                </PaginationItem>
                
                {[...Array(paginationMeta.totalPages)].map((_, i) => {
                  const page = i + 1;
                  // Show current, first, last, and pages around current
                  if (
                    page === 1 || 
                    page === paginationMeta.totalPages || 
                    (page >= currentPage - 1 && page <= currentPage + 1)
                  ) {
                    return (
                      <PaginationItem key={page}>
                        <PaginationLink 
                          isActive={currentPage === page}
                          onClick={() => setCurrentPage(page)}
                          className="cursor-pointer"
                        >
                          {page}
                        </PaginationLink>
                      </PaginationItem>
                    );
                  }
                  if (
                    (page === 2 && currentPage > 3) || 
                    (page === paginationMeta.totalPages - 1 && currentPage < paginationMeta.totalPages - 2)
                  ) {
                    return <PaginationItem key={page}><PaginationEllipsis /></PaginationItem>;
                  }
                  return null;
                })}

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

      <Dialog open={showNewApplicationModal} onOpenChange={setShowNewApplicationModal}>
        <DialogContent className="max-w-2xl" data-testid="onboarding-new-app-modal">
          <DialogHeader>
            <DialogTitle>Add New Application (Admin)</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <p className="text-slate-600">This form allows administrators to manually add applications to the system.</p>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>Name</Label>
                <Input placeholder="Full Name" data-testid="onboarding-new-app-name" />
              </div>
              <div>
                <Label>Email</Label>
                <Input type="email" placeholder="email@example.com" data-testid="onboarding-new-app-email" />
              </div>
              <div>
                <Label>Phone</Label>
                <Input placeholder="+91 XXXXX XXXXX" data-testid="onboarding-new-app-phone" />
              </div>
              <div>
                <Label>Preferred Location</Label>
                <Select>
                  <SelectTrigger data-testid="onboarding-new-app-location-select">
                    <SelectValue placeholder="Select location" />
                  </SelectTrigger>
                  <SelectContent>
                    {locations.map(loc => (
                      <SelectItem key={loc} value={loc}>{loc}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="flex justify-end gap-3">
              <Button variant="outline" onClick={() => setShowNewApplicationModal(false)} data-testid="onboarding-new-app-cancel">
                Cancel
              </Button>
              <Button className="bg-amber-600 hover:bg-amber-700" data-testid="onboarding-new-app-submit">
                Create Application
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
