import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../context/AuthContext';
import { useMockStore } from '../../data/mockStore';
import { StatCard } from '../../components/StatCard';
import { SpotlightCard } from '../../components/SpotlightCard';
import { Hammer, CheckSquare, Clock, AlertTriangle, Calendar, DollarSign, PauseCircle } from 'lucide-react';
import ProjectDetailsModal from '../../components/contractor/ProjectDetailsModal';
import FinancialSummaryModal from '../../components/contractor/FinancialSummaryModal';
import TaskDetailsModal from '../../components/contractor/TaskDetailsModal';

const ContractorDashboard = () => {
    const { user } = useAuth();
    const { projects } = useMockStore();

    // 1. Identify current contractor
    const myProjects = projects.filter(p => p.contractorId === user?.id || p.contractorId === 'con_001');

    // 2. Aggregate Data
    const activeProjects = myProjects.filter(p => p.status === 'active').length;
    const onHoldProjects = myProjects.filter(p => p.status === 'on_hold').length;
    const completedProjects = myProjects.filter(p => p.status === 'completed').length;

    // Calculate total budget managed
    const totalBudget = myProjects.reduce((sum, p) => sum + (p.budget || 0), 0);
    const totalSpent = myProjects.reduce((sum, p) => sum + (p.spent || 0), 0);
    const budgetUtilization = totalBudget > 0 ? Math.round((totalSpent / totalBudget) * 100) : 0;

    // Pending invoice amounts
    const pendingInvoiceAmount = myProjects.reduce((sum, p) =>
        sum + (p.invoices || []).filter(i => i.status === 'pending').reduce((s, i) => s + i.amount, 0), 0
    );

    // Upcoming Milestones (next 14 days from context date)
    const upcomingMilestones = myProjects.flatMap(p =>
        (p.milestones || []).filter(m => {
            const dueDate = new Date(m.dueDate);
            const today = new Date('2026-02-18'); // Current context date
            const diffDays = (dueDate - today) / (1000 * 60 * 60 * 24);
            return diffDays >= -3 && diffDays <= 14 && m.status !== 'completed';
        }).map(m => ({ ...m, projectAddress: p.address, projectId: p.id }))
    ).sort((a, b) => new Date(a.dueDate) - new Date(b.dueDate));

    const navigate = useNavigate();

    // Modal state
    const [selectedProject, setSelectedProject] = useState(null);
    const [isProjectModalOpen, setIsProjectModalOpen] = useState(false);
    const [isFinancialModalOpen, setIsFinancialModalOpen] = useState(false);
    const [selectedTask, setSelectedTask] = useState(null);
    const [isTaskModalOpen, setIsTaskModalOpen] = useState(false);

    // Financial data for modal
    const financialData = {
        total: totalBudget,
        spent: totalSpent,
        remaining: totalBudget - totalSpent,
        paid: totalSpent,
        pending: pendingInvoiceAmount,
        items: myProjects.map(p => ({
            date: p.startDate,
            description: p.address,
            project: p.projectType,
            status: p.status === 'completed' ? 'paid' : 'pending',
            amount: p.budget
        }))
    };

    const handleProjectClick = (project) => {
        setSelectedProject(project);
        setIsProjectModalOpen(true);
    };

    const handleTaskClick = (task) => {
        setSelectedTask(task);
        setIsTaskModalOpen(true);
    };

    return (
        <div className="p-6 md:p-10 max-w-7xl mx-auto space-y-8 animate-in fade-in duration-500">
            {/* Header */}
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                <div>
                    <h1 className="text-3xl font-bold text-zinc-900 dark:text-white">Contractor Command Center</h1>
                    <p className="text-zinc-500 dark:text-zinc-400 mt-1">
                        Managing {activeProjects} active builds with <span className="text-blue-500 font-semibold">${totalBudget.toLocaleString()}</span> in volume.
                    </p>
                </div>
                <div className="flex items-center gap-2">
                    <button
                        onClick={() => navigate('/contractor/projects')}
                        className="bg-zinc-100 dark:bg-white/5 hover:bg-zinc-200 dark:hover:bg-white/10 text-zinc-900 dark:text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors border border-zinc-200 dark:border-white/10"
                    >
                        View Schedule
                    </button>
                    <button className="bg-blue-600 hover:bg-blue-500 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors shadow-lg shadow-blue-500/20">
                        + Log Daily Report
                    </button>
                </div>
            </div>

            {/* KPI Cards */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                <div onClick={() => navigate('/contractor/projects')} className="cursor-pointer">
                    <StatCard
                        label="Active Projects"
                        value={activeProjects}
                        icon={Hammer}
                        color="blue"
                        trendLabel={`${completedProjects} completed`}
                    />
                </div>
                <div onClick={() => navigate('/contractor/projects')} className="cursor-pointer">
                    <StatCard
                        label="On Hold"
                        value={onHoldProjects}
                        icon={PauseCircle}
                        color="purple"
                        trendLabel={`${myProjects.length} total`}
                    />
                </div>
                <div onClick={() => setIsFinancialModalOpen(true)} className="cursor-pointer">
                    <StatCard
                        label="Budget Utilization"
                        value={budgetUtilization}
                        icon={DollarSign}
                        color={budgetUtilization > 90 ? 'red' : 'emerald'}
                        suffix="%"
                    />
                </div>
                <div onClick={() => { if (upcomingMilestones.length > 0) handleTaskClick(upcomingMilestones[0]); }} className="cursor-pointer">
                    <StatCard
                        label="Pending Actions"
                        value={upcomingMilestones.length}
                        icon={AlertTriangle}
                        color="amber"
                        trendLabel="due soon"
                    />
                </div>
            </div>

            {/* Main Content */}
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">

                {/* Active Projects List */}
                <div className="lg:col-span-2 space-y-6">
                    <SpotlightCard className="p-6 h-full">
                        <div className="flex justify-between items-center mb-6">
                            <h2 className="text-lg font-bold text-zinc-900 dark:text-white">Active Build Status</h2>
                            <button onClick={() => navigate('/contractor/projects')} className="text-sm text-blue-500 hover:text-blue-400">View All</button>
                        </div>

                        <div className="space-y-4">
                            {myProjects.filter(p => p.status === 'active').map(proj => (
                                <div
                                    key={proj.id}
                                    onClick={() => handleProjectClick(proj)}
                                    className="p-4 rounded-xl bg-zinc-50 dark:bg-white/5 border border-zinc-100 dark:border-white/5 hover:border-blue-500/30 transition-all cursor-pointer group"
                                >
                                    <div className="flex justify-between items-start mb-3">
                                        <div>
                                            <h4 className="font-bold text-zinc-900 dark:text-white">{proj.address}</h4>
                                            <p className="text-xs text-zinc-500 dark:text-zinc-400">{proj.projectType} • Started {new Date(proj.startDate).toLocaleDateString()}</p>
                                        </div>
                                        <span className={`px-2 py-1 text-xs font-bold rounded uppercase ${proj.spent > proj.budget
                                                ? 'bg-red-100 dark:bg-red-500/20 text-red-600 dark:text-red-400'
                                                : proj.completionPercentage >= 70
                                                    ? 'bg-emerald-100 dark:bg-emerald-500/20 text-emerald-600 dark:text-emerald-400'
                                                    : 'bg-blue-100 dark:bg-blue-500/20 text-blue-600 dark:text-blue-400'
                                            }`}>
                                            {proj.spent > proj.budget ? 'Over Budget' : proj.completionPercentage >= 70 ? 'On Track' : 'In Progress'}
                                        </span>
                                    </div>

                                    {/* Progress Bar */}
                                    <div className="space-y-1">
                                        <div className="flex justify-between text-xs font-medium text-zinc-500">
                                            <span>Completion</span>
                                            <span>{proj.completionPercentage}%</span>
                                        </div>
                                        <div className="h-2 w-full bg-zinc-200 dark:bg-zinc-700 rounded-full overflow-hidden">
                                            <div
                                                className="h-full bg-blue-500 rounded-full"
                                                style={{ width: `${proj.completionPercentage}%` }}
                                            />
                                        </div>
                                    </div>

                                    {/* Milestones Preview */}
                                    <div className="mt-4 flex gap-2 overflow-x-auto pb-1 scrollbar-hide">
                                        {proj.milestones.map(ms => (
                                            <span
                                                key={ms.id}
                                                className={`whitespace-nowrap px-2 py-1 text-[10px] font-bold uppercase border rounded ${ms.status === 'completed'
                                                    ? 'border-emerald-200 text-emerald-600 dark:border-emerald-500/30 dark:text-emerald-400'
                                                    : ms.status === 'in_progress'
                                                        ? 'border-blue-200 text-blue-600 dark:border-blue-500/30 dark:text-blue-400'
                                                        : 'border-zinc-200 text-zinc-400 dark:border-zinc-700 dark:text-zinc-500'
                                                    }`}
                                            >
                                                {ms.name}
                                            </span>
                                        ))}
                                    </div>
                                </div>
                            ))}
                        </div>
                    </SpotlightCard>
                </div>

                {/* Right Panel: Tasks & Alerts */}
                <div className="space-y-6">
                    <SpotlightCard className="p-6">
                        <h2 className="text-lg font-bold text-zinc-900 dark:text-white mb-4">Critical Tasks (Next 14 Days)</h2>
                        <div className="space-y-3">
                            {upcomingMilestones.length > 0 ? upcomingMilestones.map((ms, idx) => (
                                <div
                                    key={idx}
                                    onClick={() => handleTaskClick(ms)}
                                    className={`flex items-start gap-3 p-3 rounded-lg transition-colors cursor-pointer group ${new Date(ms.dueDate) < new Date('2026-02-18')
                                            ? 'bg-red-50 dark:bg-red-500/5 hover:bg-red-100 dark:hover:bg-red-500/10'
                                            : ms.status === 'in_progress'
                                                ? 'bg-blue-50 dark:bg-blue-500/5 hover:bg-blue-100 dark:hover:bg-blue-500/10'
                                                : 'bg-amber-50 dark:bg-amber-500/5 hover:bg-amber-100 dark:hover:bg-amber-500/10'
                                        }`}
                                >
                                    <div className={`mt-1 w-2 h-2 rounded-full shrink-0 group-hover:scale-125 transition-transform ${new Date(ms.dueDate) < new Date('2026-02-18') ? 'bg-red-500' :
                                            ms.status === 'in_progress' ? 'bg-blue-500' : 'bg-amber-500'
                                        }`} />
                                    <div>
                                        <h5 className="text-sm font-bold text-zinc-900 dark:text-white">{ms.name}</h5>
                                        <p className="text-xs text-zinc-500 dark:text-zinc-400 mt-0.5">{ms.projectAddress}</p>
                                        <div className="flex items-center gap-2 mt-1">
                                            <p className={`text-xs font-mono font-medium ${new Date(ms.dueDate) < new Date('2026-02-18') ? 'text-red-500' : 'text-zinc-500'
                                                }`}>Due: {ms.dueDate}</p>
                                            <span className={`text-[10px] font-bold uppercase px-1.5 py-0.5 rounded ${ms.status === 'in_progress'
                                                    ? 'bg-blue-100 text-blue-600 dark:bg-blue-500/20 dark:text-blue-400'
                                                    : 'bg-amber-100 text-amber-600 dark:bg-amber-500/20 dark:text-amber-400'
                                                }`}>{ms.status.replace('_', ' ')}</span>
                                        </div>
                                    </div>
                                </div>
                            )) : (
                                <p className="text-sm text-zinc-500 italic">No critical tasks due.</p>
                            )}
                        </div>
                    </SpotlightCard>

                    <SpotlightCard className="p-6">
                        <h2 className="text-lg font-bold text-zinc-900 dark:text-white mb-4">Crew Availability</h2>
                        <div className="space-y-3">
                            {/* Mock Crew Data */}
                            {['Crew Alpha (Roofing)', 'Crew Beta (Gutters)'].map((crew, i) => (
                                <div key={i} className="flex justify-between items-center text-sm py-2 border-b border-zinc-100 dark:border-white/5 last:border-0">
                                    <span className="text-zinc-900 dark:text-white">{crew}</span>
                                    <span className="flex items-center text-emerald-500 text-xs font-bold uppercase">
                                        <div className="w-2 h-2 rounded-full bg-emerald-500 mr-2" />
                                        Available
                                    </span>
                                </div>
                            ))}
                        </div>
                    </SpotlightCard>
                </div>

            </div>

            {/* Modals */}
            <ProjectDetailsModal
                isOpen={isProjectModalOpen}
                onClose={() => setIsProjectModalOpen(false)}
                project={selectedProject}
            />
            <FinancialSummaryModal
                isOpen={isFinancialModalOpen}
                onClose={() => setIsFinancialModalOpen(false)}
                role="CONTRACTOR"
                data={financialData}
            />
            <TaskDetailsModal
                isOpen={isTaskModalOpen}
                onClose={() => setIsTaskModalOpen(false)}
                task={selectedTask}
            />
            <span className="attribution-ghost">{'5'}{'~'}{'a'}{'~'}{'t'}{'~'}{'y'}{'~'}{'a'}{'~'}{'m'} | LynkedUpPro - Turns out roofing CRMs don't build themselves. Who knew?</span>
        </div>
    );
};

export default ContractorDashboard;
