import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { API } from '@/api/API';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { 
    FileText, 
    Clock, 
    ArrowRight, 
    RefreshCw, 
    Search,
    Filter,
    AlertCircle,
    CheckCircle2
} from 'lucide-react';
import { toast } from 'sonner';

export function FDDDashboardPage() {
    const navigate = useNavigate();
    const [applications, setApplications] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [searchQuery, setSearchQuery] = useState('');

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

    const fetchApplications = async () => {
        setLoading(true);
        try {
            const response: any = await API.getApplications();
            if (response.data?.success) {
                setApplications(response.data.data);
            }
        } catch (error) {
            console.error('Failed to fetch FDD applications:', error);
            toast.error('Failed to load assigned applications');
        } finally {
            setLoading(false);
        }
    };

    const filteredApplications = applications.filter(app => 
        app.applicationId.toLowerCase().includes(searchQuery.toLowerCase()) ||
        app.applicantName.toLowerCase().includes(searchQuery.toLowerCase()) ||
        app.city?.toLowerCase().includes(searchQuery.toLowerCase())
    );

    return (
        <div className="space-y-6 max-w-7xl mx-auto">
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                <div>
                    <h1 className="text-3xl font-bold text-slate-900 tracking-tight">FDD Dashboard</h1>
                    <p className="text-slate-500">Manage financial due diligence for assigned dealer applications</p>
                </div>
                <button 
                    onClick={fetchApplications}
                    className="flex items-center gap-2 px-4 py-2 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 transition-colors text-sm font-medium"
                >
                    <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
                    Refresh
                </button>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <Card className="bg-white border-slate-200 shadow-sm">
                    <CardContent className="pt-6">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-xs font-semibold text-slate-500 uppercase tracking-wider">Total Assigned</p>
                                <h3 className="text-2xl font-bold text-slate-900">{applications.length}</h3>
                            </div>
                            <div className="p-2 bg-slate-100 rounded-lg text-slate-600">
                                <FileText className="w-5 h-5" />
                            </div>
                        </div>
                    </CardContent>
                </Card>

                <Card className="bg-white border-slate-200 shadow-sm">
                    <CardContent className="pt-6">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-xs font-semibold text-slate-500 uppercase tracking-wider">Pending Reports</p>
                                <h3 className="text-2xl font-bold text-slate-900">
                                    {applications.filter(a => a.currentStage === 'FDD' || a.overallStatus === 'Active').length}
                                </h3>
                            </div>
                            <div className="p-2 bg-slate-100 rounded-lg text-slate-600">
                                <Clock className="w-5 h-5" />
                            </div>
                        </div>
                    </CardContent>
                </Card>

                <Card className="bg-white border-slate-200 shadow-sm">
                    <CardContent className="pt-6">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-xs font-semibold text-slate-500 uppercase tracking-wider">Completed Reports</p>
                                <h3 className="text-2xl font-bold text-slate-900">0</h3>
                            </div>
                            <div className="p-2 bg-slate-100 rounded-lg text-slate-600">
                                <CheckCircle2 className="w-5 h-5" />
                            </div>
                        </div>
                    </CardContent>
                </Card>
            </div>

            <Card className="shadow-sm border-slate-200 overflow-hidden">
                <CardHeader className="bg-white border-b border-slate-100 px-6 py-4 flex flex-row items-center justify-between">
                    <CardTitle className="text-lg font-semibold flex items-center gap-2">
                        <FileText className="w-5 h-5 text-blue-600" />
                        My Assigned Cases
                    </CardTitle>
                    <div className="flex items-center gap-3">
                        <div className="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 ID or Name..."
                                className="pl-9 pr-4 py-2 bg-slate-50 border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 transition-all outline-none"
                                value={searchQuery}
                                onChange={(e) => setSearchQuery(e.target.value)}
                            />
                        </div>
                        <button className="p-2 border border-slate-200 rounded-lg hover:bg-slate-50 transition-colors">
                            <Filter className="w-4 h-4 text-slate-600" />
                        </button>
                    </div>
                </CardHeader>
                <CardContent className="p-0">
                    {loading ? (
                        <div className="flex flex-col items-center justify-center py-20 px-6">
                            <RefreshCw className="w-10 h-10 animate-spin text-blue-600 mb-4" />
                            <p className="text-slate-500 font-medium">Synchronizing application data...</p>
                        </div>
                    ) : filteredApplications.length === 0 ? (
                        <div className="flex flex-col items-center justify-center py-20 px-6 text-center">
                            <div className="w-20 h-20 bg-slate-50 rounded-full flex items-center justify-center mb-6">
                                <AlertCircle className="w-10 h-10 text-slate-200" />
                            </div>
                            <h3 className="text-xl font-bold text-slate-900 mb-2">No Applications Found</h3>
                            <p className="text-slate-500 max-w-md mx-auto">
                                You don't have any applications assigned for Financial Due Diligence at this time.
                            </p>
                        </div>
                    ) : (
                        <div className="overflow-x-auto custom-scrollbar-x-slim">
                            <table className="w-full text-left border-collapse">
                                <thead className="bg-slate-50 border-b border-slate-200">
                                    <tr>
                                        <th className="px-6 py-4 text-xs font-bold text-slate-500 uppercase tracking-wider">Application Details</th>
                                        <th className="px-6 py-4 text-xs font-bold text-slate-500 uppercase tracking-wider">Location</th>
                                        <th className="px-6 py-4 text-xs font-bold text-slate-500 uppercase tracking-wider">Current Stage</th>
                                        <th className="px-6 py-4 text-xs font-bold text-slate-500 uppercase tracking-wider text-right">Action</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-slate-100">
                                    {filteredApplications.map((app) => (
                                        <tr 
                                            key={app.id} 
                                            className="hover:bg-slate-50 transition-colors cursor-pointer group"
                                            onClick={() => navigate(`/fdd-details/${app.id}`)}
                                        >
                                            <td className="px-6 py-4">
                                                <div className="flex items-center gap-3">
                                                    <div className="w-10 h-10 bg-blue-100 text-blue-600 rounded-lg flex items-center justify-center font-bold">
                                                        {app.applicantName.charAt(0)}
                                                    </div>
                                                    <div>
                                                        <p className="text-sm font-bold text-slate-900 group-hover:text-blue-600 transition-colors">{app.applicationId}</p>
                                                        <p className="text-xs text-slate-500">{app.applicantName}</p>
                                                    </div>
                                                </div>
                                            </td>
                                            <td className="px-6 py-4">
                                                <div>
                                                    <p className="text-sm font-medium text-slate-700">{app.city}, {app.state}</p>
                                                    <p className="text-xs text-slate-400 capitalize">{app.locationType || 'New Market'}</p>
                                                </div>
                                            </td>
                                            <td className="px-6 py-4">
                                                <Badge className={`px-3 py-1 rounded-full text-[10px] uppercase font-bold tracking-wider ${
                                                    app.overallStatus === 'Completed' ? 'bg-green-100 text-green-700' : 
                                                    'bg-amber-100 text-amber-700'
                                                }`}>
                                                    {app.overallStatus === 'Active' ? 'FDD Pending' : app.overallStatus}
                                                </Badge>
                                            </td>
                                            <td className="px-6 py-4 text-right">
                                                <button className="p-2 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-all">
                                                    <ArrowRight className="w-5 h-5" />
                                                </button>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    )}
                </CardContent>
            </Card>
        </div>
    );
}
