'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Sidebar from '@/components/Sidebar';
import Topbar from '@/components/Topbar';
import Dashboard from '@/components/Dashboard';
import Agenda from '@/components/Agenda';
import Clients from '@/components/Clients';
import Services from '@/components/Services';
import Team from '@/components/Team';
import Settings from '@/components/Settings';
import Subscription from '@/components/Subscription';

// Helper para cookies
const getCookie = (name: string): string => {
  if (typeof document === 'undefined') return '';
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop()!.split(';').shift() || '';
  return '';
};

const setCookie = (name: string, value: string, days: number = 7) => {
  if (typeof document === 'undefined') return;
  const date = new Date();
  date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
  const expires = "; expires=" + date.toUTCString();
  document.cookie = name + "=" + (value || "") + expires + "; path=/";
};

export default function Home() {
  const [currentPage, setCurrentPage] = useState('dashboard');
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [currentPlan, setCurrentPlan] = useState('Professional');
  const [isLocked, setIsLocked] = useState(false);
  const [loadingSubscription, setLoadingSubscription] = useState(true);
  const router = useRouter();

  const checkSubscriptionStatus = async () => {
    const slug = localStorage.getItem('agendapro_tenant_slug') || 'barbearia-premium';
    
    // Verifica primeiro se há um status ativo local/homologação
    const localStatus = localStorage.getItem('agendapro_subscription_status') || getCookie('agendapro_subscription_status');
    if (localStatus === 'active') {
      setIsLocked(false);
      setLoadingSubscription(false);
      return;
    }

    try {
      const res = await fetch(`/api/tenant/subscription?slug=${slug}`);
      if (res.ok) {
        const data = await res.json();
        const inactive = data.status !== 'active';
        setIsLocked(inactive);
        if (inactive) {
          setCurrentPage('subscription');
        }
        if (data.subscription?.plan_name) {
          setCurrentPlan(data.subscription.plan_name);
        }
      }
    } catch (err) {
      console.error('Erro ao verificar assinatura:', err);
    } finally {
      setLoadingSubscription(false);
    }
  };

  useEffect(() => {
    const token = localStorage.getItem('agendapro_token');
    if (!token) {
      router.push('/login');
    } else {
      checkSubscriptionStatus();
    }

    const handleStorageChange = () => {
      checkSubscriptionStatus();
    };
    window.addEventListener('storage', handleStorageChange);
    return () => window.removeEventListener('storage', handleStorageChange);
  }, [router]);

  const handlePlanChange = (newPlan: string) => {
    setCurrentPlan(newPlan);
    localStorage.setItem('agendapro_plan', newPlan);
    setCookie('agendapro_plan', newPlan, 30);
  };

  const pages: Record<string, { title: string; subtitle: string }> = {
    dashboard: { title: 'Dashboard', subtitle: 'Visão geral do seu negócio' },
    agenda: { title: 'Agenda', subtitle: 'Gerencie seus agendamentos' },
    clients: { title: 'Clientes', subtitle: 'Base de clientes' },
    services: { title: 'Serviços', subtitle: 'Catálogo de serviços' },
    team: { title: 'Equipe', subtitle: 'Profissionais e horários' },
    settings: { title: 'Configurações', subtitle: 'Personalize seu estabelecimento' },
    subscription: { title: 'Assinatura', subtitle: 'Gerencie seu plano' },
  };

  const renderPage = () => {
    switch (currentPage) {
      case 'dashboard': return <Dashboard onNavigate={setCurrentPage} />;
      case 'agenda': return <Agenda />;
      case 'clients': return <Clients />;
      case 'services': return <Services />;
      case 'team': return <Team />;
      case 'settings': return <Settings />;
      case 'subscription': return (
        <Subscription 
          currentPlan={currentPlan} 
          onPlanChange={handlePlanChange} 
          isLocked={isLocked}
          onPaymentSuccess={checkSubscriptionStatus}
        />
      );
      default: return <Dashboard onNavigate={setCurrentPage} />;
    }
  };

  if (loadingSubscription) {
    return (
      <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--bg-primary)', flexDirection: 'column', gap: '16px' }}>
        <div className="avatar avatar-lg" style={{ animation: 'pulse 1.5s infinite', width: 64, height: 64, fontSize: 24, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>✂️</div>
        <div style={{ color: 'var(--text-secondary)', fontWeight: 600 }}>Carregando dados do AgendaPRO...</div>
      </div>
    );
  }

  return (
    <div className="app-layout">
      <Sidebar
        currentPage={currentPage}
        onNavigate={setCurrentPage}
        isOpen={sidebarOpen}
        onClose={() => setSidebarOpen(false)}
        currentPlan={currentPlan}
        isLocked={isLocked}
      />
      <main className="main-content">
        <Topbar
          title={pages[currentPage]?.title || 'Dashboard'}
          subtitle={pages[currentPage]?.subtitle || ''}
          onMenuClick={() => setSidebarOpen(true)}
        />
        <div className="page-content fade-in" key={currentPage}>
          {renderPage()}
        </div>
      </main>
    </div>
  );
}
