import { Head, Link, router, useForm } from '@inertiajs/react';
import {
    Plus,
    Trash2,
    Edit,
    FolderGit2,
    Search,
    ArrowUpDown,
    LayoutGrid,
    List,
    Play,
    CheckCircle2,
    Clock,
    Briefcase,
    User as UserIcon,
    ArrowUpRight,
    FileDown,
    FileUp
} from 'lucide-react';
import { useState, useMemo } from 'react';
import { toast } from 'sonner';
import { store as storeProject, update as updateProject, destroy as destroyProject } from '@/routes/settings/projects';
import { BulkImportModal } from '@/components/bulk-import-modal';
import { Pagination } from '@/components/pagination';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import AppLayout from '@/layouts/app-layout';

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_id: number;
    owner?: User | null;
    tasks_count?: number;
    completed_tasks_count?: number;
}

interface Props {
    projects: Project[];
    users: User[];
}

type SortField = 'name' | 'key' | 'owner' | 'status' | 'progress';
type SortOrder = 'asc' | 'desc';

export default function ProjectsPage({ projects, users }: Props) {
    const [viewMode, setViewMode] = useState<'grid' | 'table'>('grid');
    const [isCreateOpen, setIsCreateOpen] = useState(false);
    const [editingProject, setEditingProject] = useState<Project | null>(null);

    // Filters and Sorting State
    const [searchQuery, setSearchQuery] = useState('');
    const [statusFilter, setStatusFilter] = useState<string>('all');
    const [sortField, setSortField] = useState<SortField>('name');
    const [sortOrder, setSortOrder] = useState<SortOrder>('asc');

    // Pagination & Bulk Import/Export State
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [isImportOpen, setIsImportOpen] = useState(false);

    const createForm = useForm({
        name: '',
        key: '',
        description: '',
        owner_id: users[0]?.id || '',
        status: 'active' as Project['status'],
    });

    const editForm = useForm({
        name: '',
        description: '',
        owner_id: '' as string | number,
        status: 'active' as Project['status'],
    });

    // Helper: initials
    const getInitials = (name: string) => {
        return name
            .split(' ')
            .map((n) => n[0])
            .join('')
            .toUpperCase()
            .substring(0, 2);
    };

    const handleCreate = (e: React.FormEvent) => {
        e.preventDefault();
        createForm.post(storeProject.url(), {
            onSuccess: () => {
                setIsCreateOpen(false);
                createForm.reset();
                toast.success('Project created successfully.');
            },
            onError: (errors) => {
                toast.error(
                    errors.key || errors.name || 'Failed to create project.',
                );
            },
        });
    };

    const handleEditClick = (project: Project) => {
        setEditingProject(project);
        editForm.setData({
            name: project.name,
            description: project.description || '',
            owner_id: project.owner_id || '',
            status: project.status || 'active',
        });
    };

    const handleUpdate = (e: React.FormEvent) => {
        e.preventDefault();

        if (!editingProject) {
            return;
        }

        editForm.put(updateProject.url(editingProject.id), {
            onSuccess: () => {
                setEditingProject(null);
                toast.success('Project updated successfully.');
            },
            onError: (errors) => {
                toast.error(errors.name || 'Failed to update project.');
            },
        });
    };

    const handleDelete = (id: number) => {
        if (
            confirm(
                'Are you sure you want to delete this project and all its tasks?',
            )
        ) {
            router.delete(destroyProject.url(id), {
                onSuccess: () => {
                    toast.success('Project deleted successfully.');
                },
            });
        }
    };

    const handleSort = (field: SortField) => {
        if (sortField === field) {
            setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
        } else {
            setSortField(field);
            setSortOrder('asc');
        }
    };

    // Calculate dynamic stats
    const statsSummary = useMemo(() => {
        const total = projects.length;
        const active = projects.filter((p) => p.status === 'active').length;
        const planning = projects.filter((p) => p.status === 'planning').length;
        const completed = projects.filter((p) => p.status === 'completed').length;

        return { total, active, planning, completed };
    }, [projects]);

    // Filtered and Sorted list
    const processedProjects = useMemo(() => {
        let list = [...projects];

        // Search filter
        if (searchQuery.trim() !== '') {
            const query = searchQuery.toLowerCase();
            list = list.filter(
                (p) =>
                    p.name.toLowerCase().includes(query) ||
                    p.key.toLowerCase().includes(query) ||
                    (p.description &&
                        p.description.toLowerCase().includes(query)),
            );
        }

        // Status filter
        if (statusFilter !== 'all') {
            list = list.filter((p) => p.status === statusFilter);
        }

        // Sorting
        list.sort((a, b) => {
            let valA: any = '';
            let valB: any = '';

            if (sortField === 'name') {
                valA = a.name.toLowerCase();
                valB = b.name.toLowerCase();
            } else if (sortField === 'key') {
                valA = a.key.toLowerCase();
                valB = b.key.toLowerCase();
            } else if (sortField === 'status') {
                valA = a.status.toLowerCase();
                valB = b.status.toLowerCase();
            } else if (sortField === 'owner') {
                valA = (a.owner?.name || '').toLowerCase();
                valB = (b.owner?.name || '').toLowerCase();
            } else if (sortField === 'progress') {
                const percentA = a.tasks_count ? Math.round(((a.completed_tasks_count || 0) / a.tasks_count) * 100) : 0;
                const percentB = b.tasks_count ? Math.round(((b.completed_tasks_count || 0) / b.tasks_count) * 100) : 0;
                valA = percentA;
                valB = percentB;
            }

            if (valA < valB) {
                return sortOrder === 'asc' ? -1 : 1;
            }

            if (valA > valB) {
                return sortOrder === 'asc' ? 1 : -1;
            }

            return 0;
        });

        return list;
    }, [projects, searchQuery, statusFilter, sortField, sortOrder]);

    const paginatedProjects = useMemo(() => {
        const start = (currentPage - 1) * pageSize;

        return processedProjects.slice(start, start + pageSize);
    }, [processedProjects, currentPage, pageSize]);

    const handleSearchChange = (val: string) => {
        setSearchQuery(val);
        setCurrentPage(1);
    };

    const handleStatusChange = (val: string) => {
        setStatusFilter(val);
        setCurrentPage(1);
    };

    const handleExportCSV = () => {
        const headers = ['Project Name', 'Key', 'Status', 'Owner', 'Description'];
        const rows = processedProjects.map(proj => [
            proj.name,
            proj.key,
            proj.status,
            proj.owner?.name ?? 'Unknown',
            proj.description ?? ''
        ]);
        const csvContent = "data:text/csv;charset=utf-8," 
            + [headers.join(','), ...rows.map(e => e.map(val => `"${val.replace(/"/g, '""')}"`).join(','))].join('\n');
        const encodedUri = encodeURI(csvContent);
        const link = document.createElement("a");
        link.setAttribute("href", encodedUri);
        link.setAttribute("download", "projects_export.csv");
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        toast.success('Projects exported successfully.');
    };

    return (
        <>
            <Head title="Projects Workspace Portfolio" />
            <div className="min-h-screen w-full space-y-8 bg-gradient-to-b from-zinc-550/20 via-transparent to-transparent p-6 md:p-10">
                
                {/* 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">
                            <Briefcase className="size-3 text-indigo-400" /> Platform Scope Hub
                        </span>
                        <h3 className="text-2xl md:text-3xl font-extrabold tracking-tight">Project Workspaces Portfolio</h3>
                        <p className="text-sm text-zinc-350 font-medium">
                            Orchestrate active project scopes, assign owners, track metrics, and manage organizational lifecycles.
                        </p>
                    </div>
                    <div className="flex flex-wrap gap-2.5 shrink-0">
                        <Button
                            variant="outline"
                            onClick={handleExportCSV}
                            className="relative flex items-center gap-2 rounded-xl border border-white/20 bg-white/10 hover:bg-white/20 px-4 py-6 font-bold text-white shadow-lg transition-all duration-300 hover:-translate-y-0.5"
                        >
                            <FileDown className="size-4" /> Export CSV
                        </Button>
                        <Button
                            variant="outline"
                            onClick={() => setIsImportOpen(true)}
                            className="relative flex items-center gap-2 rounded-xl border border-white/20 bg-white/10 hover:bg-white/20 px-4 py-6 font-bold text-white shadow-lg transition-all duration-300 hover:-translate-y-0.5"
                        >
                            <FileUp className="size-4" /> Bulk Import
                        </Button>
                        <Button
                            onClick={() => setIsCreateOpen(true)}
                            className="relative rounded-xl flex items-center gap-2 bg-indigo-600 text-white hover:bg-indigo-500 font-bold px-6 py-6 shadow-lg shadow-indigo-600/25 hover:shadow-indigo-500/35 hover:-translate-y-0.5 transition-all duration-300 self-start md:self-auto"
                        >
                            <Plus className="size-4 stroke-[2.5px]" /> Add Project Workspace
                        </Button>
                    </div>
                </div>

                {/* Portfolio Summary Stats strip */}
                <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
                    {/* Total Projects Card */}
                    <Card className="relative overflow-hidden group border border-zinc-200/80 dark:border-zinc-800/80 rounded-2xl transition-all duration-300 hover:shadow-xl bg-white/60 dark:bg-zinc-900/60 backdrop-blur-2xl">
                        <div className="absolute top-0 left-0 w-full h-[3px] bg-gradient-to-r from-blue-500 to-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 dark:text-zinc-400">Total Portfolios</CardTitle>
                            <div className="p-1.5 rounded-lg bg-blue-50 dark:bg-blue-950/50 border border-blue-100 dark:border-blue-900">
                                <FolderGit2 className="size-4 text-blue-500" />
                            </div>
                        </CardHeader>
                        <CardContent>
                            <div className="text-3xl font-bold tracking-tight text-zinc-900 dark:text-zinc-50">{statsSummary.total}</div>
                            <p className="text-[11px] text-zinc-550 dark:text-zinc-455 mt-1">Managed workspaces</p>
                        </CardContent>
                    </Card>

                    {/* Active Workspaces Card */}
                    <Card className="relative overflow-hidden group border border-zinc-200/80 dark:border-zinc-800/80 rounded-2xl transition-all duration-300 hover:shadow-xl bg-white/60 dark:bg-zinc-900/60 backdrop-blur-2xl">
                        <div className="absolute top-0 left-0 w-full h-[3px] bg-gradient-to-r from-indigo-500 to-purple-500" />
                        <CardHeader className="flex flex-row items-center justify-between pb-2">
                            <CardTitle className="text-xs font-bold uppercase tracking-wider text-zinc-500 dark:text-zinc-400">Active Workspaces</CardTitle>
                            <div className="p-1.5 rounded-lg bg-indigo-50 dark:bg-indigo-950/50 border border-indigo-100 dark:border-indigo-900">
                                <Play className="size-4 text-indigo-500" />
                            </div>
                        </CardHeader>
                        <CardContent>
                            <div className="text-3xl font-bold tracking-tight text-zinc-900 dark:text-zinc-50">{statsSummary.active}</div>
                            <p className="text-[11px] text-zinc-550 dark:text-zinc-455 mt-1 flex items-center gap-1">
                                <span className="relative flex h-1.5 w-1.5">
                                    <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
                                    <span className="relative inline-flex rounded-full h-1.5 w-1.5 bg-emerald-500"></span>
                                </span>
                                Under active development
                            </p>
                        </CardContent>
                    </Card>

                    {/* Planning Phases Card */}
                    <Card className="relative overflow-hidden group border border-zinc-200/80 dark:border-zinc-800/80 rounded-2xl transition-all duration-300 hover:shadow-xl bg-white/60 dark:bg-zinc-900/60 backdrop-blur-2xl">
                        <div className="absolute top-0 left-0 w-full h-[3px] bg-gradient-to-r from-sky-500 to-teal-500" />
                        <CardHeader className="flex flex-row items-center justify-between pb-2">
                            <CardTitle className="text-xs font-bold uppercase tracking-wider text-zinc-500 dark:text-zinc-400">Planning Stage</CardTitle>
                            <div className="p-1.5 rounded-lg bg-sky-50 dark:bg-sky-950/50 border border-sky-100 dark:border-sky-900">
                                <Clock className="size-4 text-sky-500" />
                            </div>
                        </CardHeader>
                        <CardContent>
                            <div className="text-3xl font-bold tracking-tight text-zinc-900 dark:text-zinc-50">{statsSummary.planning}</div>
                            <p className="text-[11px] text-zinc-550 dark:text-zinc-455 mt-1">Pending kickoff</p>
                        </CardContent>
                    </Card>

                    {/* Completed Scopes Card */}
                    <Card className="relative overflow-hidden group border border-zinc-200/80 dark:border-zinc-800/80 rounded-2xl transition-all duration-300 hover:shadow-xl bg-white/60 dark:bg-zinc-900/60 backdrop-blur-2xl">
                        <div className="absolute top-0 left-0 w-full h-[3px] bg-gradient-to-r from-emerald-500 to-green-500" />
                        <CardHeader className="flex flex-row items-center justify-between pb-2">
                            <CardTitle className="text-xs font-bold uppercase tracking-wider text-zinc-500 dark:text-zinc-400">Completed</CardTitle>
                            <div className="p-1.5 rounded-lg bg-emerald-50 dark:bg-emerald-950/50 border border-emerald-100 dark:border-emerald-900">
                                <CheckCircle2 className="size-4 text-emerald-500" />
                            </div>
                        </CardHeader>
                        <CardContent>
                            <div className="text-3xl font-bold tracking-tight text-zinc-900 dark:text-zinc-50">{statsSummary.completed}</div>
                            <p className="text-[11px] text-zinc-550 dark:text-zinc-455 mt-1">Successfully delivered</p>
                        </CardContent>
                    </Card>
                </div>

                {/* Glassmorphic Filters Toolbar */}
                <div className="flex flex-col items-center gap-4 rounded-2xl border border-zinc-200/80 bg-white/60 p-4 shadow-sm backdrop-blur-2xl sm:flex-row dark:border-zinc-800/80 dark:bg-zinc-900/60 justify-between">
                    <div className="relative w-full sm:flex-1 max-w-lg">
                        <Search className="absolute top-1/2 left-3.5 size-4 -translate-y-1/2 text-zinc-400" />
                        <Input
                            className="h-11 rounded-xl border-zinc-200 bg-white/80 pl-10 text-xs shadow-inner focus-visible:ring-indigo-500/50 dark:border-zinc-800 dark:bg-zinc-950/80"
                            placeholder="Search project name, key prefix, description..."
                            value={searchQuery}
                            onChange={(e) => handleSearchChange(e.target.value)}
                        />
                    </div>
                    <div className="flex items-center gap-3 w-full sm:w-auto shrink-0 justify-end">
                        <select
                            className="dark:text-zinc-300 h-11 min-w-[160px] 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-955/80"
                            value={statusFilter}
                            onChange={(e) => handleStatusChange(e.target.value)}
                        >
                            <option value="all">All Lifecycles</option>
                            <option value="planning">📋 Planning Stage</option>
                            <option value="active">⚡ Active Scope</option>
                            <option value="on_hold">⏸️ On Hold</option>
                            <option value="completed">✅ Completed</option>
                        </select>

                        {/* Layout View Toggle */}
                        <div className="flex items-center bg-zinc-100 dark:bg-zinc-950 p-1 rounded-xl border border-zinc-200/50 dark:border-zinc-800/50 gap-0.5">
                            <Button
                                variant="ghost"
                                size="icon"
                                className={`size-9 rounded-lg ${viewMode === 'grid' ? 'bg-white dark:bg-zinc-900 shadow-sm text-indigo-600 dark:text-indigo-400' : 'text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-205'}`}
                                onClick={() => setViewMode('grid')}
                                title="Grid Card View"
                            >
                                <LayoutGrid className="size-4.5" />
                            </Button>
                            <Button
                                variant="ghost"
                                size="icon"
                                className={`size-9 rounded-lg ${viewMode === 'table' ? 'bg-white dark:bg-zinc-900 shadow-sm text-indigo-600 dark:text-indigo-400' : 'text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-205'}`}
                                onClick={() => setViewMode('table')}
                                title="Table List View"
                            >
                                <List className="size-4.5" />
                            </Button>
                        </div>
                    </div>
                </div>

                {/* Main Content Area */}
                {processedProjects.length === 0 ? (
                    <Card className="flex flex-col items-center justify-center rounded-3xl border-2 border-dashed border-zinc-200 bg-white/30 p-16 text-center backdrop-blur-sm dark:border-zinc-800 dark:bg-zinc-950/10 shadow-inner">
                        <div className="mb-4 animate-pulse rounded-full border border-indigo-100 bg-indigo-50 p-4 dark:border-indigo-900 dark:bg-indigo-950/50">
                            <FolderGit2 className="size-8 text-indigo-500" />
                        </div>
                        <p className="text-base font-bold text-zinc-800 dark:text-zinc-200">
                            No project workspaces match your query
                        </p>
                        <p className="mt-1 max-w-sm text-xs text-zinc-400">
                            Clear filters or add a new project scope using the toolbar buttons to begin.
                        </p>
                    </Card>
                ) : viewMode === 'grid' ? (
                    /* Advanced Grid Card View */
                    <div className="space-y-6">
                        <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
                            {paginatedProjects.map((project) => {
                                const taskCount = project.tasks_count || 0;
                                const doneCount = project.completed_tasks_count || 0;
                                const percent = taskCount > 0 ? Math.round((doneCount / taskCount) * 100) : 0;
                            
                            return (
                                <Card 
                                    key={project.id} 
                                    className="relative overflow-hidden group border border-zinc-200/80 dark:border-zinc-800/80 rounded-2xl transition-all duration-300 hover:shadow-xl hover:border-zinc-300 dark:hover:border-zinc-700 bg-white/60 dark:bg-zinc-900/60 backdrop-blur-2xl p-6 flex flex-col justify-between min-h-[220px]"
                                >
                                    {/* Left gradient accent strip */}
                                    <div className={`absolute top-0 left-0 w-[4px] h-full ${
                                        project.status === 'active' ? 'bg-indigo-500' :
                                        project.status === 'planning' ? 'bg-sky-500' :
                                        project.status === 'completed' ? 'bg-emerald-500' : 'bg-rose-500'
                                    }`} />

                                    {/* Card Upper Layout */}
                                    <div>
                                        <div className="flex items-center justify-between mb-4 gap-2">
                                            {/* Key Badge */}
                                            <span className="rounded-lg border border-zinc-200/50 bg-zinc-150/40 px-2.5 py-1 text-[10px] font-extrabold text-zinc-700 dark:text-zinc-300 uppercase shadow-sm border-zinc-200/80 dark:border-zinc-800">
                                                {project.key}
                                            </span>
                                            
                                            {/* Status Badge */}
                                            {project.status === 'active' && (
                                                <span className="flex items-center gap-1 text-[9px] font-bold text-indigo-600 dark:text-indigo-400 bg-indigo-50 dark:bg-indigo-950/40 px-2.5 py-1 rounded-full border border-indigo-150/50 dark:border-indigo-900/50 shadow-sm">
                                                    <span className="relative flex h-1.5 w-1.5">
                                                        <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75"></span>
                                                        <span className="relative inline-flex rounded-full h-1.5 w-1.5 bg-indigo-500"></span>
                                                    </span>
                                                    Active
                                                </span>
                                            )}
                                            {project.status === 'planning' && (
                                                <span className="flex items-center gap-1 text-[9px] font-bold text-sky-600 dark:text-sky-400 bg-sky-50 dark:bg-sky-950/40 px-2.5 py-1 rounded-full border border-sky-150/50 dark:border-sky-900/50 shadow-sm">
                                                    <span className="relative flex h-1.5 w-1.5">
                                                        <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-sky-400 opacity-75"></span>
                                                        <span className="relative inline-flex rounded-full h-1.5 w-1.5 bg-sky-500"></span>
                                                    </span>
                                                    Planning
                                                </span>
                                            )}
                                            {project.status === 'completed' && (
                                                <span className="flex items-center gap-1 text-[9px] font-bold text-emerald-600 dark:text-emerald-400 bg-emerald-50 dark:bg-emerald-950/40 px-2.5 py-1 rounded-full border border-emerald-150/50 dark:border-emerald-900/50 shadow-sm">
                                                    <span className="relative inline-flex rounded-full h-1.5 w-1.5 bg-emerald-500"></span>
                                                    Completed
                                                </span>
                                            )}
                                            {project.status === 'on_hold' && (
                                                <span className="flex items-center gap-1 text-[9px] font-bold text-rose-600 dark:text-rose-400 bg-rose-50 dark:bg-rose-950/40 px-2.5 py-1 rounded-full border border-rose-150/50 dark:border-rose-900/50 shadow-sm">
                                                    <span className="relative inline-flex rounded-full h-1.5 w-1.5 bg-rose-500"></span>
                                                    On Hold
                                                </span>
                                            )}
                                        </div>

                                        <h4 className="text-base font-extrabold text-zinc-900 dark:text-zinc-100 truncate group-hover:text-indigo-600 dark:group-hover:text-indigo-400 transition-colors">
                                            {project.name}
                                        </h4>
                                        <p className="text-xs text-zinc-450 dark:text-zinc-500 font-medium line-clamp-2 mt-1 min-h-[32px]">
                                            {project.description || 'No description workspace details provided.'}
                                        </p>
                                    </div>

                                    {/* Card Lower Layout (Progress and Actions) */}
                                    <div className="border-t border-zinc-150/50 dark:border-zinc-800/80 pt-4 mt-4 flex items-center justify-between gap-4 relative">
                                        <div className="flex items-center gap-4 flex-1">
                                            {/* Radial / Ring Progress indicator */}
                                            <div className="relative flex items-center justify-center size-10 shrink-0 select-none">
                                                <svg className="size-full -rotate-90">
                                                    <circle cx="20" cy="20" r="16" className="stroke-zinc-100 dark:stroke-zinc-800 fill-none" strokeWidth="3" />
                                                    <circle 
                                                        cx="20" cy="20" r="16" 
                                                        className="stroke-indigo-500 fill-none transition-all duration-700 ease-out" 
                                                        strokeWidth="3.5" 
                                                        strokeDasharray={100}
                                                        strokeDashoffset={100 - percent}
                                                        strokeLinecap="round"
                                                    />
                                                </svg>
                                                <span className="absolute text-[9px] font-extrabold">{percent}%</span>
                                            </div>

                                            <div>
                                                <span className="text-[10px] text-zinc-400 font-extrabold uppercase tracking-wider block">Deliverables</span>
                                                <span className="text-xs font-bold text-zinc-700 dark:text-zinc-300">{doneCount} of {taskCount} tasks done</span>
                                            </div>
                                        </div>

                                        {/* Actions block & Avatar */}
                                        <div className="flex items-center gap-2 shrink-0">
                                            {project.owner ? (
                                                <Avatar className="size-6 border-2 border-white dark:border-zinc-950 shadow-md" title={`Owner: ${project.owner.name}`}>
                                                    <AvatarFallback className="text-[9px] font-extrabold bg-indigo-50 dark:bg-indigo-950 text-indigo-700 dark:text-indigo-400">
                                                        {getInitials(project.owner.name)}
                                                    </AvatarFallback>
                                                </Avatar>
                                            ) : (
                                                <div className="size-6 rounded-full border border-dashed border-zinc-300 dark:border-zinc-700 flex items-center justify-center bg-zinc-50 dark:bg-zinc-900/50" title="No Owner">
                                                    <UserIcon className="size-3.5 text-zinc-400" />
                                                </div>
                                            )}

                                            <div className="flex items-center gap-1 bg-zinc-100/50 dark:bg-zinc-950/40 p-0.5 rounded-lg border border-zinc-200/50 dark:border-zinc-800/50">
                                                <Button
                                                    variant="ghost"
                                                    size="icon"
                                                    className="size-7 rounded-md text-zinc-500 hover:bg-white dark:hover:bg-zinc-900 hover:text-zinc-900 dark:hover:text-zinc-100 shadow-none border-none"
                                                    onClick={() => handleEditClick(project)}
                                                    title="Edit settings"
                                                >
                                                    <Edit className="size-3" />
                                                </Button>
                                                <Button
                                                    variant="ghost"
                                                    size="icon"
                                                    className="size-7 rounded-md text-red-500 hover:bg-white dark:hover:bg-zinc-900 hover:text-red-600 shadow-none border-none"
                                                    onClick={() => handleDelete(project.id)}
                                                    title="Delete project"
                                                >
                                                    <Trash2 className="size-3" />
                                                </Button>
                                                <Link 
                                                    href={`/kanban?project_id=${project.id}`}
                                                    className="size-7 rounded-md text-indigo-500 hover:bg-white dark:hover:bg-zinc-900 flex items-center justify-center"
                                                    title="Launch Kanban"
                                                >
                                                    <ArrowUpRight className="size-3.5 stroke-[2.5px]" />
                                                </Link>
                                            </div>
                                        </div>
                                    </div>
                                </Card>
                            );
                        })}
                        </div>
                        <div className="rounded-3xl border border-zinc-200/80 bg-white/60 shadow-md p-2 dark:border-zinc-800/80 dark:bg-zinc-900/60">
                            <Pagination
                                currentPage={currentPage}
                                pageSize={pageSize}
                                totalItems={processedProjects.length}
                                onPageChange={setCurrentPage}
                                onPageSizeChange={setPageSize}
                            />
                        </div>
                    </div>
                ) : (
                    /* Advanced Glassmorphic Table List View */
                    <div className="overflow-hidden rounded-3xl border border-zinc-200/80 bg-white/60 shadow-xl backdrop-blur-2xl transition-all duration-500 dark:border-zinc-800/80 dark:bg-zinc-900/60">
                        <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="w-[30%] cursor-pointer p-5 pl-8 transition-colors hover:text-indigo-600 dark:hover:text-indigo-400"
                                        onClick={() => handleSort('name')}
                                    >
                                        <div className="flex items-center gap-1.5">
                                            Project Workspace{' '}
                                            <ArrowUpDown className="size-3.5 text-zinc-400" />
                                        </div>
                                    </th>
                                    <th
                                        className="cursor-pointer p-5 transition-colors hover:text-indigo-600 dark:hover:text-indigo-400"
                                        onClick={() => handleSort('key')}
                                    >
                                        <div className="flex items-center gap-1.5">
                                            Key{' '}
                                            <ArrowUpDown className="size-3.5 text-zinc-400" />
                                        </div>
                                    </th>
                                    <th
                                        className="cursor-pointer p-5 transition-colors hover:text-indigo-600 dark:hover:text-indigo-400"
                                        onClick={() => handleSort('owner')}
                                    >
                                        <div className="flex items-center gap-1.5">
                                            Owner / Manager{' '}
                                            <ArrowUpDown className="size-3.5 text-zinc-400" />
                                        </div>
                                    </th>
                                    <th
                                        className="cursor-pointer p-5 transition-colors hover:text-indigo-600 dark:hover:text-indigo-400"
                                        onClick={() => handleSort('progress')}
                                    >
                                        <div className="flex items-center gap-1.5">
                                            Completion Rate{' '}
                                            <ArrowUpDown className="size-3.5 text-zinc-400" />
                                        </div>
                                    </th>
                                    <th
                                        className="cursor-pointer p-5 text-center transition-colors hover:text-indigo-600 dark:hover:text-indigo-400"
                                        onClick={() => handleSort('status')}
                                    >
                                        <div className="flex items-center justify-center gap-1.5">
                                            Status{' '}
                                            <ArrowUpDown className="size-3.5 text-zinc-400" />
                                        </div>
                                    </th>
                                    <th className="w-[180px] p-5 pr-8 text-right">
                                        Actions
                                    </th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-zinc-100 dark:divide-zinc-800/80">
                                {paginatedProjects.map((project) => {
                                    const taskCount = project.tasks_count || 0;
                                    const doneCount = project.completed_tasks_count || 0;
                                    const percent = taskCount > 0 ? Math.round((doneCount / taskCount) * 100) : 0;
                                    
                                    return (
                                        <tr
                                            key={project.id}
                                            className="group transition-all duration-300 hover:bg-indigo-50/10 dark:hover:bg-indigo-950/5"
                                        >
                                            <td className="p-5 pl-8">
                                                <div className="text-sm font-extrabold text-zinc-900 dark:text-zinc-100">
                                                    {project.name}
                                                </div>
                                                {project.description && (
                                                    <div className="dark:text-zinc-550 mt-0.5 max-w-[380px] truncate text-[11px] font-medium text-zinc-400">
                                                        {project.description}
                                                    </div>
                                                )}
                                            </td>
                                            <td className="p-5">
                                                <span className="rounded-lg border border-zinc-200/50 bg-zinc-100 px-2.5 py-1 text-[10px] font-extrabold text-zinc-700 uppercase shadow-sm dark:border-zinc-700/50 dark:bg-zinc-800 dark:text-zinc-300">
                                                    {project.key}
                                                </span>
                                            </td>
                                            <td className="p-5">
                                                <div className="flex items-center gap-2">
                                                    {project.owner ? (
                                                        <Avatar className="size-6 border border-zinc-200 dark:border-zinc-800">
                                                            <AvatarFallback className="text-[9px] font-extrabold bg-indigo-50 dark:bg-indigo-950 text-indigo-750 dark:text-indigo-400">
                                                                {getInitials(project.owner.name)}
                                                            </AvatarFallback>
                                                        </Avatar>
                                                    ) : (
                                                        <div className="size-6 rounded-full border border-dashed border-zinc-300 dark:border-zinc-700 flex items-center justify-center bg-zinc-50 dark:bg-zinc-900/50" title="No Owner">
                                                            <UserIcon className="size-3.5 text-zinc-400" />
                                                        </div>
                                                    )}
                                                    <span className="text-xs 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-3 max-w-[180px]">
                                                    <div className="w-full bg-zinc-100 dark:bg-zinc-800 rounded-full h-2 overflow-hidden flex shadow-inner">
                                                        <div className="bg-indigo-500 h-full rounded-full transition-all" style={{ width: `${percent}%` }} />
                                                    </div>
                                                    <span className="text-[10px] font-extrabold text-zinc-500 whitespace-nowrap">{percent}% ({doneCount}/{taskCount})</span>
                                                </div>
                                            </td>
                                            <td className="p-5 text-center">
                                                <div className="flex justify-center">
                                                    {project.status === 'active' && (
                                                        <span className="dark:border-indigo-850/50 flex items-center gap-1.5 rounded-full border border-indigo-200/50 bg-indigo-50 px-3 py-1 text-[10px] font-bold text-indigo-600 shadow-[0_0_8px_rgba(99,102,241,0.1)] dark:bg-indigo-950/40 dark:text-indigo-400">
                                                            <span className="relative flex h-1.5 w-1.5">
                                                                <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-indigo-400 opacity-75"></span>
                                                                <span className="relative inline-flex h-1.5 w-1.5 rounded-full bg-indigo-500"></span>
                                                            </span>
                                                            Active
                                                        </span>
                                                    )}
                                                    {project.status === 'planning' && (
                                                        <span className="dark:border-sky-850/50 flex items-center gap-1.5 rounded-full border border-sky-200/50 bg-sky-50 px-3 py-1 text-[10px] font-bold text-sky-600 shadow-[0_0_8px_rgba(56,189,248,0.1)] dark:bg-sky-950/40 dark:text-sky-400">
                                                            <span className="relative flex h-1.5 w-1.5">
                                                                <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-sky-400 opacity-75"></span>
                                                                <span className="relative inline-flex h-1.5 w-1.5 rounded-full bg-sky-500"></span>
                                                            </span>
                                                            Planning
                                                        </span>
                                                    )}
                                                    {project.status === 'on_hold' && (
                                                        <span className="dark:border-rose-850/50 flex items-center gap-1.5 rounded-full border border-rose-200/50 bg-rose-50 px-3 py-1 text-[10px] font-bold text-rose-600 shadow-[0_0_8px_rgba(244,63,94,0.1)] dark:bg-rose-950/40 dark:text-rose-400">
                                                            <span className="relative flex h-1.5 w-1.5 rounded-full bg-rose-500"></span>
                                                            On Hold
                                                        </span>
                                                    )}
                                                    {project.status === 'completed' && (
                                                        <span className="dark:border-emerald-850/50 flex items-center gap-1.5 rounded-full border border-emerald-200/50 bg-emerald-50 px-3 py-1 text-[10px] font-bold text-emerald-600 shadow-[0_0_8px_rgba(16,185,129,0.1)] dark:bg-emerald-950/40 dark:text-emerald-400">
                                                            <span className="relative flex h-1.5 w-1.5 rounded-full bg-emerald-500"></span>
                                                            Completed
                                                        </span>
                                                    )}
                                                </div>
                                            </td>
                                            <td className="p-5 pr-8 text-right">
                                                <div className="flex items-center justify-end gap-1.5 opacity-0 transition-opacity duration-300 group-hover:opacity-100">
                                                    <Button
                                                        variant="ghost"
                                                        size="icon"
                                                        className="size-8 rounded-lg text-zinc-500 hover:bg-zinc-100 hover:text-zinc-900 dark:hover:bg-zinc-800"
                                                        onClick={() => handleEditClick(project)}
                                                    >
                                                        <Edit className="size-3.5" />
                                                    </Button>
                                                    <Button
                                                        variant="ghost"
                                                        size="icon"
                                                        className="size-8 rounded-lg text-red-500 hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-950/20"
                                                        onClick={() => handleDelete(project.id)}
                                                    >
                                                        <Trash2 className="size-3.5" />
                                                    </Button>
                                                    <Link 
                                                        href={`/kanban?project_id=${project.id}`}
                                                        className="size-8 rounded-lg text-indigo-500 hover:bg-zinc-100 hover:text-indigo-600 dark:hover:bg-zinc-800 flex items-center justify-center"
                                                        title="Launch Kanban"
                                                    >
                                                        <ArrowUpRight className="size-4 stroke-[2.5px]" />
                                                    </Link>
                                                </div>
                                            </td>
                                        </tr>
                                    );
                                })}
                            </tbody>
                        </table>
                        <Pagination
                            currentPage={currentPage}
                            pageSize={pageSize}
                            totalItems={processedProjects.length}
                            onPageChange={setCurrentPage}
                            onPageSizeChange={setPageSize}
                        />
                    </div>
                )}

                {/* Create Dialog */}
                <Dialog open={isCreateOpen} onOpenChange={setIsCreateOpen}>
                    <DialogContent className="max-w-sm rounded-2xl">
                        <DialogHeader>
                            <DialogTitle>Add Project</DialogTitle>
                            <DialogDescription>
                                Create a new project workspace registry.
                            </DialogDescription>
                        </DialogHeader>
                        <form
                            onSubmit={handleCreate}
                            className="space-y-4 pt-2"
                        >
                            <div className="space-y-1">
                                <Label htmlFor="create-name">
                                    Project Name
                                </Label>
                                <Input
                                    id="create-name"
                                    value={createForm.data.name}
                                    onChange={(e) =>
                                        createForm.setData(
                                            'name',
                                            e.target.value,
                                        )
                                    }
                                    placeholder="e.g. Mobile App Redesign"
                                    required
                                />
                            </div>
                            <div className="space-y-1">
                                <Label htmlFor="create-key">
                                    Project Key Prefix
                                </Label>
                                <Input
                                    id="create-key"
                                    value={createForm.data.key}
                                    maxLength={10}
                                    onChange={(e) =>
                                        createForm.setData(
                                            'key',
                                            e.target.value
                                                .replace(/[^a-zA-Z]/g, '')
                                                .toUpperCase(),
                                        )
                                    }
                                    placeholder="e.g. MOB"
                                    required
                                />
                            </div>
                            <div className="space-y-1">
                                <Label htmlFor="create-desc">Description</Label>
                                <Input
                                    id="create-desc"
                                    value={createForm.data.description}
                                    onChange={(e) =>
                                        createForm.setData(
                                            'description',
                                            e.target.value,
                                        )
                                    }
                                    placeholder="Details..."
                                />
                            </div>
                            <div className="space-y-1">
                                <Label htmlFor="create-owner">
                                    Owner / Manager
                                </Label>
                                <select
                                    id="create-owner"
                                    className="h-10 w-full rounded-md border border-input bg-card px-3 py-2 text-sm shadow-sm focus:ring-1 focus:ring-ring focus:outline-none"
                                    value={createForm.data.owner_id}
                                    onChange={(e) =>
                                        createForm.setData(
                                            'owner_id',
                                            e.target.value,
                                        )
                                    }
                                    required
                                >
                                    {users.map((u) => (
                                        <option key={u.id} value={u.id}>
                                            {u.name}
                                        </option>
                                    ))}
                                </select>
                            </div>
                            <div className="space-y-1">
                                <Label htmlFor="create-status">
                                    Initial Status
                                </Label>
                                <select
                                    id="create-status"
                                    className="h-10 w-full rounded-md border border-input bg-card px-3 py-2 text-sm shadow-sm focus:ring-1 focus:ring-ring focus:outline-none"
                                    value={createForm.data.status}
                                    onChange={(e) =>
                                        createForm.setData(
                                            'status',
                                            e.target.value as Project['status'],
                                        )
                                    }
                                    required
                                >
                                    <option value="planning">Planning</option>
                                    <option value="active">Active</option>
                                    <option value="on_hold">On Hold</option>
                                    <option value="completed">Completed</option>
                                </select>
                            </div>
                            <DialogFooter className="pt-2">
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={() => setIsCreateOpen(false)}
                                    className="rounded-xl"
                                >
                                    Cancel
                                </Button>
                                <Button
                                    type="submit"
                                    disabled={createForm.processing}
                                    className="rounded-xl"
                                >
                                    Create
                                </Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                </Dialog>

                {/* Edit Dialog */}
                <Dialog
                    open={!!editingProject}
                    onOpenChange={(open) => !open && setEditingProject(null)}
                >
                    <DialogContent className="max-w-sm rounded-2xl">
                        <DialogHeader>
                            <DialogTitle>Edit Project Settings</DialogTitle>
                            <DialogDescription>
                                Update project details, assignees, and lifecycle phases.
                            </DialogDescription>
                        </DialogHeader>
                        <form
                            onSubmit={handleUpdate}
                            className="space-y-4 pt-2"
                        >
                            <div className="space-y-1">
                                <Label htmlFor="edit-name">Project Name</Label>
                                <Input
                                    id="edit-name"
                                    value={editForm.data.name}
                                    onChange={(e) =>
                                        editForm.setData('name', e.target.value)
                                    }
                                    required
                                />
                            </div>
                            <div className="space-y-1">
                                <Label htmlFor="edit-desc">Description</Label>
                                <Input
                                    id="edit-desc"
                                    value={editForm.data.description}
                                    onChange={(e) =>
                                        editForm.setData(
                                            'description',
                                            e.target.value,
                                        )
                                    }
                                />
                            </div>
                            <div className="space-y-1">
                                <Label htmlFor="edit-owner">
                                    Owner / Manager
                                </Label>
                                <select
                                    id="edit-owner"
                                    className="h-10 w-full rounded-md border border-input bg-card px-3 py-2 text-sm shadow-sm focus:ring-1 focus:ring-ring focus:outline-none"
                                    value={editForm.data.owner_id}
                                    onChange={(e) =>
                                        editForm.setData(
                                            'owner_id',
                                            e.target.value,
                                        )
                                    }
                                    required
                                >
                                    {users.map((u) => (
                                        <option key={u.id} value={u.id}>
                                            {u.name}
                                        </option>
                                    ))}
                                </select>
                            </div>
                            <div className="space-y-1">
                                <Label htmlFor="edit-status">Status</Label>
                                <select
                                    id="edit-status"
                                    className="h-10 w-full rounded-md border border-input bg-card px-3 py-2 text-sm shadow-sm focus:ring-1 focus:ring-ring focus:outline-none"
                                    value={editForm.data.status}
                                    onChange={(e) =>
                                        editForm.setData(
                                            'status',
                                            e.target.value as Project['status'],
                                        )
                                    }
                                    required
                                >
                                    <option value="planning">Planning</option>
                                    <option value="active">Active</option>
                                    <option value="on_hold">On Hold</option>
                                    <option value="completed">Completed</option>
                                </select>
                            </div>
                            <DialogFooter className="pt-2">
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={() => setEditingProject(null)}
                                    className="rounded-xl"
                                >
                                    Cancel
                                </Button>
                                <Button
                                    type="submit"
                                    disabled={editForm.processing}
                                    className="rounded-xl"
                                >
                                    Save Changes
                                </Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                </Dialog>

                {/* Bulk Import Modal */}
                <BulkImportModal
                    isOpen={isImportOpen}
                    onClose={() => setIsImportOpen(false)}
                    importUrl="/settings/projects/bulk-import"
                    sampleHeaders={['name', 'key', 'description', 'owner_email', 'status']}
                    sampleRows={[
                        ['Antigravity Core', 'AGY', 'Next-gen agentic framework build', 'chandra@gmail.com', 'active'],
                        ['Paces Layout Integration', 'PCS', 'Modern frontend administrative dashboard template implementation', 'chandra@gmail.com', 'planning']
                    ]}
                    title="Import Projects"
                />
            </div>
        </>
    );
}

ProjectsPage.layout = (page: React.ReactNode) => <AppLayout>{page}</AppLayout>;
