'use client';

import { useEffect, useRef, useState } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { clearAuth, getUser, getTenants, saveAuth, saveTenants, TenantInfo } from '@/lib/auth';
import api from '@/lib/api';

const NAV = [
  { href: '/',               label: 'Dashboard',    icon: '▦' },
  { href: '/clientes',       label: 'Clientes',      icon: '👥' },
  { href: '/produtos',       label: 'Produtos',      icon: '📦' },
  { href: '/propostas',      label: 'Propostas',     icon: '📋' },
  { href: '/contratos',      label: 'Contratos',     icon: '📄' },
  { href: '/cobrancas',      label: 'Cobranças',     icon: '💰' },
  { href: '/notas-fiscais',  label: 'NFS-e',         icon: '🧾' },
  { href: '/saas',           label: 'SaaS',          icon: '🔑' },
  { href: '/configuracoes',  label: 'Configurações', icon: '⚙️' },
];

function CompanyIcon({ tenant }: { tenant: TenantInfo | null }) {
  if (!tenant) {
    return (
      <div className="w-8 h-8 rounded-lg bg-[#B7895A] flex items-center justify-center shrink-0 text-sm font-semibold text-[#0E0F12]">
        K
      </div>
    );
  }
  if (tenant.logoUrl) {
    return (
      <div className="w-8 h-8 rounded-lg overflow-hidden shrink-0 bg-[#1F2024]">
        <Image src={tenant.logoUrl} alt={tenant.name} width={32} height={32} style={{ objectFit: 'contain', width: '100%', height: '100%' }} unoptimized />
      </div>
    );
  }
  return (
    <div className="w-8 h-8 rounded-lg bg-[#B7895A] flex items-center justify-center shrink-0 text-sm font-semibold text-[#0E0F12]">
      {tenant.name[0]?.toUpperCase() ?? 'K'}
    </div>
  );
}

interface SidebarProps {
  open?: boolean;
  onClose?: () => void;
}

