import { motion } from 'framer-motion'
import { Link, useLocation } from 'react-router-dom'
import { useAuth } from '@/lib/auth'
import { useEffect, useState } from 'react'
import { api, type Settings } from '@/lib/api'

const API_HOST = import.meta.env.VITE_API_URL?.replace('/api', '') || 'http://localhost:3001';
import { getAcademicYearLabel, useAcademicYear } from '@/contexts/AcademicYearContext'

function AnneesScolairesIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <rect x="2" y="3" width="16" height="14" rx="2" />
      <path d="M2 7h16M6 1v4M14 1v4" />
    </svg>
  )
}

const navItems = [
  { label: 'Tableau de bord', icon: DashboardIcon, path: '/' },
  { label: 'Filieres', icon: FilieresIcon, path: '/filieres' },
  { label: 'Etudiants', icon: EtudiantsIcon, path: '/etudiants' },
  { label: 'Paiements', icon: PaiementsIcon, path: '/paiements' },
  { label: 'Rapports', icon: RapportsIcon, path: '/rapports' },
]

const adminNavItems = [
  { label: 'Annees Scolaires', icon: AnneesScolairesIcon, path: '/annees-scolaires' },
  { label: 'Parametres', icon: SettingsIcon, path: '/settings' },
]

function SettingsIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="10" cy="10" r="3" />
      <path d="M16.5 10a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06A1.65 1.65 0 0 0 12.18 15a1.65 1.65 0 0 0-1 .69 1.65 1.65 0 0 0-.33 1V17a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-.33-1A1.65 1.65 0 0 0 5.82 15a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 1.5 10a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 5.82 5c.39 0 .76-.14 1.04-.39.28-.25.46-.6.51-.98V3a2 2 0 1 1 4 0v.09c.05.38.23.73.51.98.28.25.65.39 1.04.39.69 0 1.35-.27 1.82-.75l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06c-.48.47-.75 1.13-.75 1.82Z" />
    </svg>
  )
}

function DashboardIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <rect x="2" y="2" width="7" height="7" rx="1.5" />
      <rect x="11" y="2" width="7" height="7" rx="1.5" />
      <rect x="2" y="11" width="7" height="7" rx="1.5" />
      <rect x="11" y="11" width="7" height="7" rx="1.5" />
    </svg>
  )
}

function FilieresIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 4h14M3 10h14M3 16h10" />
    </svg>
  )
}

function EtudiantsIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="10" cy="6" r="3.5" />
      <path d="M3.5 17.5c0-3.59 2.91-6.5 6.5-6.5s6.5 2.91 6.5 6.5" />
    </svg>
  )
}

function PaiementsIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <rect x="2" y="4" width="16" height="12" rx="2" />
      <path d="M2 8h16" />
    </svg>
  )
}

function RapportsIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M4 2h8l4 4v12a2 2 0 01-2 2H4a2 2 0 01-2-2V4a2 2 0 012-2z" />
      <path d="M12 2v4h4" />
      <path d="M6 12h8M6 15h5" />
    </svg>
  )
}

interface SidebarProps {
  isOpen: boolean
  onClose: () => void
}

export default function Sidebar({ isOpen, onClose }: SidebarProps) {
  const location = useLocation()
  const { user } = useAuth()
  const [settings, setSettings] = useState<Settings | null>(null)
  const {
    academicYears,
    selectedAcademicYear,
    activeAcademicYear,
    isLoading: isAcademicYearsLoading,
    setSelectedAcademicYearId,
  } = useAcademicYear()

  const allNavItems = user?.role === 'ADMIN' ? [...navItems, ...adminNavItems] : navItems
  const displayedAcademicYear = selectedAcademicYear ?? activeAcademicYear

  useEffect(() => {
    api.getSettings().then(setSettings).catch(() => undefined)
  }, [])

  function isActive(path: string) {
    if (path === '/') return location.pathname === '/'
    return location.pathname.startsWith(path)
  }

  return (
    <>
      {/* Mobile overlay */}
      {isOpen && (
        <div
          className="fixed inset-0 bg-black/50 z-40 lg:hidden"
          onClick={onClose}
        />
      )}

      <motion.aside
        initial={{ x: -20, opacity: 0 }}
        animate={{ x: 0, opacity: 1 }}
        transition={{ duration: 0.3 }}
        className={`
          fixed top-0 left-0 h-full w-64 bg-sidebar z-50
          flex flex-col
          lg:translate-x-0
          ${isOpen ? 'translate-x-0' : '-translate-x-full'}
          transition-transform duration-300 lg:transition-none
        `}
      >
        {/* Logo */}
        <div className="flex items-center gap-3 px-6 py-6">
          <img
            src={`${API_HOST}${settings?.logoUrl || '/api/settings/logo'}`}
            alt={`${settings?.nomCommercial || 'ISPM'} Logo`}
            className="h-10 w-auto max-w-[120px] object-contain"
          />
          <div className="text-white font-bold text-lg leading-tight">{settings?.nomCommercial || 'ISPM'}</div>
        </div>

        {/* Navigation */}
        <nav className="flex-1 px-3 mt-4">
          {allNavItems.map((item) => (
            <Link
              key={item.label}
              to={item.path}
              onClick={onClose}
              className={`
                flex items-center gap-3 px-4 py-3 rounded-lg mb-1
                transition-all duration-200
                ${isActive(item.path)
                  ? 'bg-accent text-white'
                  : 'text-white/70 hover:bg-white/10 hover:text-white'
                }
              `}
            >
              <item.icon />
              <span className="text-sm font-medium">{item.label}</span>
            </Link>
          ))}
        </nav>

        {/* Academic year at bottom */}
        <div className="px-6 py-5 border-t border-white/10">
          <div className="flex items-start gap-3">
            <svg width="18" height="18" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="1.5" className="text-white/60">
              <rect x="2" y="3" width="14" height="13" rx="2" />
              <path d="M2 7h14M6 1v4M12 1v4" />
            </svg>
            <div className="flex-1 min-w-0">
              <div className="text-white/60 text-xs">Annee academique</div>
              <div className="text-white text-sm font-medium">
                {displayedAcademicYear ? getAcademicYearLabel(displayedAcademicYear) : 'Aucune annee disponible'}
              </div>
              {user?.role === 'ADMIN' && academicYears.length > 0 && (
                <select
                  value={selectedAcademicYear?.id ?? activeAcademicYear?.id ?? ''}
                  onChange={(event) => setSelectedAcademicYearId(event.target.value)}
                  disabled={isAcademicYearsLoading}
                  className="mt-3 w-full rounded-md border border-white/10 bg-white/10 px-3 py-2 text-sm text-white outline-none transition focus:border-white/30 disabled:cursor-not-allowed disabled:opacity-60"
                >
                  {academicYears.map((year) => (
                    <option key={year.id} value={year.id} className="text-slate-900">
                      {getAcademicYearLabel(year)}
                    </option>
                  ))}
                </select>
              )}
            </div>
          </div>
        </div>
      </motion.aside>
    </>
  )
}
