import { useState, useEffect } from 'react';
import { Application, ApplicationStatus } 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 {
    Search,
    Download,
    Database,
    Loader2,
    CheckSquare,
    Calendar
} from 'lucide-react';
import {
    Pagination,
    PaginationContent,
    PaginationEllipsis,
    PaginationItem,
    PaginationLink,
    PaginationNext,
    PaginationPrevious,
} from "@/components/ui/pagination";
import { Checkbox } from '@/components/ui/checkbox';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { toast } from 'sonner';
import { formatDateTime } from '@/components/ui/utils';

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

export function NonOpportunitiesPage({ onViewDetails }: NonOpportunitiesPageProps) {
    const [searchQuery, setSearchQuery] = useState('');
    const [locationFilter, setLocationFilter] = useState<string>('all');
    const [stateFilter, setStateFilter] = useState<string>('all');
    const [fromDate, setFromDate] = useState<string>('');
    const [toDate, setToDate] = useState<string>('');
    const [currentPage, setCurrentPage] = useState(1);
    const [paginationMeta, setPaginationMeta] = useState<any>(null);

    // Real data integration
    const [applicationsData, setApplicationsData] = useState<Application[]>([]);
    const [isGlobalLoading, setIsGlobalLoading] = useState(true);
    const [states, setStates] = useState<string[]>([]);
    const [locations, setLocations] = useState<string[]>([]);
    const [selectedIds, setSelectedIds] = useState<string[]>([]);
    const [isBulkConverting, setIsBulkConverting] = useState(false);
    
    const handleBulkConvert = async () => {
        if (selectedIds.length === 0) return;
        
        try {
            setIsBulkConverting(true);
            const res = await onboardingService.bulkConvertToOpportunity({ ids: selectedIds });
            if (res?.success) {
                // If some succeeded, show success message
                if (res.data?.success > 0 || !res.data) {
                    toast.success(res.message || `Successfully converted ${res.data?.success || selectedIds.length} leads.`);
                }
                
                // If some failed, show specific error messages as requested
                if (res.data?.failed > 0 && res.data?.errors) {
                    res.data.errors.forEach((err: string) => {
                        toast.error(err, { duration: 5000 });
                    });
                }
                
                setSelectedIds([]);
                await fetchApplications();
            }
        } catch (error: any) {
            console.error('Bulk conversion error:', error);
            toast.error(error.message || 'Failed to perform bulk conversion');
        } finally {
            setIsBulkConverting(false);
        }
    };

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

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

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

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

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

    const fetchStates = async () => {
        try {
            const response = await masterService.getStates();
            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 {
            setIsGlobalLoading(true);
            const response = await onboardingService.getApplications({
                fromDate,
                toDate,
                search: searchQuery,
                status: 'Submitted',
                isShortlisted: 'false',
                location: locationFilter !== 'all' ? locationFilter : undefined,
                state: stateFilter !== 'all' ? stateFilter : undefined,
                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, // Backend provides this
                // 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
            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 non-opportunity requests');
        } finally {
            setIsGlobalLoading(false);
        }
    };

    const filteredLeads = applicationsData;

    return (
        <div className="space-y-6">
            {/* Header */}
            <div>
                <h2 className="text-2xl mb-2">Non-opportunities (Lead Generation)</h2>
                <p className="text-slate-600">
                    Interest submissions from regions where dealerships are currently not being offered. These leads received non-opportunity notification and are stored for future reference.
                </p>
            </div>

            {/* Stats */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="bg-white rounded-lg border border-slate-200 p-4" data-testid="onboarding-non-opps-stat-total">
                    <div className="flex items-center justify-between">
                        <div>
                            <p className="text-slate-600">Total Leads</p>
                            <p className="text-2xl text-slate-900 mt-1">{paginationMeta?.total || applicationsData.length}</p>
                        </div>
                        <div className="p-3 bg-blue-100 rounded-lg">
                            <Database className="w-6 h-6 text-blue-600" />
                        </div>
                    </div>
                </div>
                <div className="bg-white rounded-lg border border-slate-200 p-4" data-testid="onboarding-non-opps-stat-locations">
                    <p className="text-slate-600">Unique Locations</p>
                    <p className="text-2xl text-slate-900 mt-1">
                        {paginationMeta?.stats?.uniqueLocations || 0}
                    </p>
                </div>
                <div className="bg-white rounded-lg border border-slate-200 p-4" data-testid="onboarding-non-opps-stat-exp">
                    <p className="text-slate-600">With Experience</p>
                    <p className="text-2xl text-amber-600 mt-1">
                        {paginationMeta?.stats?.withExperience || 0}
                    </p>
                </div>
            </div>

            {/* Filters and Actions */}
            <div className="flex flex-col lg: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, email, phone, or registration number..."
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        className="pl-10"
                        data-testid="onboarding-non-opps-search-input"
                    />
                </div>

                <div className="flex items-center gap-2">
                    <Popover>
                        <PopoverTrigger asChild>
                            <Button
                                variant="outline"
                                className={cn(
                                    "w-full md:w-36 justify-start text-left font-normal h-10 px-3",
                                    !fromDate && "text-muted-foreground"
                                )}
                                data-testid="onboarding-non-opps-from-date-trigger"
                            >
                                <Calendar className="mr-2 h-4 w-4 text-slate-400" />
                                {fromDate ? format(new Date(fromDate), "PP") : <span className="text-xs text-slate-500">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-36 justify-start text-left font-normal h-10 px-3",
                                    !toDate && "text-muted-foreground"
                                )}
                                data-testid="onboarding-non-opps-to-date-trigger"
                            >
                                <Calendar className="mr-2 h-4 w-4 text-slate-400" />
                                {toDate ? format(new Date(toDate), "PP") : <span className="text-xs text-slate-500">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={locationFilter} onValueChange={setLocationFilter}>
                    <SelectTrigger className="w-full lg:w-48" data-testid="onboarding-non-opps-location-select">
                        <SelectValue placeholder="All Locations" />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem value="all">All Locations</SelectItem>
                        {locations.map((location) => (
                            <SelectItem key={location} value={location}>{location}</SelectItem>
                        ))}
                    </SelectContent>
                </Select>

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

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

                <Button variant="outline" size="icon" data-testid="onboarding-non-opps-export-btn">
                    <Download className="w-4 h-4" />
                </Button>

                {selectedIds.length > 0 && (
                    <Button 
                        className="bg-amber-600 hover:bg-amber-700 font-bold"
                        onClick={handleBulkConvert}
                        disabled={isBulkConverting}
                    >
                        {isBulkConverting ? (
                            <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                        ) : (
                            <CheckSquare className="w-4 h-4 mr-2" />
                        )}
                        Convert {selectedIds.length} to Opportunity
                    </Button>
                )}
            </div>

            {/* Lead Generation Table */}
            <div className="bg-white rounded-lg border border-slate-200 overflow-hidden" data-testid="onboarding-non-opps-table-container">
                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead className="w-12">
                                <Checkbox 
                                    checked={filteredLeads.length > 0 && selectedIds.length === filteredLeads.length}
                                    onCheckedChange={toggleSelectAll}
                                />
                            </TableHead>
                            <TableHead data-testid="onboarding-non-opps-th-name">Name</TableHead>
                            <TableHead data-testid="onboarding-non-opps-th-phone">Phone</TableHead>
                            <TableHead data-testid="onboarding-non-opps-th-email">Email</TableHead>
                            <TableHead data-testid="onboarding-non-opps-th-loc">Preferred Location</TableHead>
                            <TableHead data-testid="onboarding-non-opps-th-address">Main Address</TableHead>
                            <TableHead data-testid="onboarding-non-opps-th-age">Age</TableHead>
                            <TableHead data-testid="onboarding-non-opps-th-exp">Experience</TableHead>
                            <TableHead data-testid="onboarding-non-opps-th-edu">Education</TableHead>
                            <TableHead data-testid="onboarding-non-opps-th-date">Applied On</TableHead>
                            <TableHead className="text-right" data-testid="onboarding-non-opps-th-actions">Actions</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {isGlobalLoading ? (
                            <TableRow>
                                <TableCell colSpan={11} className="text-center py-20">
                                    <Loader2 className="w-8 h-8 mx-auto animate-spin text-amber-600 mb-2" />
                                    <p className="text-slate-500 text-sm">Loading applications...</p>
                                </TableCell>
                            </TableRow>
                        ) : filteredLeads.length === 0 ? (
                            <TableRow>
                                <TableCell colSpan={11} className="text-center py-12 text-slate-500" data-testid="onboarding-non-opps-empty-state">
                                    <Database className="w-12 h-12 mx-auto mb-4 text-slate-400" />
                                    <p className="text-lg mb-2">No lead generation data found</p>
                                    <p className="text-sm">Try adjusting your filters</p>
                                </TableCell>
                            </TableRow>
                        ) : (
                            filteredLeads.map((lead, idx) => (
                                <TableRow 
                                    key={lead.id} 
                                    data-testid={`onboarding-non-opps-row-${idx}`}
                                    className={selectedIds.includes(lead.id) ? 'bg-amber-50/50' : ''}
                                >
                                    <TableCell>
                                        <Checkbox 
                                            checked={selectedIds.includes(lead.id)}
                                            onCheckedChange={() => toggleSelectRow(lead.id)}
                                        />
                                    </TableCell>
                                    <TableCell>
                                        <div>
                                            <p className="text-slate-900" data-testid={`onboarding-non-opps-name-${idx}`}>{lead.name}</p>
                                            <p className="text-slate-500 text-sm" data-testid={`onboarding-non-opps-id-${idx}`}>{lead.registrationNumber}</p>
                                        </div>
                                    </TableCell>
                                    <TableCell className="text-slate-900" data-testid={`onboarding-non-opps-phone-${idx}`}>{lead.phone}</TableCell>
                                    <TableCell className="text-slate-600" data-testid={`onboarding-non-opps-email-${idx}`}>{lead.email}</TableCell>
                                    <TableCell>
                                        <div data-testid={`onboarding-non-opps-pref-loc-${idx}`}>
                                            <p className="text-slate-900">{lead.preferredLocation}</p>
                                            <p className="text-slate-500 text-sm">{lead.state}</p>
                                        </div>
                                    </TableCell>
                                    <TableCell className="text-slate-600 max-w-xs truncate" data-testid={`onboarding-non-opps-address-${idx}`}>{lead.residentialAddress}</TableCell>
                                    <TableCell className="text-slate-900" data-testid={`onboarding-non-opps-age-${idx}`}>{lead.age}</TableCell>
                                    <TableCell className="text-slate-600" data-testid={`onboarding-non-opps-experience-${idx}`}>{lead.pastExperience}</TableCell>
                                    <TableCell className="text-slate-900" data-testid={`onboarding-non-opps-education-${idx}`}>{lead.education}</TableCell>
                                    <TableCell className="text-slate-600" data-testid={`onboarding-non-opps-date-${idx}`}>
                                        {formatDateTime(lead.submissionDate)}
                                    </TableCell>
                                    <TableCell className="text-right">
                                        <div className="flex justify-end gap-2">
                                            <Button
                                                variant="outline"
                                                size="sm"
                                                onClick={() => onViewDetails(lead.id)}
                                                data-testid={`onboarding-non-opps-view-btn-${idx}`}
                                            >
                                                View
                                            </Button>
                                        </div>
                                    </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;
                                    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>
        </div>
    );
}