export default function Sidebar({ open = false, onClose }: SidebarProps) {
  const pathname = usePathname();
  const router = useRouter();
  const [user, setUser] = useState<ReturnType<typeof getUser>>(null);
  const [tenants, setTenants] = useState<TenantInfo[]>([]);
  const [currentTenant, setCurrentTenant] = useState<TenantInfo | null>(null);
  const [switcherOpen, setSwitcherOpen] = useState(false);
  const [switching, setSwitching] = useState(false);
  const switcherRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    setUser(getUser());
  }, []);

  useEffect(() => {
    // Show cached list immediately, then refresh from API
    const stored = getTenants();
    if (stored.length > 0) {
      setTenants(stored);
      setCurrentTenant(stored.find((t) => t.id === user?.tenantId) ?? stored[0]);
    }
    api.get('/auth/my-tenants').then((r) => {
      const list: TenantInfo[] = r.data;
      saveTenants(list);
      setTenants(list);
      setCurrentTenant(list.find((t) => t.id === user?.tenantId) ?? list[0]);
    }).catch(() => {});
  }, [user?.tenantId]);

  useEffect(() => {
    function onClickOutside(e: MouseEvent) {
      if (switcherRef.current && !switcherRef.current.contains(e.target as Node)) {
        setSwitcherOpen(false);
      }
    }
    document.addEventListener('mousedown', onClickOutside);
    return () => document.removeEventListener('mousedown', onClickOutside);
  }, []);

  async function handleSwitch(tenantId: string, redirectTo?: string) {
    if (tenantId === user?.tenantId || switching) {
      if (redirectTo) router.push(redirectTo);
      setSwitcherOpen(false);
      return;
    }
    setSwitching(true);
    try {
      const { data } = await api.post('/auth/switch-tenant', { tenantId });
      saveAuth(data);
      setSwitcherOpen(false);
      window.location.href = redirectTo ?? pathname;
    } catch {
      setSwitching(false);
    }
  }

  function handleLogout() {
    clearAuth();
    router.push('/login');
  }

  const otherTenants = tenants.filter((t) => t.id !== user?.tenantId);

  return (
    <aside className={`
      flex flex-col w-64 bg-[#0E0F12] text-[#FAF7F2] shrink-0
      fixed inset-y-0 left-0 z-30 transition-transform duration-300 ease-in-out
      md:relative md:inset-auto md:z-auto md:translate-x-0
      ${open ? 'translate-x-0' : '-translate-x-full'}
    `}>

      {/* Company switcher */}
      <div ref={switcherRef} className="relative border-b border-[#1F2024]">
        <button
          onClick={() => setSwitcherOpen((v) => !v)}
          className="w-full flex items-center gap-3 px-5 py-4 hover:bg-[#1F2024] transition-colors text-left"
        >
          <CompanyIcon tenant={currentTenant} />
          <div className="flex-1 min-w-0">
            <p className="text-sm font-semibold text-[#FAF7F2] truncate">{currentTenant?.name ?? 'Klavo'}</p>
            <p className="text-xs text-[#FAF7F2]/40 truncate">{currentTenant?.plan ?? '—'}</p>
          </div>
          {tenants.length > 1 && (
            <span className="text-[#FAF7F2]/30 text-xs shrink-0">{switcherOpen ? '▲' : '▼'}</span>
          )}
        </button>

        {switcherOpen && (
          <div className="absolute left-0 right-0 top-full z-50 bg-[#1F2024] border border-[#2A2B2F] rounded-b-xl shadow-xl">
            {otherTenants.map((t) => (
              <div key={t.id} className="border-b border-[#2A2B2F] last:border-b-0">
                <button
                  onClick={() => handleSwitch(t.id)}
                  disabled={switching}
                  className="w-full flex items-center gap-3 px-5 py-3 hover:bg-[#0B2545] transition-colors text-left"
                >
                  <div className="w-7 h-7 rounded-md overflow-hidden shrink-0 flex items-center justify-center bg-[#B7895A] text-xs font-semibold text-[#0E0F12]">
                    {t.logoUrl ? (
                      <Image src={t.logoUrl} alt={t.name} width={28} height={28} style={{ objectFit: 'contain', width: '100%', height: '100%' }} unoptimized />
                    ) : (
                      t.name[0]?.toUpperCase()
                    )}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm text-[#FAF7F2] truncate">{t.name}</p>
                    <p className="text-xs text-[#FAF7F2]/40">{t.plan}</p>
                  </div>
                </button>
                <button
                  onClick={() => handleSwitch(t.id, '/configuracoes')}
                  disabled={switching}
                  className="w-full text-left px-5 py-1.5 text-xs text-[#B7895A] hover:text-[#D4A97A] hover:bg-[#0B2545] transition-colors"
                >
                  Dados da empresa →
                </button>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Navigation */}
      <nav className="flex-1 overflow-y-auto py-4">
        {NAV.map(({ href, label, icon }) => {
          const active = href === '/' ? pathname === '/' : pathname.startsWith(href);
          return (
            <Link
              key={href}
              href={href}
              onClick={() => onClose?.()}
              className={`flex items-center gap-3 px-6 py-2.5 text-sm transition-colors ${
                active
                  ? 'bg-[#0B2545] text-[#FAF7F2]'
                  : 'text-[#FAF7F2]/60 hover:bg-[#1F2024] hover:text-[#FAF7F2]'
              }`}
            >
              <span className="text-base leading-none">{icon}</span>
              {label}
            </Link>
          );
        })}
      </nav>

      {/* User footer */}
      <div className="px-6 py-4 border-t border-[#1F2024]">
        <p className="text-xs text-[#FAF7F2]/60 truncate">{user?.name}</p>
        <p className="text-xs text-[#FAF7F2]/30 truncate mb-3">{user?.email}</p>
        <button
          onClick={handleLogout}
          className="w-full text-xs text-[#FAF7F2]/40 hover:text-[#FAF7F2] transition-colors text-left"
        >
          Sair →
        </button>
      </div>
    </aside>
  );
}
