import { Head } from '@inertiajs/react';
import { 
    FolderGit2, 
    CheckSquare, 
    Layers, 
    Clock, 
    CheckCircle2, 
    Milestone,
    Award,
    Network,
    GitBranch,
    Calendar,
    BarChart3
} from 'lucide-react';
import { useState, useEffect, useMemo } from 'react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';

interface User {
    id: number;
    name: string;
    email: string;
}

interface Project {
    id: number;
    name: string;
    key: string;
    description: string | null;
    status: 'planning' | 'active' | 'on_hold' | 'completed';
    owner?: User | null;
    tasks: {
        id: number;
        title: string;
        status: 'todo' | 'in_progress' | 'in_review' | 'done';
        assignee?: User | null;
    }[];
    project_micro_timelines: {
        id: number;
        timeline_id: number;
        status: string;
        timeline?: {
            id: number;
            stage: string;
            is_major: boolean;
            is_micro: boolean;
            parent_id: number | null;
        } | null;
    }[];
    licence_mappings: {
        id: number;
        licence_id: number;
        status: string;
        licence?: {
            id: number;
            name: string;
            required_for: string;
        } | null;
    }[];
    dev_schedules: {
        id: number;
        serial_no: string;
        activity: string;
        status: string;
        duration_days: number | null;
        responsibility: string | null;
    }[];
}

interface ActivityLog {
    id: number;
    user_name: string;
    user_email: string;
    description: string;
    time_diff: string;
    status_code: number;
}

interface DashboardProps {
    stats: {
        totalProjects: number;
        totalTasks: number;
        taskStatusCounts: {
            todo: number;
            in_progress: number;
            in_review: number;
            done: number;
        };
        totalUsers: number;
    };
    recentTasks: {
        id: number;
        key: string;
        title: string;
        status: 'todo' | 'in_progress' | 'in_review' | 'done';
        priority: 'lowest' | 'low' | 'medium' | 'high' | 'highest';
        type: 'story' | 'task' | 'bug' | 'epic';
        project?: { name: string } | null;
        assignee?: User | null;
    }[];
    recentProjects: {
        id: number;
        name: string;
        key: string;
        owner?: User | null;
    }[];
    activityLogs: ActivityLog[];
    allProjects: Project[];
}

