import React, { useState } from 'react';
import { Sidebar } from './Sidebar';
import { TopNav } from './TopNav';
import { cn } from '@/lib/utils';
import { motion, AnimatePresence } from 'framer-motion';
import { X, CheckSquare, Briefcase, Users, TrendingUp, Ticket, FileText, UserPlus, Wrench, FilePlus, ShieldAlert } from 'lucide-react';
import { toast } from 'sonner';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '@/context/AuthContext';
import { useApp } from '@/context/AppContext';

interface LayoutProps {
  children: React.ReactNode;
}

export function Layout({ children }: LayoutProps) {
  const [isCollapsed, setIsCollapsed] = useState(false);
  const [isQuickCreateOpen, setIsQuickCreateOpen] = useState(false);
  const { profile, rolePermissions, isAdmin, hasPermission } = useAuth();
  const { companySettings } = useApp();
  const navigate = useNavigate();

  const handleQuickAction = (action: string) => {
    const routes: Record<string, string> = {
      'Employee': '/employees',
      'Candidate': '/recruitment',
      'Engineer': '/engineers',
      'Project': '/projects',
      'Task': '/tasks',
      'Lead': '/crm',
      'Invoice': '/finance',
      'Expense': '/expenses'
    };

    const route = routes[action];
    if (route) {
      navigate(`${route}?create=true`);
      setIsQuickCreateOpen(false);
    } else {
      toast.success(`Opening ${action} form...`);
      setIsQuickCreateOpen(false);
    }
  };

  const hasAnyAccess = isAdmin || (profile && (rolePermissions[profile.role] || []).length > 0);
  const isLogged = !!profile;

  return (
    <div className="min-h-screen bg-background text-foreground">
      {isLogged && <Sidebar isCollapsed={isCollapsed} setIsCollapsed={setIsCollapsed} />}
      <div
        className={cn(
          "transition-all duration-300 ease-in-out",
          isLogged ? (isCollapsed ? "pl-16" : "pl-64") : "pl-0"
        )}
      >
        <TopNav onOpenQuickCreate={() => setIsQuickCreateOpen(true)} />
        <main className="p-6">
          {hasAnyAccess ? (
            children
          ) : (
            <div className="flex h-[70vh] flex-col items-center justify-center text-center px-4">
              <div className="mb-6 rounded-full bg-primary/10 p-6 text-primary">
                <ShieldAlert size={48} />
              </div>
              <h1 className="text-3xl font-bold tracking-tight mb-2">
                Welcome to {companySettings.name}
              </h1>
              <div className="max-w-md space-y-4">
                <div className="text-lg text-muted-foreground">
                  <p>You currently do not have permission to access this system.</p>
                  <p>Please contact the Management Team for access.</p>
                </div>
                <div className="pt-4">
                  <p className="text-[10px] text-muted-foreground/60 uppercase tracking-widest font-bold">
                    Please contact <span className="text-primary/80">{companySettings.email || 'support@maittech.com'}</span>
                  </p>
                </div>
              </div>
            </div>
          )}
        </main>
      </div>

      {/* Quick Create Modal - Moved to root level to avoid stacking context issues */}
      <AnimatePresence>
        {isQuickCreateOpen && (
          <>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setIsQuickCreateOpen(false)}
              className="fixed inset-0 z-[100] bg-background/80 backdrop-blur-sm"
            />
            <motion.div
              initial={{ opacity: 0, scale: 0.95, y: 20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: 20 }}
              className="fixed left-1/2 top-1/2 z-[101] w-[95vw] max-w-2xl -translate-x-1/2 -translate-y-1/2 rounded-2xl border border-border bg-card p-8 shadow-2xl overflow-hidden"
            >
              <div className="flex items-center justify-between mb-8">
                <div className="space-y-1">
                  <h2 className="text-2xl font-bold tracking-tight">Quick Create</h2>
                  <p className="text-sm text-muted-foreground">Select an action to quickly add a new record to the system.</p>
                </div>
                <button 
                  onClick={() => setIsQuickCreateOpen(false)}
                  className="rounded-full p-2 hover:bg-accent transition-colors text-muted-foreground hover:text-foreground"
                >
                  <X size={24} />
                </button>
              </div>
              
              <div className="grid grid-cols-2 gap-3">
                <div className="space-y-3">
                  <p className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground px-1">Operations</p>
                  <QuickActionButton icon={Users} label="Employee" description="Add new staff member" onClick={() => handleQuickAction('Employee')} />
                  <QuickActionButton icon={UserPlus} label="Candidate" description="Add to recruitment" onClick={() => handleQuickAction('Candidate')} />
                  <QuickActionButton icon={Wrench} label="Engineer" description="Register specialist" onClick={() => handleQuickAction('Engineer')} />
                </div>
                <div className="space-y-3">
                  <p className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground px-1">Execution</p>
                  <QuickActionButton icon={Briefcase} label="Project" description="Launch new initiative" onClick={() => handleQuickAction('Project')} />
                  <QuickActionButton icon={CheckSquare} label="Task" description="Assign new work item" onClick={() => handleQuickAction('Task')} />
                  <QuickActionButton icon={TrendingUp} label="Lead" description="New sales opportunity" onClick={() => handleQuickAction('Lead')} />
                </div>
                <div className="space-y-3 col-span-2 mt-2">
                  <p className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground px-1">Financials</p>
                  <div className="grid grid-cols-2 gap-3">
                    <QuickActionButton icon={FilePlus} label="Invoice" description="Generate billing" onClick={() => handleQuickAction('Invoice')} />
                    <QuickActionButton icon={Ticket} label="Expense" description="Log new cost" onClick={() => handleQuickAction('Expense')} />
                  </div>
                </div>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </div>
  );
}

function QuickActionButton({ icon: Icon, label, description, onClick }: { icon: any, label: string, description: string, onClick: () => void }) {
  return (
    <button 
      onClick={onClick}
      className="flex items-center gap-4 w-full rounded-xl border border-border bg-background p-3 text-left transition-all hover:border-primary hover:bg-primary/5 hover:shadow-md group"
    >
      <div className="rounded-lg bg-accent p-2.5 group-hover:bg-primary/10 group-hover:text-primary transition-colors shrink-0">
        <Icon size={20} />
      </div>
      <div className="flex flex-col min-w-0">
        <span className="text-sm font-bold group-hover:text-primary transition-colors">{label}</span>
        <span className="text-[10px] text-muted-foreground truncate">{description}</span>
      </div>
    </button>
  );
}
