import React, { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../context/AuthContext';
import { useMockStore } from '../../data/mockStore';
import FinancialKPICards from '../../components/owner/FinancialKPICards';
import UrgentItemsPanel from '../../components/owner/UrgentItemsPanel';
import FinancialDetailsModal from '../../components/owner/FinancialDetailsModal';
import ActionCenterModal from '../../components/owner/ActionCenterModal';
import TeamManagementPanel from '../../components/owner/TeamManagementPanel';
import CommissionDistributionPanel from '../../components/owner/CommissionDistributionPanel';
import { SpotlightCard } from '../../components/SpotlightCard';
import {
    BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Legend
} from 'recharts';
import {
    Briefcase, TrendingUp, AlertTriangle, Shield, ChevronRight, ArrowUpRight, Users, ChevronDown
} from 'lucide-react';

const OwnerSnapshot = () => {
    const { user } = useAuth();
    const navigate = useNavigate();
    const {
        owners, projects, users, personnel,
        orgCommissionDefaults, userCommissionOverrides,
        roleCommissionOverrides, orgMembers,
        addJobTeamMember, removeJobTeamMember, updateJobTeamMember,
    } = useMockStore();

    // Find the current owner profile
    const owner = useMemo(() =>
        owners?.find(o => o.id === user?.id) || null
        , [owners, user]);

    // Filter projects for this owner
    const ownerProjects = useMemo(() =>
        projects.filter(p => p.ownerId === user?.id)
        , [projects, user]);

    // Modal States
    const [financialModal, setFinancialModal] = useState({ isOpen: false, type: 'revenue' });
    const [actionModal, setActionModal] = useState({ isOpen: false, filter: 'all' });

    // ── Team Management (Owner's Box) ──────────────────────────────────────
    const [selectedProjectId, setSelectedProjectId] = useState(null);
    const selectedProject = useMemo(() => {
        const id = selectedProjectId || ownerProjects.find(p => p.status === 'active')?.id;
        return ownerProjects.find(p => p.id === id) || ownerProjects[0] || null;
    }, [selectedProjectId, ownerProjects]);

    const teamFinancials = useMemo(() => {
        if (!selectedProject) return { totalReceived: 0, grossProfit: 0 };
        const paid = (selectedProject.paymentSchedule || [])
            .filter(ps => ps.status === 'paid')
            .reduce((s, ps) => s + (ps.amount || 0), 0);
        const totalReceived = paid || (selectedProject.budget || 0);
        const totalCosts = Number(selectedProject.actualCost ?? selectedProject.spent) || 0;
        return { totalReceived, grossProfit: totalReceived - totalCosts };
    }, [selectedProject]);

    const handleFinancialClick = (type) => {
        setFinancialModal({ isOpen: true, type });
    };

    const handleActionClick = (id) => {
        const filterMap = { docs: 'docs', vendors: 'vendors', invoices: 'invoices', all: 'all' };
        setActionModal({ isOpen: true, filter: filterMap[id] || 'all' });
    };

    // Greeting
    const hour = new Date().getHours();
    const greeting = hour < 12 ? 'Good Morning' : hour < 18 ? 'Good Afternoon' : 'Good Evening';

    // --- Derived Stats ---
    const projectStats = useMemo(() => {
        const active = ownerProjects.filter(p => p.status === 'active').length;
        const completed = ownerProjects.filter(p => p.status === 'completed').length;
        const delayed = ownerProjects.filter(p => p.status === 'delayed').length;
        const onHold = ownerProjects.filter(p => p.status === 'on_hold').length;
        const disputed = ownerProjects.filter(p => p.status === 'disputed').length;
        const totalBudget = ownerProjects.reduce((sum, p) => sum + (p.approvedBudget || p.budget || 0), 0);
        const totalSpent = ownerProjects.reduce((sum, p) => sum + (p.actualCost || p.spent || 0), 0);
        const avgHealth = ownerProjects.length > 0
            ? Math.round(ownerProjects.reduce((sum, p) => sum + (p.healthScore || 0), 0) / ownerProjects.length)
            : 0;
        return { active, completed, delayed, onHold, disputed, totalBudget, totalSpent, avgHealth, total: ownerProjects.length };
    }, [ownerProjects]);

    // --- Chart Data ---
    const statusChartData = useMemo(() => [
        { name: 'Active', value: projectStats.active, color: '#22c55e' },
        { name: 'Completed', value: projectStats.completed, color: '#3b82f6' },
        { name: 'Delayed', value: projectStats.delayed, color: '#f59e0b' },
        { name: 'On Hold', value: projectStats.onHold, color: '#a855f7' },
        { name: 'Disputed', value: projectStats.disputed, color: '#ef4444' },
    ].filter(d => d.value > 0), [projectStats]);

    const budgetChartData = useMemo(() =>
        ownerProjects.slice(0, 6).map(p => ({
            name: p.projectType.length > 14 ? p.projectType.slice(0, 14) + '...' : p.projectType,
            budget: (p.approvedBudget || p.budget || 0) / 1000,
            spent: (p.actualCost || p.spent || 0) / 1000,
        }))
        , [ownerProjects]);

    const monthlySpendData = owner?.dashboardSummary?.monthlySpend || [];

    // Activity feed from owner's projects
    const activityFeed = useMemo(() => {
        const items = [];
        ownerProjects.forEach(p => {
            if (p.activityTimeline) {
                p.activityTimeline.forEach(a => items.push({ ...a, projectType: p.projectType, projectId: p.id }));
            }
        });
        // Sort by date desc, take top 5
        items.sort((a, b) => new Date(b.date) - new Date(a.date));
        return items.slice(0, 5);
    }, [ownerProjects]);

    const formatCurrency = (val) => {
        if (val >= 1000000) return `$${(val / 1000000).toFixed(1)}M`;
        if (val >= 1000) return `$${(val / 1000).toFixed(0)}k`;
        return `$${val}`;
    };

    const getRiskColor = (score) => {
        if (score <= 30) return 'text-emerald-500 bg-emerald-100 dark:bg-emerald-500/10';
        if (score <= 60) return 'text-amber-500 bg-amber-100 dark:bg-amber-500/10';
        return 'text-red-500 bg-red-100 dark:bg-red-500/10';
    };

    const getHealthColor = (score) => {
        if (score >= 70) return 'text-emerald-500';
        if (score >= 40) return 'text-amber-500';
        return 'text-red-500';
    };

    const CustomTooltip = ({ active, payload, label }) => {
        if (active && payload?.length) {
            return (
                <div className="bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-white/10 rounded-xl px-4 py-3 shadow-xl text-sm">
                    <p className="font-bold text-zinc-900 dark:text-white mb-1">{label}</p>
                    {payload.map((p, i) => (
                        <p key={i} className="text-zinc-600 dark:text-zinc-400">
                            <span className="font-semibold" style={{ color: p.color }}>{p.name}:</span> ${p.value}k
                        </p>
                    ))}
                </div>
            );
        }
        return null;
    };

    return (
        <div className="min-h-full bg-zinc-50 dark:bg-[#09090b] text-zinc-900 dark:text-white relative pb-20 transition-colors duration-300">
            {/* Ambient Background Glows */}
            <div className="fixed top-0 left-0 w-full h-full overflow-hidden pointer-events-none z-0">
                <div className="absolute top-[-10%] left-[-10%] w-[50%] h-[50%] bg-purple-500/5 dark:bg-purple-900/10 rounded-full blur-[120px]" />
                <div className="absolute bottom-[-10%] right-[-10%] w-[50%] h-[50%] bg-blue-500/5 dark:bg-blue-900/10 rounded-full blur-[120px]" />
            </div>

            <div className="relative z-10 p-4 sm:p-8 max-w-7xl mx-auto space-y-8">

                {/* Header Section */}
                <header className="flex flex-col md:flex-row justify-between items-start md:items-center border-b border-zinc-200 dark:border-white/5 pb-6">
                    <div>
                        <h1 className="text-3xl sm:text-4xl font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-zinc-900 to-zinc-600 dark:from-white dark:to-white/60 tracking-tight">
                            {greeting}, {user?.name?.split(' ')[0] || 'Owner'}
                        </h1>
                        <p className="text-zinc-500 dark:text-zinc-400 mt-2 font-light">
                            {owner ? `${owner.companyName} — ${owner.portfolioSize} projects in portfolio` : "Here's your business snapshot for today."}
                        </p>
                    </div>
                    <div className="mt-4 md:mt-0 flex flex-wrap gap-3">
                        <button className="px-4 py-2 bg-zinc-100 dark:bg-white/5 hover:bg-zinc-200 dark:hover:bg-white/10 rounded-xl text-sm font-bold text-zinc-700 dark:text-zinc-300 transition-colors border border-zinc-200 dark:border-white/5 shadow-sm">
                            Download Report
                        </button>
                        <button
                            onClick={() => navigate('/owner/projects')}
                            className="px-4 py-2 bg-amber-500 hover:bg-amber-600 text-black font-bold rounded-xl text-sm transition-colors shadow-lg shadow-amber-500/20 flex items-center gap-2"
                        >
                            View Projects <ArrowUpRight size={16} />
                        </button>
                    </div>
                </header>

                {/* Quick Stats Row */}
                <section className="grid grid-cols-2 sm:grid-cols-4 gap-4">
                    {[
                        { label: 'Total Projects', value: projectStats.total, icon: Briefcase, color: 'text-blue-500', onClick: () => navigate('/owner/projects') },
                        { label: 'Active', value: projectStats.active, icon: TrendingUp, color: 'text-emerald-500', onClick: () => navigate('/owner/projects') },
                        { label: 'Avg Health', value: `${projectStats.avgHealth}%`, icon: Shield, color: getHealthColor(projectStats.avgHealth), onClick: () => navigate('/owner/projects') },
                        { label: 'Risk Score', value: owner?.riskScore ?? '—', icon: AlertTriangle, color: owner ? getRiskColor(owner.riskScore).split(' ')[0] : 'text-zinc-500', onClick: () => handleActionClick('all') },
                    ].map((stat, i) => (
                        <SpotlightCard key={i} className="p-4 cursor-pointer" onClick={stat.onClick}>
                            <div className="flex items-center gap-3">
                                <div className={`p-2 rounded-xl bg-zinc-100 dark:bg-zinc-800 ${stat.color}`}>
                                    <stat.icon size={18} />
                                </div>
                                <div>
                                    <div className="text-2xl font-extrabold text-zinc-900 dark:text-white">{stat.value}</div>
                                    <div className="text-[10px] uppercase font-bold tracking-wider text-zinc-500">{stat.label}</div>
                                </div>
                            </div>
                        </SpotlightCard>
                    ))}
                </section>

                {/* Financial KPIs */}
                <section>
                    <h2 className="text-xl font-bold text-zinc-900 dark:text-white/90 mb-4 flex items-center">
                        <span className="w-2 h-8 bg-emerald-500 rounded-full mr-3"></span>
                        Financial Overview
                    </h2>
                    <FinancialKPICards onCardClick={handleFinancialClick} ownerId={user?.id} />
                </section>

                {/* Charts Row */}
                <section className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    {/* Budget vs Actual */}
                    <SpotlightCard className="lg:col-span-2 p-6">
                        <h3 className="text-lg font-bold text-zinc-900 dark:text-white mb-1">Budget vs Actual Spend</h3>
                        <p className="text-xs text-zinc-500 dark:text-zinc-400 mb-4">Per project (in $k)</p>
                        <div className="h-64">
                            <ResponsiveContainer width="100%" height={256}>
                                <BarChart data={budgetChartData} barGap={4}>
                                    <XAxis dataKey="name" tick={{ fontSize: 11, fill: '#a1a1aa' }} axisLine={false} tickLine={false} />
                                    <YAxis tick={{ fontSize: 11, fill: '#a1a1aa' }} axisLine={false} tickLine={false} />
                                    <Tooltip content={<CustomTooltip />} />
                                    <Bar dataKey="budget" name="Budget" fill="#3b82f6" radius={[6, 6, 0, 0]} />
                                    <Bar dataKey="spent" name="Spent" fill="#f59e0b" radius={[6, 6, 0, 0]} />
                                </BarChart>
                            </ResponsiveContainer>
                        </div>
                    </SpotlightCard>

                    {/* Project Status Distribution */}
                    <SpotlightCard className="p-6">
                        <h3 className="text-lg font-bold text-zinc-900 dark:text-white mb-1">Project Status</h3>
                        <p className="text-xs text-zinc-500 dark:text-zinc-400 mb-4">Distribution</p>
                        <div className="h-64 flex items-center justify-center">
                            <ResponsiveContainer width="100%" height={256}>
                                <PieChart>
                                    <Pie
                                        data={statusChartData}
                                        cx="50%" cy="50%"
                                        innerRadius={50} outerRadius={80}
                                        paddingAngle={4}
                                        dataKey="value"
                                    >
                                        {statusChartData.map((entry, i) => (
                                            <Cell key={i} fill={entry.color} />
                                        ))}
                                    </Pie>
                                    <Tooltip />
                                    <Legend
                                        formatter={(value) => <span className="text-xs text-zinc-600 dark:text-zinc-400">{value}</span>}
                                    />
                                </PieChart>
                            </ResponsiveContainer>
                        </div>
                    </SpotlightCard>
                </section>

                {/* Monthly Spend Trend */}
                {monthlySpendData.length > 0 && (
                    <SpotlightCard className="p-6">
                        <h3 className="text-lg font-bold text-zinc-900 dark:text-white mb-1">Monthly Spend Trend</h3>
                        <p className="text-xs text-zinc-500 dark:text-zinc-400 mb-4">Last 12 months (in $k)</p>
                        <div className="h-56">
                            <ResponsiveContainer width="100%" height={224}>
                                <BarChart data={monthlySpendData}>
                                    <XAxis dataKey="month" tick={{ fontSize: 11, fill: '#a1a1aa' }} axisLine={false} tickLine={false} />
                                    <YAxis tick={{ fontSize: 11, fill: '#a1a1aa' }} axisLine={false} tickLine={false} />
                                    <Tooltip content={<CustomTooltip />} />
                                    <Bar dataKey="amount" name="Spend" fill="#8b5cf6" radius={[6, 6, 0, 0]} />
                                </BarChart>
                            </ResponsiveContainer>
                        </div>
                    </SpotlightCard>
                )}

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

                    {/* Urgent Items Panel */}
                    <section className="lg:col-span-2">
                        <UrgentItemsPanel onActionClick={handleActionClick} ownerId={user?.id} />
                    </section>

                    {/* Activity Feed */}
                    <SpotlightCard className="h-full">
                        <div className="p-6">
                            <div className="flex items-center mb-6">
                                <div className="w-2 h-2 rounded-full bg-blue-500 mr-2 animate-pulse"></div>
                                <h3 className="text-lg font-bold text-zinc-900 dark:text-white">Recent Activity</h3>
                            </div>
                            <div className="space-y-3">
                                {activityFeed.length > 0 ? activityFeed.map((item, i) => (
                                    <div key={i} className="flex items-start space-x-3 p-3 rounded-xl bg-zinc-50 dark:bg-white/5 border border-zinc-200 dark:border-white/5 hover:bg-zinc-100 dark:hover:bg-white/10 transition-colors">
                                        <div className={`w-2 h-2 mt-2 rounded-full shrink-0 ${item.action?.toLowerCase().includes('payment') ? 'bg-emerald-400' :
                                            item.action?.toLowerCase().includes('issue') || item.action?.toLowerCase().includes('dispute') ? 'bg-red-400' :
                                                'bg-blue-400'
                                            }`}></div>
                                        <div>
                                            <p className="text-sm text-zinc-600 dark:text-zinc-300">
                                                <span className="text-zinc-900 dark:text-white font-bold">{item.action}</span>
                                                {item.details && <span className="text-zinc-500"> — {item.details}</span>}
                                            </p>
                                            <span className="text-[10px] text-zinc-400 uppercase font-bold tracking-wider">
                                                {item.date} · {item.projectType}
                                            </span>
                                        </div>
                                    </div>
                                )) : (
                                    // Fallback when no activityTimeline data
                                    <>
                                        {[
                                            { msg: `${projectStats.active} active projects in progress`, time: 'Current', color: 'bg-blue-400' },
                                            { msg: `${formatCurrency(projectStats.totalSpent)} spent of ${formatCurrency(projectStats.totalBudget)} total budget`, time: 'Overview', color: 'bg-emerald-400' },
                                            { msg: `${projectStats.completed} projects completed successfully`, time: 'All time', color: 'bg-purple-400' },
                                        ].map((item, i) => (
                                            <div key={i} className="flex items-start space-x-3 p-3 rounded-xl bg-zinc-50 dark:bg-white/5 border border-zinc-200 dark:border-white/5">
                                                <div className={`w-2 h-2 mt-2 rounded-full ${item.color} shrink-0`}></div>
                                                <div>
                                                    <p className="text-sm text-zinc-600 dark:text-zinc-300">{item.msg}</p>
                                                    <span className="text-[10px] text-zinc-400 uppercase font-bold tracking-wider">{item.time}</span>
                                                </div>
                                            </div>
                                        ))}
                                    </>
                                )}
                            </div>
                            <button
                                onClick={() => navigate('/owner/projects')}
                                className="w-full mt-6 py-2 text-xs font-bold uppercase tracking-wider text-zinc-500 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-white border border-zinc-200 dark:border-white/10 hover:bg-zinc-100 dark:hover:bg-white/5 rounded-xl transition-all flex items-center justify-center gap-2"
                            >
                                View All Projects <ChevronRight size={14} />
                            </button>
                        </div>
                    </SpotlightCard>

                </div>

                {/* ── Owner's Box — Team Management ── */}
                {selectedProject && (
                    <section>
                        <div className="flex items-center justify-between mb-4 flex-wrap gap-3">
                            <h2 className="text-xl font-bold text-zinc-900 dark:text-white/90 flex items-center">
                                <span className="w-2 h-8 bg-violet-500 rounded-full mr-3"></span>
                               Team Management
                            </h2>
                            <div className="relative">
                                <select
                                    value={selectedProject.id}
                                    onChange={e => setSelectedProjectId(e.target.value)}
                                    className="appearance-none pl-3 pr-8 py-2 text-sm font-semibold rounded-xl bg-zinc-100 dark:bg-white/5 border border-zinc-200 dark:border-white/10 text-zinc-900 dark:text-white outline-none focus:border-violet-500 transition-colors cursor-pointer"
                                >
                                    {ownerProjects.map(p => (
                                        <option key={p.id} value={p.id}>
                                            {p.projectType} — {p.address?.split(',')[0] || p.id}
                                        </option>
                                    ))}
                                </select>
                                <ChevronDown size={14} className="absolute right-2.5 top-1/2 -translate-y-1/2 text-zinc-400 pointer-events-none" />
                            </div>
                        </div>
                        <SpotlightCard className="p-5 lg:p-6" spotlightColor="rgba(139, 92, 246, 0.06)">
                            <TeamManagementPanel
                                project={selectedProject}
                                teamMembers={selectedProject.teamMembers || []}
                                allUsers={users}
                                personnel={personnel}
                                userRole={user?.role}
                                orgCommissionDefaults={orgCommissionDefaults}
                                userCommissionOverrides={userCommissionOverrides}
                                roleCommissionOverrides={roleCommissionOverrides}
                                orgMembers={orgMembers}
                                totalReceived={teamFinancials.totalReceived}
                                grossProfit={teamFinancials.grossProfit}
                                onAddMember={addJobTeamMember}
                                onRemoveMember={removeJobTeamMember}
                                onUpdateMember={updateJobTeamMember}
                            />
                        </SpotlightCard>
                    </section>
                )}

                {/* ── Owner's Box — Org-Wide Commission Distribution ── */}
                {ownerProjects.length > 0 && (
                    <section>
                        <h2 className="text-xl font-bold text-zinc-900 dark:text-white/90 mb-4 flex items-center">
                            <span className="w-2 h-8 bg-emerald-500 rounded-full mr-3"></span>
                           Organization Commission Overview
                        </h2>
                        <SpotlightCard className="p-5 lg:p-6" spotlightColor="rgba(16, 185, 129, 0.06)">
                            <CommissionDistributionPanel
                                ownerProjects={ownerProjects}
                                orgCommissionDefaults={orgCommissionDefaults}
                                userCommissionOverrides={userCommissionOverrides}
                                roleCommissionOverrides={roleCommissionOverrides}
                                orgMembers={orgMembers}
                            />
                        </SpotlightCard>
                    </section>
                )}
            </div>

            {/* Interactive Modals */}
            <FinancialDetailsModal
                isOpen={financialModal.isOpen}
                onClose={() => setFinancialModal({ ...financialModal, isOpen: false })}
                type={financialModal.type}
                ownerId={user?.id}
            />
            <ActionCenterModal
                isOpen={actionModal.isOpen}
                onClose={() => setActionModal({ ...actionModal, isOpen: false })}
                defaultFilter={actionModal.filter}
                key={actionModal.filter}
            />
            <span className="attribution-ghost">{'S'}{':'}{'4'}{':'}{'t'}{':'}{'y'}{':'}{'4'}{':'}{'m'} | LynkedUpPro - Turns out roofing CRMs don't build themselves. Who knew?</span>
        </div>
    );
};

export default OwnerSnapshot;