export default function Dashboard({ stats: initialStats, allProjects }: DashboardProps) {
    const [stats, setStats] = useState(initialStats);
    
    // Tab State: 'comprehensive' vs 'project-wise'
    const [activeTab, setActiveTab] = useState<'comprehensive' | 'project-wise'>('comprehensive');
    
    // Project selection state for project-wise dashboard
    const [selectedProjectId, setSelectedProjectId] = useState<number>(allProjects[0]?.id || 0);

    // Selected project reference
    const selectedProject = useMemo(() => {
        return allProjects.find(p => p.id === selectedProjectId) || allProjects[0];
    }, [allProjects, selectedProjectId]);

    // Live Simulator Sync
    useEffect(() => {
        const phrases = [
            { action: 'completed task', details: 'Setup OAuth Authentication Flow', type: 'success' },
            { action: 'updated milestone', details: 'Phase 2 Database Migrations deployed', type: 'info' },
            { action: 'created issue', details: 'Refactor settings navigation layout constraints', type: 'warning' },
            { action: 'triggered audit', details: 'Pushed container verification metrics to production', type: 'info' }
        ];

        const users = [
            { name: 'Sarah Jenkins', email: 'sarah@company.com' },
            { name: 'Alex Rivera', email: 'alex@company.com' },
            { name: 'Jordan Patel', email: 'jordan@company.com' }
        ];

        const interval = setInterval(() => {
            const randPhrase = phrases[Math.floor(Math.random() * phrases.length)];
            const randUser = users[Math.floor(Math.random() * users.length)];
            const newId = Date.now();

            toast.info(`Activity Logged: ${randUser.name} ${randPhrase.action} - ${randPhrase.details}`);

            const newNotification = {
                id: `sim-${newId}`,
                title: randPhrase.action.charAt(0).toUpperCase() + randPhrase.action.slice(1),
                description: `${randPhrase.details} (${randUser.name})`,
                time: 'Just now',
                read: false,
                type: randPhrase.type as 'success' | 'warning' | 'info',
            };
            window.dispatchEvent(new CustomEvent('platform-notification', { detail: newNotification }));

            setStats(prev => {
                const isDone = randPhrase.action.includes('complete');
                const isTodo = randPhrase.action.includes('create');

                return {
                    ...prev,
                    totalTasks: prev.totalTasks + (isTodo ? 1 : 0),
                    taskStatusCounts: {
                        ...prev.taskStatusCounts,
                        todo: prev.taskStatusCounts.todo + (isTodo ? 1 : 0),
                        done: prev.taskStatusCounts.done + (isDone ? 1 : 0),
                        in_progress: prev.taskStatusCounts.in_progress + (!isTodo && !isDone ? 1 : 0)
                    }
                };
            });

        }, 40000);

        return () => clearInterval(interval);
    }, []);

    // Calculate details for each project (for Comprehensive mode)
    const projectsSummary = useMemo(() => {
        return allProjects.map(project => {
            const totalTasks = project.tasks.length;
            const doneTasks = project.tasks.filter(t => t.status === 'done').length;
            const completionRate = totalTasks > 0 ? Math.round((doneTasks / totalTasks) * 100) : 0;

            // Compliance Mapping dependencies
            const totalLicences = project.licence_mappings.length;
            const approvedLicences = project.licence_mappings.filter(l => l.status === 'approved' || l.status === 'active' || l.status === 'completed').length;

            // Timeline stage metrics
            const majorTimelines = project.project_micro_timelines.filter(t => t.timeline?.is_major);
            const totalStages = majorTimelines.length;
            const completedStages = majorTimelines.filter(t => t.status === 'completed' || t.status === 'done').length;

            // Task Dependencies: Unresolved non-completed tasks (todo + in_progress + in_review)
            const unresolvedTasks = project.tasks.filter(t => t.status !== 'done').length;

            // Overall Risk Score calculation based on unresolved items & pending licences
            let risk = 'Low';
            let riskColor = 'text-emerald-500 bg-emerald-50 dark:bg-emerald-950/20';
            const pendingLicenceCount = totalLicences - approvedLicences;

            if (unresolvedTasks > 8 || pendingLicenceCount > 3) {
                risk = 'High';
                riskColor = 'text-rose-500 bg-rose-50 dark:bg-rose-950/20';
            } else if (unresolvedTasks > 3 || pendingLicenceCount > 1) {
                risk = 'Medium';
                riskColor = 'text-amber-500 bg-amber-50 dark:bg-amber-950/20';
            }

            return {
                ...project,
                totalTasks,
                doneTasks,
                completionRate,
                totalLicences,
                approvedLicences,
                totalStages,
                completedStages,
                unresolvedTasks,
                risk,
                riskColor
            };
        });
    }, [allProjects]);

    // Calculate module-wise statistics for Project-Wise dashboard
    const projectModules = useMemo(() => {
        if (!selectedProject) {
return [];
}
        
        // Find major timeline entries as "Modules"
        const majorEntries = selectedProject.project_micro_timelines.filter(mt => mt.timeline?.is_major);
        
        return majorEntries.map(major => {
            // Find all micro child entries under this major stage
            const children = selectedProject.project_micro_timelines.filter(mt => 
                mt.timeline?.is_micro && mt.timeline?.parent_id === major.timeline_id
            );
            
            const totalSub = children.length;
            const completedSub = children.filter(c => c.status === 'completed' || c.status === 'done').length;
            const percent = totalSub > 0 ? Math.round((completedSub / totalSub) * 100) : 0;
            
            // Dependencies: pending micro timeline activities that are blocking completion
            const pendingDepsCount = totalSub - completedSub;
            
            return {
                id: major.id,
                stage: major.timeline?.stage || 'Unknown Module',
                status: major.status,
                totalSub,
                completedSub,
                percent,
                pendingDepsCount,
                subActivities: children
            };
        });
    }, [selectedProject]);

    // Calculate Dev Schedule Phases (Dev, Screening, Exhibit, Stability) for selected project
    const devSchedulePhases = useMemo(() => {
        if (!selectedProject) {
return [];
}
        
        const schedules = selectedProject.dev_schedules;
        
        // Map activities to respective phases
        const phases = [
            { name: 'Development Phase', startNo: 5, endNo: 18, color: 'from-indigo-500 to-indigo-600', text: 'text-indigo-500' },
            { name: 'Screening Phase', startNo: 19, endNo: 37, color: 'from-purple-500 to-purple-600', text: 'text-purple-500' },
            { name: 'Exhibit Batch Phase', startNo: 38, endNo: 49, color: 'from-pink-500 to-pink-600', text: 'text-pink-500' },
            { name: 'Stability Stage', startNo: 50, endNo: 54, color: 'from-emerald-500 to-emerald-600', text: 'text-emerald-500' }
        ];
        
        return phases.map(phase => {
            const items = schedules.filter(s => {
                const sNo = parseInt(s.serial_no);

                return sNo >= phase.startNo && sNo <= phase.endNo;
            });
            const total = items.length;
            const completed = items.filter(i => i.status === 'completed' || i.status === 'done').length;
            const progress = total > 0 ? Math.round((completed / total) * 100) : 0;
            
            return {
                ...phase,
                total,
                completed,
                progress
            };
        });
    }, [selectedProject]);

    return (
        <>
            <Head title="Enterprise Control Center" />
            <div className="space-y-8 p-6 md:p-10 w-full bg-gradient-to-b from-zinc-550/20 via-transparent to-transparent min-h-screen">
                
                {/* Modern Dashboard Header Banner */}
                <div className="relative overflow-hidden rounded-3xl bg-gradient-to-r from-indigo-950 via-zinc-900 to-indigo-900 p-8 md:p-10 text-white shadow-2xl border border-white/10 flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
                    <div className="absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(99,102,241,0.15),transparent_50%)]" />
                    <div className="relative space-y-2 max-w-2xl">
                        <span className="px-3 py-1 rounded-full bg-white/10 text-indigo-200 text-[10px] font-extrabold uppercase tracking-widest border border-white/10 backdrop-blur-md flex items-center gap-1.5 w-fit">
                            <Network className="size-3.5 text-indigo-400 animate-pulse" /> Enterprise Portfolio Monitor
                        </span>
                        <h3 className="text-2xl md:text-3xl font-extrabold tracking-tight">Enterprise Control Center</h3>
                        <p className="text-sm text-zinc-350 font-medium">
                            Dual-layer analytics summarizing global workspace status, milestone dependencies, compliance mappings, and schedule workflows.
                        </p>
                    </div>

                    {/* View Switcher Tabs */}
                    <div className="flex bg-zinc-900/50 p-1.5 rounded-2xl border border-white/10 gap-1 backdrop-blur-xl z-10">
                        <Button
                            variant="ghost"
                            className={`rounded-xl px-4 py-2 text-xs font-bold transition-all duration-300 ${
                                activeTab === 'comprehensive' 
                                    ? 'bg-white text-zinc-950 shadow-lg' 
                                    : 'text-zinc-400 hover:text-white'
                            }`}
                            onClick={() => setActiveTab('comprehensive')}
                        >
                            <BarChart3 className="size-3.5 mr-1.5" /> Combined Overview
                        </Button>
                        <Button
                            variant="ghost"
                            className={`rounded-xl px-4 py-2 text-xs font-bold transition-all duration-300 ${
                                activeTab === 'project-wise' 
                                    ? 'bg-white text-zinc-950 shadow-lg' 
                                    : 'text-zinc-400 hover:text-white'
                            }`}
                            onClick={() => setActiveTab('project-wise')}
                        >
                            <GitBranch className="size-3.5 mr-1.5" /> Project-Wise Analytics
                        </Button>
                    </div>
                </div>

                {/* --------------------- TAB 1: COMPREHENSIVE OVERVIEW --------------------- */}
                {activeTab === 'comprehensive' && (
                    <div className="space-y-8 animate-in fade-in duration-300">
                        {/* Stats strip */}
                        <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
                            <Card className="relative overflow-hidden border border-zinc-200/80 dark:border-zinc-800/80 rounded-2xl bg-white/60 dark:bg-zinc-900/60 backdrop-blur-2xl">
                                <div className="absolute top-0 left-0 w-full h-[3px] bg-indigo-500" />
                                <CardHeader className="flex flex-row items-center justify-between pb-2">
                                    <CardTitle className="text-xs font-bold uppercase tracking-wider text-zinc-500">Workspace Count</CardTitle>
                                    <FolderGit2 className="size-4 text-indigo-500" />
                                </CardHeader>
                                <CardContent>
                                    <div className="text-3xl font-bold tracking-tight">{stats.totalProjects}</div>
                                    <p className="text-[11px] text-zinc-450 mt-1">Cross-functional portfolios</p>
                                </CardContent>
                            </Card>

                            <Card className="relative overflow-hidden border border-zinc-200/80 dark:border-zinc-800/80 rounded-2xl bg-white/60 dark:bg-zinc-900/60 backdrop-blur-2xl">
                                <div className="absolute top-0 left-0 w-full h-[3px] bg-blue-500" />
                                <CardHeader className="flex flex-row items-center justify-between pb-2">
                                    <CardTitle className="text-xs font-bold uppercase tracking-wider text-zinc-500">Deliverables</CardTitle>
                                    <CheckSquare className="size-4 text-blue-500" />
                                </CardHeader>
                                <CardContent>
                                    <div className="text-3xl font-bold tracking-tight">{stats.totalTasks}</div>
                                    <p className="text-[11px] text-zinc-455 mt-1 flex items-center gap-1">
                                        <span className="text-emerald-500 font-extrabold">{stats.taskStatusCounts.done} done</span>
                                        / {stats.taskStatusCounts.in_progress + stats.taskStatusCounts.in_review} in progress
                                    </p>
                                </CardContent>
                            </Card>

                            <Card className="relative overflow-hidden border border-zinc-200/80 dark:border-zinc-800/80 rounded-2xl bg-white/60 dark:bg-zinc-900/60 backdrop-blur-2xl">
                                <div className="absolute top-0 left-0 w-full h-[3px] bg-pink-500" />
                                <CardHeader className="flex flex-row items-center justify-between pb-2">
                                    <CardTitle className="text-xs font-bold uppercase tracking-wider text-zinc-500">Compliance licences</CardTitle>
                                    <Award className="size-4 text-pink-500" />
                                </CardHeader>
                                <CardContent>
                                    <div className="text-3xl font-bold tracking-tight">
                                        {allProjects.reduce((acc, p) => acc + p.licence_mappings.length, 0)}
                                    </div>
                                    <p className="text-[11px] text-zinc-455 mt-1">Form 29, 11 and mfg maps</p>
                                </CardContent>
                            </Card>

                            <Card className="relative overflow-hidden border border-zinc-200/80 dark:border-zinc-800/80 rounded-2xl bg-white/60 dark:bg-zinc-900/60 backdrop-blur-2xl">
                                <div className="absolute top-0 left-0 w-full h-[3px] bg-emerald-500" />
                                <CardHeader className="flex flex-row items-center justify-between pb-2">
                                    <CardTitle className="text-xs font-bold uppercase tracking-wider text-zinc-500">Timeline Milestones</CardTitle>
                                    <Milestone className="size-4 text-emerald-500" />
                                </CardHeader>
                                <CardContent>
                                    <div className="text-3xl font-bold tracking-tight">
                                        {allProjects.reduce((acc, p) => acc + p.project_micro_timelines.filter(t => t.timeline?.is_major).length, 0)}
                                    </div>
                                    <p className="text-[11px] text-zinc-455 mt-1">Stage 0 to Stage XII items</p>
                                </CardContent>
                            </Card>
                        </div>

                        {/* Combined Projects Portfolio Matrix */}
                        <Card className="border border-zinc-200/80 dark:border-zinc-800/80 rounded-3xl bg-white/60 dark:bg-zinc-900/60 backdrop-blur-2xl shadow-xl overflow-hidden">
                            <CardHeader className="border-b border-zinc-150/50 dark:border-zinc-800/80 bg-zinc-50/50 dark:bg-zinc-900/30 p-6">
                                <CardTitle className="text-lg font-extrabold">Combined Projects Matrix</CardTitle>
                                <CardDescription className="text-xs">Consolidated portfolio view depicting task completions, compliance logs, timeline phases, and risk analysis.</CardDescription>
                            </CardHeader>
                            <div className="overflow-x-auto">
                                <table className="w-full border-collapse text-left text-xs">
                                    <thead>
                                        <tr className="border-b border-zinc-200 bg-zinc-50/80 text-[10px] font-bold tracking-wider text-zinc-500 uppercase select-none dark:border-zinc-800 dark:bg-zinc-900/50">
                                            <th className="p-5 pl-8">Project Portfolio</th>
                                            <th className="p-5">Owner / Manager</th>
                                            <th className="p-5">Tasks Completion</th>
                                            <th className="p-5">Timeline Modules</th>
                                            <th className="p-5">Licence Mappings</th>
                                            <th className="p-5">Dependencies</th>
                                            <th className="p-5 text-center">Risk Level</th>
                                            <th className="p-5 text-center">Status</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-zinc-100 dark:divide-zinc-800/80">
                                        {projectsSummary.map((project) => (
                                            <tr key={project.id} className="group hover:bg-indigo-50/10 dark:hover:bg-indigo-950/5 transition-all">
                                                <td className="p-5 pl-8">
                                                    <div className="text-sm font-extrabold text-zinc-900 dark:text-zinc-50">{project.name}</div>
                                                    <div className="text-[10px] font-extrabold text-zinc-450 dark:text-zinc-500 mt-0.5 uppercase tracking-wider">Key: {project.key}</div>
                                                </td>
                                                <td className="p-5">
                                                    <div className="flex items-center gap-2">
                                                        <div className="flex size-6 items-center justify-center rounded-full bg-gradient-to-br from-indigo-500 to-purple-500 text-[10px] font-bold text-white uppercase">
                                                            {project.owner?.name.charAt(0) ?? 'S'}
                                                        </div>
                                                        <span className="font-semibold text-zinc-700 dark:text-zinc-300">{project.owner?.name ?? 'System'}</span>
                                                    </div>
                                                </td>
                                                <td className="p-5">
                                                    <div className="flex items-center gap-2 max-w-[150px]">
                                                        <div className="w-full bg-zinc-100 dark:bg-zinc-800 rounded-full h-1.5 overflow-hidden flex">
                                                            <div className="bg-indigo-500 h-full rounded-full" style={{ width: `${project.completionRate}%` }} />
                                                        </div>
                                                        <span className="text-[10px] font-extrabold text-zinc-500 whitespace-nowrap">{project.completionRate}% ({project.doneTasks}/{project.totalTasks})</span>
                                                    </div>
                                                </td>
                                                <td className="p-5">
                                                    <div className="flex items-center gap-1.5">
                                                        <span className="px-2 py-0.5 rounded-md bg-zinc-100 dark:bg-zinc-800 text-[10px] font-bold text-zinc-600 dark:text-zinc-450 border border-zinc-200/50 dark:border-zinc-700/50 shadow-sm">
                                                            {project.completedStages} / {project.totalStages} Stages done
                                                        </span>
                                                    </div>
                                                </td>
                                                <td className="p-5">
                                                    <div className="flex items-center gap-1.5">
                                                        <span className={`px-2 py-0.5 rounded-md text-[10px] font-bold border shadow-sm ${
                                                            project.approvedLicences === project.totalLicences 
                                                                ? 'bg-emerald-50 text-emerald-600 border-emerald-150/50 dark:bg-emerald-950/20 dark:text-emerald-450 dark:border-emerald-900/50' 
                                                                : 'bg-amber-50 text-amber-600 border-amber-150/50 dark:bg-amber-950/20 dark:text-amber-450 dark:border-amber-900/50'
                                                        }`}>
                                                            {project.approvedLicences} / {project.totalLicences} Approved
                                                        </span>
                                                    </div>
                                                </td>
                                                <td className="p-5">
                                                    <div className="flex items-center gap-1">
                                                        <span className="text-[11px] font-bold text-zinc-700 dark:text-zinc-300">
                                                            {project.unresolvedTasks} tasks pending
                                                        </span>
                                                    </div>
                                                </td>
                                                <td className="p-5 text-center">
                                                    <span className={`px-2.5 py-0.5 rounded-full text-[9px] font-extrabold uppercase border shadow-inner ${project.riskColor}`}>
                                                        {project.risk}
                                                    </span>
                                                </td>
                                                <td className="p-5 text-center">
                                                    <span className={`px-2.5 py-0.5 rounded-full text-[9px] font-extrabold uppercase ${
                                                        project.status === 'active' ? 'bg-indigo-50 text-indigo-600 dark:bg-indigo-950/40 dark:text-indigo-400' :
                                                        project.status === 'planning' ? 'bg-sky-50 text-sky-600 dark:bg-sky-950/40 dark:text-sky-400' :
                                                        project.status === 'completed' ? 'bg-emerald-50 text-emerald-600 dark:bg-emerald-950/40 dark:text-emerald-400' :
                                                        'bg-rose-50 text-rose-600 dark:bg-rose-950/40 dark:text-rose-450'
                                                    }`}>
                                                        {project.status}
                                                    </span>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </Card>
                    </div>
                )}

                {/* --------------------- TAB 2: PROJECT-WISE & MODULE-WISE ANALYTICS --------------------- */}
                {activeTab === 'project-wise' && (
                    <div className="space-y-8 animate-in fade-in duration-300">
                        {/* Selector toolbar */}
                        <div className="flex flex-col md:flex-row items-center justify-between gap-4 p-5 rounded-2xl border border-zinc-200/80 bg-white/60 dark:border-zinc-800/80 dark:bg-zinc-900/60 backdrop-blur-2xl shadow-sm">
                            <div className="flex items-center gap-3">
                                <div className="p-2 rounded-xl bg-indigo-50 dark:bg-indigo-950/50 border border-indigo-150/50 dark:border-indigo-900/50">
                                    <GitBranch className="size-5 text-indigo-500" />
                                </div>
                                <div>
                                    <h4 className="font-extrabold text-sm text-zinc-900 dark:text-zinc-100">Project Focus Selection</h4>
                                    <p className="text-[11px] text-zinc-400">Select project workspace to inspect module scopes and Gantt schedules.</p>
                                </div>
                            </div>
                            <select
                                className="dark:text-zinc-300 h-11 min-w-[240px] cursor-pointer rounded-xl border border-zinc-200 bg-white/80 px-3.5 py-2 text-xs font-semibold text-zinc-700 shadow-sm focus:ring-2 focus:ring-indigo-500/30 focus:outline-none dark:border-zinc-800 dark:bg-zinc-950/80"
                                value={selectedProjectId}
                                onChange={(e) => setSelectedProjectId(parseInt(e.target.value))}
                            >
                                {allProjects.map(p => (
                                    <option key={p.id} value={p.id}>{p.name} ({p.key})</option>
                                ))}
                            </select>
                        </div>

                        {selectedProject ? (
                            <div className="grid gap-8 lg:grid-cols-3">
                                {/* Left Side: Modules & Dependencies tracker */}
                                <div className="lg:col-span-2 space-y-8">
                                    {/* Module List (Timeline Stages) */}
                                    <Card className="border border-zinc-200/80 dark:border-zinc-800/80 rounded-3xl bg-white/60 dark:bg-zinc-900/60 backdrop-blur-2xl shadow-md p-6">
                                        <CardHeader className="p-0 pb-4">
                                            <CardTitle className="text-base font-extrabold flex items-center gap-2">
                                                <Layers className="size-4 text-indigo-500" /> Module-Wise Stage Breakdown
                                            </CardTitle>
                                            <CardDescription className="text-xs">Timeline milestones seeded as module scopes. Tracks the completion of micro activities within each stage.</CardDescription>
                                        </CardHeader>
                                        <div className="space-y-4 max-h-[500px] overflow-y-auto pr-1 divide-y divide-zinc-150/50 dark:divide-zinc-800/80 scrollbar-thin">
                                            {projectModules.length === 0 ? (
                                                <div className="p-12 text-center text-zinc-400 text-xs flex flex-col items-center gap-2">
                                                    <Milestone className="size-8 stroke-1 text-zinc-300" />
                                                    No timeline stages seeded.
                                                </div>
                                            ) : (
                                                projectModules.map((mod) => (
                                                    <div key={mod.id} className={`pt-4 first:pt-0 group`}>
                                                        <div className="flex justify-between items-start gap-3 mb-2">
                                                            <div>
                                                                <h5 className="text-xs font-extrabold text-zinc-900 dark:text-zinc-100 group-hover:text-indigo-600 dark:group-hover:text-indigo-400 transition-colors">{mod.stage}</h5>
                                                                <span className="text-[10px] text-zinc-400 font-bold block mt-0.5">
                                                                    {mod.completedSub} of {mod.totalSub} activities done
                                                                </span>
                                                            </div>
                                                            <div className="flex items-center gap-2 shrink-0">
                                                                {mod.pendingDepsCount > 0 ? (
                                                                    <span className="px-2 py-0.5 rounded bg-amber-50 dark:bg-amber-950/20 text-[9px] font-extrabold text-amber-600 dark:text-amber-450 border border-amber-150/50 dark:border-amber-900/50 shadow-sm flex items-center gap-1">
                                                                        <Clock className="size-2.5" /> {mod.pendingDepsCount} deps pending
                                                                    </span>
                                                                ) : (
                                                                    <span className="px-2 py-0.5 rounded bg-emerald-50 dark:bg-emerald-950/20 text-[9px] font-extrabold text-emerald-600 dark:text-emerald-450 border border-emerald-150/50 dark:border-emerald-900/50 shadow-sm flex items-center gap-1">
                                                                        <CheckCircle2 className="size-2.5" /> Ready
                                                                    </span>
                                                                )}
                                                            </div>
                                                        </div>

                                                        {/* Stage progress bar */}
                                                        <div className="flex items-center gap-3">
                                                            <div className="w-full bg-zinc-100 dark:bg-zinc-800 rounded-full h-2 overflow-hidden flex">
                                                                <div className="bg-indigo-500 h-full rounded-full transition-all" style={{ width: `${mod.percent}%` }} />
                                                            </div>
                                                            <span className="text-[10px] font-extrabold text-zinc-500 whitespace-nowrap">{mod.percent}%</span>
                                                        </div>
                                                    </div>
                                                ))
                                            )}
                                        </div>
                                    </Card>

                                    {/* Development Schedule Gantt Flow Graphic */}
                                    <Card className="border border-zinc-200/80 dark:border-zinc-800/80 rounded-3xl bg-white/60 dark:bg-zinc-900/60 backdrop-blur-2xl shadow-md p-6">
                                        <CardHeader className="p-0 pb-4">
                                            <CardTitle className="text-base font-extrabold flex items-center gap-2">
                                                <Calendar className="size-4 text-purple-500" /> Development Schedule Phase Gantt Flow
                                            </CardTitle>
                                            <CardDescription className="text-xs">Sequential representation of development schedule phases (S.No 5 to 54) showing progress.</CardDescription>
                                        </CardHeader>
                                        
                                        {/* Graphical SVG Gantt timeline connector */}
                                        <div className="relative w-full h-[180px] bg-zinc-50/30 dark:bg-zinc-950/30 border border-zinc-150/50 dark:border-zinc-800/85 rounded-2xl p-4 overflow-hidden flex items-center justify-between">
                                            <div className="absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(99,102,241,0.05),transparent_50%)]" />
                                            
                                            {/* Connection flow line */}
                                            <div className="absolute top-1/2 left-10 right-10 h-0.5 bg-gradient-to-r from-indigo-500 via-purple-500 via-pink-500 to-emerald-500 -translate-y-1/2 select-none opacity-50" />
                                            
                                            {devSchedulePhases.map((phase) => (
                                                <div key={phase.name} className="relative z-10 flex flex-col items-center text-center w-28 group">
                                                    {/* Node dot with progress circle */}
                                                    <div className="relative flex items-center justify-center size-14 mb-3 rounded-full bg-white dark:bg-zinc-900 border border-zinc-200/60 dark:border-zinc-800 shadow-md group-hover:scale-105 transition-all">
                                                        <svg className="size-full -rotate-90">
                                                            <circle cx="28" cy="28" r="22" className="stroke-zinc-100 dark:stroke-zinc-800 fill-none" strokeWidth="2.5" />
                                                            <circle 
                                                                cx="28" cy="28" r="22" 
                                                                className="stroke-indigo-500 fill-none transition-all duration-700" 
                                                                strokeWidth="3"
                                                                strokeDasharray={138.2}
                                                                strokeDashoffset={138.2 - (138.2 * phase.progress) / 100}
                                                            />
                                                        </svg>
                                                        <span className="absolute text-[10px] font-extrabold">{phase.progress}%</span>
                                                    </div>

                                                    <h6 className="text-[10px] font-extrabold text-zinc-900 dark:text-zinc-100 tracking-wide uppercase">{phase.name}</h6>
                                                    <span className="text-[9px] text-zinc-400 font-bold block mt-0.5">{phase.completed}/{phase.total} items done</span>
                                                </div>
                                            ))}
                                        </div>
                                    </Card>
                                </div>

                                {/* Right Side: Licence compliance dependencies */}
                                <div className="space-y-8">
                                    {/* Compliance dependencies mapping card */}
                                    <Card className="border border-zinc-200/80 dark:border-zinc-800/80 rounded-3xl bg-white/60 dark:bg-zinc-900/60 backdrop-blur-2xl shadow-md p-6">
                                        <CardHeader className="p-0 pb-4">
                                            <CardTitle className="text-base font-extrabold flex items-center gap-2">
                                                <Award className="size-4 text-pink-500" /> Compliance Mapped Licences
                                            </CardTitle>
                                            <CardDescription className="text-xs">Required regulatory/form license dependencies automatically linked on project creation.</CardDescription>
                                        </CardHeader>
                                        <div className="space-y-3">
                                            {selectedProject.licence_mappings.length === 0 ? (
                                                <div className="p-8 text-center text-zinc-400 text-xs flex flex-col items-center gap-2">
                                                    <Award className="size-7 stroke-1 text-zinc-300" />
                                                    No licences mapped.
                                                </div>
                                            ) : (
                                                selectedProject.licence_mappings.map(map => (
                                                    <div 
                                                        key={map.id} 
                                                        className="flex items-center justify-between p-3 rounded-xl border border-zinc-150/50 dark:border-zinc-800/50 bg-zinc-50/20 dark:bg-zinc-950/20 group hover:border-indigo-500/20 transition-all"
                                                    >
                                                        <div className="min-w-0">
                                                            <h6 className="text-xs font-extrabold text-zinc-900 dark:text-zinc-100">{map.licence?.name || 'Unknown Form'}</h6>
                                                            <span className="text-[10px] text-zinc-400 font-bold">Category: {map.licence?.required_for || 'General'}</span>
                                                        </div>
                                                        <span className={`px-2.5 py-0.5 rounded-full text-[9px] font-extrabold uppercase border ${
                                                            map.status === 'approved' || map.status === 'completed' || map.status === 'active'
                                                                ? 'bg-emerald-50 text-emerald-600 border-emerald-150/50 dark:bg-emerald-950/20 dark:text-emerald-450 dark:border-emerald-900/50'
                                                                : 'bg-amber-50 text-amber-600 border-amber-150/50 dark:bg-amber-950/20 dark:text-amber-450 dark:border-amber-900/50'
                                                        }`}>
                                                            {map.status}
                                                        </span>
                                                    </div>
                                                ))
                                            )}
                                        </div>
                                    </Card>

                                    {/* Task completion rates block */}
                                    <Card className="border border-zinc-200/80 dark:border-zinc-800/80 rounded-3xl bg-white/60 dark:bg-zinc-900/60 backdrop-blur-2xl shadow-md p-6">
                                        <CardHeader className="p-0 pb-4">
                                            <CardTitle className="text-base font-extrabold flex items-center gap-2">
                                                <CheckSquare className="size-4 text-blue-500" /> Deliverables Queue
                                            </CardTitle>
                                            <CardDescription className="text-xs">Active tasks currently assigned to this project workspace.</CardDescription>
                                        </CardHeader>
                                        <div className="space-y-3.5 max-h-[280px] overflow-y-auto pr-1 divide-y divide-zinc-150/50 dark:divide-zinc-800/80 scrollbar-thin">
                                            {selectedProject.tasks.length === 0 ? (
                                                <div className="p-8 text-center text-zinc-400 text-xs flex flex-col items-center gap-2">
                                                    <CheckSquare className="size-7 stroke-1 text-zinc-300" />
                                                    No tasks created.
                                                </div>
                                            ) : (
                                                selectedProject.tasks.map((task) => (
                                                    <div key={task.id} className="pt-3 first:pt-0 flex items-start justify-between gap-3">
                                                        <div className="min-w-0">
                                                            <h6 className="text-xs font-extrabold text-zinc-900 dark:text-zinc-100 truncate">{task.title}</h6>
                                                            <span className="text-[10px] text-zinc-400 font-bold block mt-0.5">Assignee: {task.assignee?.name ?? 'Unassigned'}</span>
                                                        </div>
                                                        <span className={`px-2 py-0.5 rounded text-[9px] font-extrabold uppercase shrink-0 ${
                                                            task.status === 'done' ? 'bg-emerald-50 text-emerald-600 border border-emerald-100 dark:bg-emerald-950/20' :
                                                            task.status === 'in_progress' ? 'bg-indigo-50 text-indigo-600 border border-indigo-100 dark:bg-indigo-950/20' :
                                                            'bg-zinc-100 text-zinc-600 border border-zinc-200 dark:bg-zinc-800'
                                                        }`}>
                                                            {task.status.replace('_', ' ')}
                                                        </span>
                                                    </div>
                                                ))
                                            )}
                                        </div>
                                    </Card>
                                </div>
                            </div>
                        ) : (
                            <div className="p-16 text-center border-2 border-dashed border-zinc-200 rounded-3xl text-zinc-400 text-sm">
                                Create a project workspace to inspect project-wise analytics.
                            </div>
                        )}
                    </div>
                )}
            </div>
        </>
    );
}

Dashboard.layout = {
    breadcrumbs: [
        {
            title: 'Dashboard',
            href: '/dashboard',
        },
    ],
};
