'use client';

import React from 'react';
import { useBranding } from '@/context/BrandingContext';
import AppLogo from '@/components/common/AppLogo';

export type SaasTabType =
  | 'dashboard'
  | 'stores'
  | 'active_installs'
  | 'uninstalled'
  | 'subscriptions'
  | 'billing'
  | 'analytics'
  | 'logs'
  | 'settings';

interface SidebarProps {
  activeTab: SaasTabType;
  onTabChange: (tab: SaasTabType) => void;
  stats?: {
    totalStores: number;
    activeStores: number;
    uninstalledStores: number;
    paidStores: number;
    mrr: number;
  };
  isMobileOpen?: boolean;
  onCloseMobile?: () => void;
}

export default function SaasAdminSidebar({
  activeTab,
  onTabChange,
  stats,
  isMobileOpen,
  onCloseMobile,
}: SidebarProps) {
  const { branding } = useBranding();
  const navItems = [
    {
      id: 'dashboard' as SaasTabType,
      label: 'Dashboard',
      icon: 'fa-solid fa-chart-pie',
      badge: null,
      section: 'main',
    },
    {
      id: 'stores' as SaasTabType,
      label: 'All Stores',
      icon: 'fa-solid fa-store',
      badge: stats ? stats.totalStores.toString() : null,
      section: 'stores',
    },
    {
      id: 'active_installs' as SaasTabType,
      label: 'Active Installations',
      icon: 'fa-solid fa-circle-check',
      badge: stats ? stats.activeStores.toString() : null,
      badgeColor: 'bg-emerald-100 text-emerald-800',
      section: 'stores',
    },
    {
      id: 'uninstalled' as SaasTabType,
      label: 'Uninstalled Stores',
      icon: 'fa-solid fa-circle-xmark',
      badge: stats && stats.uninstalledStores > 0 ? stats.uninstalledStores.toString() : null,
      badgeColor: 'bg-rose-100 text-rose-800',
      section: 'stores',
    },
    {
      id: 'subscriptions' as SaasTabType,
      label: 'Subscriptions',
      icon: 'fa-solid fa-id-card',
      badge: stats ? `${stats.paidStores} paid` : null,
      badgeColor: 'bg-blue-100 text-blue-800',
      section: 'finance',
    },
    {
      id: 'billing' as SaasTabType,
      label: 'Billing & Revenue',
      icon: 'fa-solid fa-dollar-sign',
      badge: stats ? `$${stats.mrr}` : null,
      badgeColor: 'bg-emerald-100 text-emerald-800',
      section: 'finance',
    },
    {
      id: 'analytics' as SaasTabType,
      label: 'Analytics & Reports',
      icon: 'fa-solid fa-chart-line',
      badge: null,
      section: 'intelligence',
    },
    {
      id: 'logs' as SaasTabType,
      label: 'Activity Logs',
      icon: 'fa-solid fa-clock-rotate-left',
      badge: null,
      section: 'system',
    },
    {
      id: 'settings' as SaasTabType,
      label: 'Settings',
      icon: 'fa-solid fa-gear',
      badge: null,
      section: 'system',
    },
  ];

  return (
    <>
      {/* Mobile Backdrop */}
      {isMobileOpen && (
        <div
          onClick={onCloseMobile}
          className="fixed inset-0 bg-slate-900/40 backdrop-blur-xs z-40 lg:hidden"
        />
      )}

      {/* Sidebar Container */}
      <aside
        className={`fixed top-0 bottom-0 left-0 z-50 w-64 bg-white border-r border-slate-200/90 flex flex-col transition-transform duration-300 ease-in-out lg:static lg:translate-x-0 ${
          isMobileOpen ? 'translate-x-0' : '-translate-x-full'
        }`}
      >
        {/* Brand / Logo Header */}
        <div className="h-16 px-5 border-b border-slate-200/80 flex items-center justify-between">
          <div className="flex items-center gap-3 min-w-0">
            <AppLogo size="md" fallbackIcon="fa-brands fa-shopify" />
            <div className="min-w-0">
              <div className="flex items-center gap-1.5 min-w-0">
                <span className="font-extrabold text-xs sm:text-sm text-slate-900 tracking-tight truncate max-w-[120px]" title={branding.appName}>
                  {branding.appName}
                </span>
                <span className="text-[10px] font-black uppercase tracking-wider px-1.5 py-0.2 rounded bg-theme/10 text-theme border border-theme/20 shrink-0">
                  Hub
                </span>
              </div>
              <p className="text-[10px] text-slate-400 font-medium truncate">SaaS Store &amp; Revenue</p>
            </div>
          </div>
          <button
            onClick={onCloseMobile}
            className="lg:hidden p-1.5 text-slate-400 hover:text-slate-600 rounded-lg"
          >
            <i className="fa-solid fa-xmark text-sm" />
          </button>
        </div>

        {/* Navigation Link Groups */}
        <div className="flex-1 overflow-y-auto py-4 px-3 space-y-6">
          {/* Main Section */}
          <div className="space-y-1">
            <span className="px-3 text-[10px] font-bold text-slate-400 uppercase tracking-wider">
              Overview
            </span>
            {navItems
              .filter((i) => i.section === 'main')
              .map((item) => (
                <button
                  key={item.id}
                  onClick={() => {
                    onTabChange(item.id);
                    if (onCloseMobile) onCloseMobile();
                  }}
                  className={`w-full flex items-center justify-between px-3 py-2 rounded-xl text-xs font-semibold transition-all cursor-pointer ${
                    activeTab === item.id
                      ? 'bg-theme/10 text-theme font-bold shadow-2xs border border-theme/20'
                      : 'text-slate-600 hover:bg-slate-50 hover:text-slate-900'
                  }`}
                >
                  <div className="flex items-center gap-2.5">
                    <i className={`${item.icon} text-xs w-4 text-center ${activeTab === item.id ? 'text-theme' : 'text-slate-400'}`} />
                    <span>{item.label}</span>
                  </div>
                  {item.badge && (
                    <span className="text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-slate-100 text-slate-600">
                      {item.badge}
                    </span>
                  )}
                </button>
              ))}
          </div>

          {/* Stores Section */}
          <div className="space-y-1">
            <span className="px-3 text-[10px] font-bold text-slate-400 uppercase tracking-wider">
              Stores Management
            </span>
            {navItems
              .filter((i) => i.section === 'stores')
              .map((item) => (
                <button
                  key={item.id}
                  onClick={() => {
                    onTabChange(item.id);
                    if (onCloseMobile) onCloseMobile();
                  }}
                  className={`w-full flex items-center justify-between px-3 py-2 rounded-xl text-xs font-semibold transition-all cursor-pointer ${
                    activeTab === item.id
                      ? 'bg-theme/10 text-theme font-bold shadow-2xs border border-theme/20'
                      : 'text-slate-600 hover:bg-slate-50 hover:text-slate-900'
                  }`}
                >
                  <div className="flex items-center gap-2.5">
                    <i className={`${item.icon} text-xs w-4 text-center ${activeTab === item.id ? 'text-theme' : 'text-slate-400'}`} />
                    <span>{item.label}</span>
                  </div>
                  {item.badge && (
                    <span
                      className={`text-[10px] font-bold px-1.5 py-0.5 rounded-full ${
                        item.badgeColor || 'bg-slate-100 text-slate-600'
                      }`}
                    >
                      {item.badge}
                    </span>
                  )}
                </button>
              ))}
          </div>

          {/* Billing & Subscriptions Section */}
          <div className="space-y-1">
            <span className="px-3 text-[10px] font-bold text-slate-400 uppercase tracking-wider">
              Billing &amp; Revenue
            </span>
            {navItems
              .filter((i) => i.section === 'finance')
              .map((item) => (
                <button
                  key={item.id}
                  onClick={() => {
                    onTabChange(item.id);
                    if (onCloseMobile) onCloseMobile();
                  }}
                  className={`w-full flex items-center justify-between px-3 py-2 rounded-xl text-xs font-semibold transition-all cursor-pointer ${
                    activeTab === item.id
                      ? 'bg-theme/10 text-theme font-bold shadow-2xs border border-theme/20'
                      : 'text-slate-600 hover:bg-slate-50 hover:text-slate-900'
                  }`}
                >
                  <div className="flex items-center gap-2.5">
                    <i className={`${item.icon} text-xs w-4 text-center ${activeTab === item.id ? 'text-theme' : 'text-slate-400'}`} />
                    <span>{item.label}</span>
                  </div>
                  {item.badge && (
                    <span
                      className={`text-[10px] font-bold px-1.5 py-0.5 rounded-full ${
                        item.badgeColor || 'bg-slate-100 text-slate-600'
                      }`}
                    >
                      {item.badge}
                    </span>
                  )}
                </button>
              ))}
          </div>

          {/* Analytics & System Section */}
          <div className="space-y-1">
            <span className="px-3 text-[10px] font-bold text-slate-400 uppercase tracking-wider">
              System &amp; Logs
            </span>
            {navItems
              .filter((i) => ['intelligence', 'system'].includes(i.section))
              .map((item) => (
                <button
                  key={item.id}
                  onClick={() => {
                    onTabChange(item.id);
                    if (onCloseMobile) onCloseMobile();
                  }}
                  className={`w-full flex items-center justify-between px-3 py-2 rounded-xl text-xs font-semibold transition-all cursor-pointer ${
                    activeTab === item.id
                      ? 'bg-theme/10 text-theme font-bold shadow-2xs border border-theme/20'
                      : 'text-slate-600 hover:bg-slate-50 hover:text-slate-900'
                  }`}
                >
                  <div className="flex items-center gap-2.5">
                    <i className={`${item.icon} text-xs w-4 text-center ${activeTab === item.id ? 'text-theme' : 'text-slate-400'}`} />
                    <span>{item.label}</span>
                  </div>
                  {item.badge && (
                    <span className="text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-slate-100 text-slate-600">
                      {item.badge}
                    </span>
                  )}
                </button>
              ))}
          </div>
        </div>

        {/* Live Synchronizer Pill */}
        <div className="p-3 border-t border-slate-200/80 bg-slate-50/60">
          <div className="p-3 rounded-xl bg-white border border-slate-200/80 shadow-2xs flex items-center gap-3">
            <span className="relative flex h-2.5 w-2.5 shrink-0">
              <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75" />
              <span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-emerald-500" />
            </span>
            <div className="min-w-0">
              <div className="text-[11px] font-bold text-slate-900 truncate">Shopify Webhooks Live</div>
              <div className="text-[10px] text-slate-400 truncate">Listening to real-time events</div>
            </div>
          </div>
        </div>
      </aside>
    </>
  );
}
