'use client';

import { useState, type ReactNode } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import {
  BookOpen,
  Calendar,
  CircleAlert,
  CreditCard,
  Crown,
  FileHeart,
  FileText,
  HeartPulse,
  LayoutDashboard,
  ListChecks,
  LogOut,
  Menu,
  MessageSquareHeart,
  ReceiptText,
  Smartphone,
  Sparkles,
  TrendingUp,
  UserCircle,
  Users,
  X,
} from 'lucide-react';
import { DynamicLogo, GradientBackground } from '@sehat/ui';
import { useAuth } from '@/lib/auth-context';

interface NavItem {
  href: string;
  label: string;
  icon: typeof LayoutDashboard;
  /** Optional grouping header rendered above this item. */
  section?: string;
}

/**
 * Sidebar nav schema — kept in one place so the patient portal stays
 * coherent across pages. The grouping is purely visual; routes are flat.
 */
const NAV: NavItem[] = [
  { href: '/dashboard', label: 'Dashboard', icon: LayoutDashboard, section: 'Care' },
  { href: '/health', label: 'My health', icon: HeartPulse },
  { href: '/messages', label: 'Coach inbox', icon: Sparkles },
  { href: '/appointments', label: 'Appointments', icon: Calendar },
  { href: '/prescriptions', label: 'Prescriptions', icon: ReceiptText },
  { href: '/emr', label: 'My EMR', icon: FileHeart },
  { href: '/family', label: 'Family', icon: Users },
  { href: '/cases', label: 'Cases', icon: ListChecks, section: 'History' },
  { href: '/stats', label: 'Stats', icon: TrendingUp },
  { href: '/transactions', label: 'Transactions', icon: CreditCard },
  { href: '/feedback', label: 'Feedback', icon: MessageSquareHeart },
  { href: '/complaints', label: 'Complaints', icon: CircleAlert },
  { href: '/profile', label: 'My profile', icon: UserCircle, section: 'Account' },
  { href: '/packages', label: 'Care plans', icon: Crown },
  { href: '/package-change', label: 'Change plan', icon: FileText },
  { href: '/devices', label: 'Devices', icon: Smartphone },
];

interface PatientShellProps {
  /** When set, the main column uses tone="warm"; defaults to soft. */
  tone?: 'warm' | 'soft';
  /** Page heading rendered in the top bar (md+). */
  title?: string;
  /** Optional one-line description under the title. */
  subtitle?: string;
  children: ReactNode;
}

/**
 * Patient portal app shell — vertical sidebar on md+, top hamburger drawer
 * on smaller screens. Highlights the active route by prefix match so nested
 * pages (e.g. /family/[id]) keep their parent tab lit.
 */
