import React from 'react';
import { useLocation, Link, useNavigate } from 'react-router-dom';
import { motion } from 'framer-motion';
import { LayoutDashboard, Users, Kanban, CheckSquare, Tag, Filter, Upload, Settings, Palette, User, FormInput, ScrollText, ChevronDown, LogOut, Zap, List, Trash2, Building2, Mail, FileText, KeyRound } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useAuth } from '@/contexts/AuthContext';
import { MenuItem } from '@/lib/types';
import { Sidebar, SidebarContent, SidebarGroup, SidebarGroupContent, SidebarMenu, SidebarMenuButton, SidebarMenuItem, SidebarMenuSub, SidebarMenuSubItem, SidebarMenuSubButton, SidebarHeader, SidebarFooter, useSidebar } from '@/components/ui/sidebar';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';

// Menu configuration
const menuItems: MenuItem[] = [{
  id: 'dashboard',
  label: 'Dashboard',
  path: '/',
  icon: 'LayoutDashboard'
}, {
  id: 'contacts',
  label: 'Contacts',
  path: '/contacts',
  icon: 'Users'
}, {
  id: 'properties',
  label: 'Properties',
  path: '/properties',
  icon: 'Building2'
}, {
  id: 'tenancies',
  label: 'Tenancies',
  path: '/tenancies',
  icon: 'KeyRound'
}, {
  id: 'pipelines',
  label: 'Pipelines',
  path: '/pipelines',
  icon: 'Kanban'
}, {
  id: 'tasks',
  label: 'Tasks',
  path: '/tasks',
  icon: 'CheckSquare'
}, {
  id: 'trash',
  label: 'Trash',
  path: '/trash',
  icon: 'Trash2'
}, {
  id: 'settings',
  label: 'Settings',
  path: '/settings',
  icon: 'Settings',
  children: [{
    id: 'appearance',
    label: 'Appearance',
    path: '/settings/appearance',
    icon: 'Palette'
  }, {
    id: 'custom-fields',
    label: 'Custom Fields',
    path: '/settings/custom-fields',
    icon: 'List'
  }, {
    id: 'tags',
    label: 'Tags',
    path: '/settings/tags',
    icon: 'Tag'
  }, {
    id: 'business',
    label: 'Business',
    path: '/settings/business',
    icon: 'Building2'
  }, {
    id: 'email',
    label: 'Email Config',
    path: '/settings/email',
    icon: 'Mail'
  }, {
    id: 'email-templates',
    label: 'Email Templates',
    path: '/settings/email-templates',
    icon: 'FileText'
  }]
}];
const iconMap: Record<string, React.ComponentType<{
  className?: string;
}>> = {
  LayoutDashboard,
  Users,
  Kanban,
  CheckSquare,
  Tag,
  Filter,
  Upload,
  Settings,
  Palette,
  User,
  FormInput,
  ScrollText,
  List,
  Trash2,
  Building2,
  Mail,
  FileText,
  KeyRound
};
export function AppSidebar() {
  const location = useLocation();
  const navigate = useNavigate();
  const {
    profile,
    signOut
  } = useAuth();
  const {
    state
  } = useSidebar();
  const isCollapsed = state === 'collapsed';
  const isActive = (path: string) => {
    if (path === '/') return location.pathname === '/';
    return location.pathname.startsWith(path);
  };
  const getInitials = (name: string | null | undefined) => {
    if (!name) return 'U';
    return name.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2);
  };
  const handleSignOut = async () => {
    await signOut();
    navigate('/login');
  };
  return <Sidebar collapsible="icon" className="border-r border-sidebar-border">
      <SidebarHeader className="border-b border-sidebar-border p-4">
        <Link to="/" className="flex items-center gap-3">
          <div className="flex h-9 w-9 items-center justify-center rounded-lg gradient-primary shadow-glow">
            <Zap className="h-5 w-5 text-primary-foreground" />
          </div>
          {!isCollapsed && <motion.span initial={{
          opacity: 0
        }} animate={{
          opacity: 1
        }} className="text-lg font-semibold tracking-tight">
              PropCRM
            </motion.span>}
        </Link>
      </SidebarHeader>

      <SidebarContent className="px-2 py-4">
        <SidebarGroup>
          <SidebarGroupContent>
            <SidebarMenu>
              {menuItems.map(item => item.children ? <Collapsible key={item.id} defaultOpen={isActive(item.path)}>
                    <SidebarMenuItem>
                      <CollapsibleTrigger asChild>
                        <SidebarMenuButton tooltip={item.label} className={cn('w-full transition-colors', isActive(item.path) && 'bg-sidebar-accent text-sidebar-accent-foreground')}>
                          {iconMap[item.icon] && React.createElement(iconMap[item.icon], {
                      className: 'h-4 w-4'
                    })}
                          <span className="flex-1">{item.label}</span>
                          <ChevronDown className="h-4 w-4 transition-transform group-data-[state=open]:rotate-180" />
                        </SidebarMenuButton>
                      </CollapsibleTrigger>
                      <CollapsibleContent>
                        <SidebarMenuSub>
                          {item.children.map(child => <SidebarMenuSubItem key={child.id}>
                              <SidebarMenuSubButton asChild isActive={isActive(child.path)}>
                                <Link to={child.path}>
                                  {iconMap[child.icon] && React.createElement(iconMap[child.icon], {
                            className: 'h-4 w-4'
                          })}
                                  <span>{child.label}</span>
                                </Link>
                              </SidebarMenuSubButton>
                            </SidebarMenuSubItem>)}
                        </SidebarMenuSub>
                      </CollapsibleContent>
                    </SidebarMenuItem>
                  </Collapsible> : <SidebarMenuItem key={item.id}>
                    <SidebarMenuButton asChild tooltip={item.label} isActive={isActive(item.path)}>
                      <Link to={item.path} className="relative">
                        {iconMap[item.icon] && React.createElement(iconMap[item.icon], {
                    className: 'h-4 w-4'
                  })}
                        <span>{item.label}</span>
                        {item.badge && <Badge variant="secondary" className="ml-auto h-5 min-w-5 justify-center rounded-full bg-primary text-primary-foreground text-xs">
                            {item.badge}
                          </Badge>}
                      </Link>
                    </SidebarMenuButton>
                  </SidebarMenuItem>)}
            </SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>
      </SidebarContent>

      <SidebarFooter className="border-t border-sidebar-border p-2">
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <button className="flex w-full items-center gap-3 rounded-lg p-2 text-left transition-colors hover:bg-sidebar-accent">
              <Avatar className="h-8 w-8">
                <AvatarFallback className="bg-primary text-primary-foreground text-xs">
                  {getInitials(profile?.name)}
                </AvatarFallback>
              </Avatar>
              {!isCollapsed && <div className="flex-1 overflow-hidden">
                  <p className="truncate text-sm font-medium">{profile?.name || 'User'}</p>
                  <p className="truncate text-xs text-muted-foreground">{profile?.email}</p>
                </div>}
            </button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="start" className="w-56">
            <DropdownMenuItem asChild>
              <Link to="/settings/appearance" className="flex items-center gap-2">
                <Palette className="h-4 w-4" />
                Appearance
              </Link>
            </DropdownMenuItem>
            <DropdownMenuItem asChild>
              <Link to="/settings/custom-fields" className="flex items-center gap-2">
                <List className="h-4 w-4" />
                Custom Fields
              </Link>
            </DropdownMenuItem>
            <DropdownMenuSeparator />
            <DropdownMenuItem onClick={handleSignOut} className="text-destructive focus:text-destructive">
              <LogOut className="mr-2 h-4 w-4" />
              Sign out
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </SidebarFooter>
    </Sidebar>;
}