import { useState } from 'react'
import { NavLink } from 'react-router-dom'
import { useAuth } from '@/context/AuthContext'
import { cn } from '@/lib/utils'
import { Separator } from '@/components/ui/separator'
import {
  Dialog, DialogContent, DialogHeader, DialogTitle,
} from '@/components/ui/dialog'
import dakLogo from '@/assets/DAK_Best-Practice-768x768.png'
import {
  LayoutDashboard,
  FolderOpen,
  Upload,
  FileEdit,
  ClipboardCheck,
  FileBarChart,
  FileOutput,
  Users,
  Mail,
  History,
  UserCog,
  ShieldCheck,
  BookOpen,
  Scale,
  ShieldAlert,
} from 'lucide-react'

interface NavItem {
  label: string
  to: string
  icon: React.ComponentType<{ className?: string }>
  adminOnly?: boolean
  mitarbeiterOnly?: boolean
}

const mainNavItems: NavItem[] = [
  { label: 'Dashboard', to: '/dashboard', icon: LayoutDashboard },
  { label: 'Fälle', to: '/cases', icon: FolderOpen },
  { label: 'Import', to: '/import', icon: Upload, adminOnly: true },
  { label: 'ICD-Eingabe', to: '/icd', icon: FileEdit, mitarbeiterOnly: true },
  { label: 'Coding', to: '/coding', icon: ClipboardCheck, adminOnly: true },
  { label: 'Berichte', to: '/reports', icon: FileBarChart },
  { label: 'Wochenübersicht', to: '/wochenuebersicht', icon: FileOutput },
]

const accountNavItems: NavItem[] = [
  { label: 'Kontoverwaltung', to: '/account', icon: UserCog },
  { label: 'Meine Freigaben', to: '/disclosures', icon: ShieldCheck, mitarbeiterOnly: true },
  { label: 'Anleitung', to: '/anleitung', icon: BookOpen },
]

const adminNavItems: NavItem[] = [
  { label: 'Freigabe-Anfragen', to: '/admin/disclosures', icon: ShieldCheck },
  { label: 'Benutzer', to: '/admin/users', icon: Users },
  { label: 'Einladungen', to: '/admin/invitations', icon: Mail },
  { label: 'Audit-Log', to: '/admin/audit', icon: History },
]

function NavItemLink({ item }: { item: NavItem }) {
  const Icon = item.icon
  return (
    <NavLink
      to={item.to}
      className={({ isActive }) =>
        cn(
          'flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors',
          isActive
            ? 'bg-primary text-primary-foreground'
            : 'text-muted-foreground hover:bg-accent hover:text-accent-foreground'
        )
      }
    >
      <Icon className="h-4 w-4 shrink-0" />
      <span>{item.label}</span>
    </NavLink>
  )
}

const legalLinks = [
  { label: 'Impressum', icon: Scale, url: 'https://complexcaresolutions.de/impressum/' },
  { label: 'Datenschutz', icon: ShieldAlert, url: 'https://www.complexcaresolutions.de/datenschutzerklaerung/' },
]

export function Sidebar({ className }: { className?: string }) {
  const { user, isAdmin } = useAuth()
  const [legalDialog, setLegalDialog] = useState<{ title: string; url: string } | null>(null)

  const filterItems = (items: NavItem[]) =>
    items.filter((item) => {
      if (item.adminOnly && !isAdmin) return false
      if (item.mitarbeiterOnly && user?.role !== 'dak_mitarbeiter') return false
      return true
    })

  const visibleMainItems = filterItems(mainNavItems)
  const visibleAccountItems = filterItems(accountNavItems)

  return (
    <>
      <aside className={cn('flex h-full flex-col gap-4 p-4', className)}>
        <NavLink to="/dashboard" className="flex items-center justify-center px-3 py-2">
          <img src={dakLogo} alt="DAK Gesundheit" className="h-18 w-auto" />
        </NavLink>

        <nav className="flex flex-col gap-1">
          {visibleMainItems.map((item) => (
            <NavItemLink key={item.to} item={item} />
          ))}
        </nav>

        <Separator />
        <nav className="flex flex-col gap-1">
          {visibleAccountItems.map((item) => (
            <NavItemLink key={item.to} item={item} />
          ))}
        </nav>

        {isAdmin && (
          <>
            <Separator />
            <div className="px-3 py-1">
              <span className="text-xs font-semibold uppercase text-muted-foreground tracking-wider">
                Administration
              </span>
            </div>
            <nav className="flex flex-col gap-1">
              {adminNavItems.map((item) => (
                <NavItemLink key={item.to} item={item} />
              ))}
            </nav>
          </>
        )}

        {/* Legal footer — pushed to bottom */}
        <div className="mt-auto">
          <Separator />
          <nav className="flex flex-col gap-0.5 pt-2">
            {legalLinks.map(({ label, icon: Icon, url }) => (
              <button
                key={label}
                onClick={() => setLegalDialog({ title: label, url })}
                className="flex items-center gap-3 rounded-lg px-3 py-1.5 text-xs text-muted-foreground hover:bg-accent hover:text-accent-foreground transition-colors text-left"
              >
                <Icon className="h-3.5 w-3.5 shrink-0" />
                <span>{label}</span>
              </button>
            ))}
          </nav>
        </div>
      </aside>

      {/* Legal content dialog */}
      <Dialog open={!!legalDialog} onOpenChange={(open) => { if (!open) setLegalDialog(null) }}>
        <DialogContent className="max-w-4xl h-[85vh] flex flex-col p-0">
          <DialogHeader className="px-6 pt-6 pb-2">
            <DialogTitle>{legalDialog?.title}</DialogTitle>
          </DialogHeader>
          <iframe
            src={legalDialog?.url}
            className="flex-1 w-full border-0 rounded-b-lg"
            title={legalDialog?.title}
          />
        </DialogContent>
      </Dialog>
    </>
  )
}
