'use client';

import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { useState } from 'react';
import { useApi } from '@/hooks/useApi';
import { useAuthStore } from '@/store/authStore';
import { useToastStore } from '@/store/toastStore';

interface SignOutResponse {
  key?: string;
  status?: string;
  msg?: string;
  message?: string;
}

const navItems = [
  { href: '/dashboard/home', icon: 'ri-dashboard-3', label: 'الرئيسية' },
  { href: '/dashboard/buses', icon: 'ri-bus-2', label: 'الباصات' },
  { href: '/dashboard/drivers', icon: 'ri-steering-2', label: 'السائقون' },
  { href: '/dashboard/trips', icon: 'ri-route', label: 'الرحلات' },
  { href: '/dashboard/routes', icon: 'ri-map-2', label: 'المسارات' },
  { href: '/dashboard/subscribers', icon: 'ri-group', label: 'المشتركون' },
  { href: '/dashboard/plans', icon: 'ri-price-tag-2', label: 'خطط الاشتراك' },
  { href: '/dashboard/reports', icon: 'ri-bar-chart-2', label: 'التقارير' },
  { href: '/dashboard/settings', icon: 'ri-settings-3', label: 'الإعدادات' },
];

export default function DashboardSidebar({ collapsed, onToggle }: { collapsed: boolean; onToggle: () => void }) {
  const pathname = usePathname();
  const router = useRouter();
  const [showLogoutDialog, setShowLogoutDialog] = useState(false);
  const showToast = useToastStore((s) => s.showToast);
  const { request, loading, lastError } = useApi<SignOutResponse>();

  async function confirmLogout() {
    const result = await request('/account/sign-out', { method: 'DELETE' });

    if (!result) {
      showToast({
        severity: 'error',
        summary: 'خطأ',
        detail: lastError.current || 'فشل تسجيل الخروج',
        life: 4000,
      });
      return;
    }

    const success =
      result.key === 'success' ||
      String(result.status).toLowerCase() === 'success';

    showToast({
      severity: success ? 'success' : 'error',
      summary: success ? 'نجاح' : 'خطأ',
      detail: result.msg || result.message || (success ? 'تم تسجيل الخروج بنجاح' : 'فشل تسجيل الخروج'),
      life: 4000,
    });

    if (!success) return;

    useAuthStore.getState().logout();
    document.cookie = 'sast-token=; Path=/; Max-Age=0; SameSite=Lax';
    setShowLogoutDialog(false);
    router.replace('/');
  }

  return (
    <aside
      className="fixed top-0 right-0 h-full z-30 flex flex-col transition-all duration-300"
      style={{
        width: collapsed ? '72px' : '240px',
        background: '#0F172A',
        borderLeft: '1px solid rgba(255,255,255,0.06)',
      }}
    >
      {/* Logo */}
      <div className="flex items-center gap-3 px-4 py-5 border-b" style={{ borderColor: 'rgba(255,255,255,0.08)', minHeight: '72px' }}>
        <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: '#1E3A8A' }}>
          <i className="ri-bus-2-fill text-white text-xl"></i>
        </div>
        {!collapsed && (
          <span className="text-white text-lg font-black whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
            باصاتي
          </span>
        )}
      </div>

      {/* Nav */}
      <nav className="flex-1 py-4 overflow-y-auto">
        {navItems.map((item) => {
          const isActive = pathname.startsWith(item.href);
          return (
            <Link key={item.href} href={item.href}>
              <div
                className="flex items-center gap-3 mx-2 mb-1 rounded-xl cursor-pointer transition-all"
                style={{
                  padding: collapsed ? '10px 12px' : '10px 14px',
                  background: isActive ? '#1E3A8A' : 'transparent',
                  justifyContent: collapsed ? 'center' : 'flex-start',
                }}
                onMouseEnter={e => { if (!isActive) (e.currentTarget as HTMLElement).style.background = 'rgba(255,255,255,0.06)'; }}
                onMouseLeave={e => { if (!isActive) (e.currentTarget as HTMLElement).style.background = 'transparent'; }}
              >
                <div className="w-5 h-5 flex items-center justify-center flex-shrink-0">
                  <i className={`${item.icon}-${isActive ? 'fill' : 'line'} text-lg`} style={{ color: isActive ? 'white' : '#94a3b8' }}></i>
                </div>
                {!collapsed && (
                  <span className="text-sm whitespace-nowrap" style={{ color: isActive ? 'white' : '#94a3b8', fontFamily: '"IBM Plex Sans Arabic", sans-serif', fontWeight: isActive ? 600 : 400 }}>
                    {item.label}
                  </span>
                )}
              </div>
            </Link>
          );
        })}
      </nav>

      {/* Toggle + Logout */}
      <div className="border-t py-3 px-2 space-y-1" style={{ borderColor: 'rgba(255,255,255,0.08)' }}>
        <button
          onClick={onToggle}
          className="flex items-center gap-3 w-full rounded-xl cursor-pointer transition-all"
          style={{ padding: collapsed ? '10px 12px' : '10px 14px', justifyContent: collapsed ? 'center' : 'flex-start' }}
          onMouseEnter={e => (e.currentTarget.style.background = 'rgba(255,255,255,0.06)')}
          onMouseLeave={e => (e.currentTarget.style.background = 'transparent')}
        >
          <div className="w-5 h-5 flex items-center justify-center flex-shrink-0">
            <i className={`${collapsed ? 'ri-arrow-left-s-line' : 'ri-arrow-right-s-line'} text-lg`} style={{ color: '#94a3b8' }}></i>
          </div>
          {!collapsed && <span className="text-sm" style={{ color: '#94a3b8', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>طي القائمة</span>}
        </button>
        <button
          type="button"
          onClick={() => setShowLogoutDialog(true)}
          className="w-full"
        >
          <div
            className="flex items-center gap-3 rounded-xl cursor-pointer transition-all"
            style={{ padding: collapsed ? '10px 12px' : '10px 14px', justifyContent: collapsed ? 'center' : 'flex-start' }}
            onMouseEnter={e => (e.currentTarget.style.background = 'rgba(239,68,68,0.1)')}
            onMouseLeave={e => (e.currentTarget.style.background = 'transparent')}
          >
            <div className="w-5 h-5 flex items-center justify-center flex-shrink-0">
              <i className="ri-logout-box-r-line text-lg" style={{ color: '#f87171' }}></i>
            </div>
            {!collapsed && <span className="text-sm" style={{ color: '#f87171', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>تسجيل الخروج</span>}
          </div>
        </button>
      </div>

      {showLogoutDialog && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4"
          onClick={(e) => {
            if (e.target === e.currentTarget && !loading) setShowLogoutDialog(false);
          }}
        >
          <div
            className="w-full max-w-md rounded-2xl bg-white p-6 shadow-2xl"
            dir="rtl"
            style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
          >
            <h3 className="text-lg font-black text-slate-900">تأكيد تسجيل الخروج</h3>
            <p className="mt-2 text-sm text-slate-600">هل أنت متأكد أنك تريد تسجيل الخروج من حسابك؟</p>

            <div className="mt-6 flex items-center justify-end gap-2">
              <button
                type="button"
                onClick={() => setShowLogoutDialog(false)}
                disabled={loading}
                className="h-10 rounded-xl px-4 text-sm font-semibold"
                style={{
                  background: '#F1F5F9',
                  color: '#334155',
                  cursor: loading ? 'not-allowed' : 'pointer',
                }}
              >
                إلغاء
              </button>
              <button
                type="button"
                onClick={confirmLogout}
                disabled={loading}
                className="h-10 rounded-xl px-4 text-sm font-bold text-white"
                style={{
                  background: loading ? '#FCA5A5' : '#DC2626',
                  cursor: loading ? 'not-allowed' : 'pointer',
                }}
              >
                {loading ? 'جاري تسجيل الخروج...' : 'تأكيد'}
              </button>
            </div>
          </div>
        </div>
      )}
    </aside>
  );
}