export function PatientShell({
  tone = 'soft',
  title,
  subtitle,
  children,
}: PatientShellProps) {
  const pathname = usePathname() ?? '/dashboard';
  const { user, logout } = useAuth();
  const [drawerOpen, setDrawerOpen] = useState(false);

  const isActive = (href: string) => {
    if (href === '/dashboard') return pathname === '/dashboard';
    return pathname === href || pathname.startsWith(`${href}/`);
  };

  const sidebar = (
    <nav className="flex h-full flex-col">
      <div className="flex items-center gap-3 px-5 py-6">
        <DynamicLogo variant="mark" size="md" />
        <div>
          <p className="font-display text-sm font-bold text-ink-1">Sehat Sahoolat</p>
          <p className="text-[11px] uppercase tracking-wider text-ink-3">
            Patient
          </p>
        </div>
      </div>

      <div className="flex-1 overflow-y-auto px-3 pb-4">
        {NAV.map((item) => {
          const Icon = item.icon;
          const active = isActive(item.href);
          return (
            <div key={item.href}>
              {item.section ? (
                <p className="mt-5 mb-2 px-3 font-display text-[10px] font-bold uppercase tracking-[0.18em] text-ink-3">
                  {item.section}
                </p>
              ) : null}
              <Link
                href={item.href}
                onClick={() => setDrawerOpen(false)}
                className={[
                  'group flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium transition-all',
                  active
                    ? 'bg-gradient-coral text-white shadow-sm'
                    : 'text-ink-2 hover:bg-warmSurface-bg hover:text-ink-1',
                ].join(' ')}
              >
                <Icon
                  className={[
                    'h-4 w-4 transition-transform',
                    active ? 'scale-110' : 'group-hover:scale-105',
                  ].join(' ')}
                />
                {item.label}
              </Link>
            </div>
          );
        })}
      </div>

      <div className="border-t border-warmSurface-border px-5 py-4">
        <div className="mb-3">
          <p className="font-display text-sm font-semibold text-ink-1">
            {user?.firstName ?? 'Patient'}
          </p>
          <p className="truncate text-xs text-ink-3">{user?.email}</p>
        </div>
        <div className="flex items-center gap-3">
          <button
            type="button"
            onClick={() => {
              window.dispatchEvent(new CustomEvent('replay-onboarding'));
              setDrawerOpen(false);
            }}
            className="inline-flex items-center gap-2 rounded-lg px-2 py-1.5 text-xs font-semibold text-ink-2 transition-colors hover:bg-warmSurface-bg hover:text-brand-600"
          >
            <BookOpen className="h-3.5 w-3.5" />
            Tour
          </button>
          <button
            type="button"
            onClick={() => void logout()}
            className="inline-flex items-center gap-2 rounded-lg px-2 py-1.5 text-xs font-semibold text-ink-2 transition-colors hover:bg-warmSurface-bg hover:text-coral-700"
          >
            <LogOut className="h-3.5 w-3.5" />
            Sign out
          </button>
        </div>
      </div>
    </nav>
  );

  return (
    <GradientBackground variant={tone === 'warm' ? 'hero' : 'soft'}>
      <div className="relative min-h-screen md:flex">
        {/* Desktop sidebar */}
        <aside className="sticky top-0 hidden h-screen w-64 shrink-0 border-r border-warmSurface-border bg-warmSurface-card/85 backdrop-blur-glass md:flex md:flex-col">
          {sidebar}
        </aside>

        {/* Mobile drawer overlay */}
        {drawerOpen ? (
          <div className="fixed inset-0 z-50 md:hidden">
            <div
              className="absolute inset-0 bg-navy-900/40 backdrop-blur-sm"
              onClick={() => setDrawerOpen(false)}
              aria-hidden
            />
            <aside className="absolute inset-y-0 left-0 w-72 bg-warmSurface-card shadow-lg">
              <div className="flex items-center justify-end px-4 pt-4">
                <button
                  type="button"
                  onClick={() => setDrawerOpen(false)}
                  className="rounded-lg p-2 text-ink-2 hover:bg-warmSurface-bg"
                  aria-label="Close menu"
                >
                  <X className="h-5 w-5" />
                </button>
              </div>
              {sidebar}
            </aside>
          </div>
        ) : null}

        <div className="min-w-0 flex-1">
          {/* Mobile top bar */}
          <header className="sticky top-0 z-30 flex items-center justify-between border-b border-warmSurface-border bg-warmSurface-card/85 px-4 py-3 backdrop-blur-glass md:hidden">
            <button
              type="button"
              onClick={() => setDrawerOpen(true)}
              className="rounded-lg p-2 text-ink-2 hover:bg-warmSurface-bg"
              aria-label="Open menu"
            >
              <Menu className="h-5 w-5" />
            </button>
            <div className="flex items-center gap-2">
              <DynamicLogo variant="mark" size="sm" />
              <p className="font-display text-sm font-semibold text-ink-1">
                Sehat Sahoolat
              </p>
            </div>
            <div className="w-9" />
          </header>

          {title ? (
            <div className="border-b border-warmSurface-border/60 bg-warmSurface-card/40 px-6 py-5 backdrop-blur-glass md:px-10">
              <h1 className="font-display text-2xl font-bold text-ink-1">
                {title}
              </h1>
              {subtitle ? (
                <p className="mt-1 text-sm text-ink-2">{subtitle}</p>
              ) : null}
            </div>
          ) : null}

          <main className="px-4 py-6 md:px-10 md:py-8">{children}</main>
        </div>
      </div>
    </GradientBackground>
  );
}
