/**
 * @file Dashboard.tsx
 * @description Painel principal de controlo ('Dashboard') para barbearias na web.
 * Consolida a visualização de Agendamentos, Histórico, Pedidos (produtos),
 * Gestão de Serviços/Produtos e Perfis de Barbeiros numa única view complexa.
 */
import { useMemo, useState, useEffect } from 'react';
import { Card } from '../components/ui/card';
import { Button } from '../components/ui/button';
import { Input } from '../components/ui/input';
import { Badge } from '../components/ui/badge';
import { Tabs } from '../components/ui/tabs';
import { currency } from '../lib/format';
import { useApp } from '../context/AppContext';
import { supabase } from '../lib/supabase';
import { Product, BarberShop, ShopSchedule } from '../types';
import { BarChart, Bar, CartesianGrid, ResponsiveContainer, Tooltip, XAxis } from 'recharts';
import { CalendarWeekView } from '../components/CalendarWeekView';
import {
  BarChart3,
  Calendar,
  ShoppingBag,
  Scissors,
  Package,
  Users,
  TrendingUp,
  AlertTriangle,
  Plus,
  Trash2,
  Minus,
  Plus as PlusIcon,
  History,
  ChevronLeft,
  ChevronRight,
  List,
  ZoomIn,
  ZoomOut,
  RefreshCw,
  Search,
  Printer,
  ChevronDown,
  UserPlus,
  Globe,
  HelpCircle,
  MessageCircle,
  Settings,
  Store,
  Clock,
  ArrowRight,
  CheckCircle2,
} from 'lucide-react';

type TabId = 'overview' | 'appointments' | 'history' | 'orders' | 'services' | 'products' | 'barbers' | 'settings';

interface SidebarTab {
  id: TabId;
  label: string;
  icon: React.FC<any>;
  badge?: number;
}

const periods: Record<string, (date: Date) => boolean> = {
  hoje: (d) => {
    const now = new Date();
    return d.toDateString() === now.toDateString();
  },
  semana: (d) => {
    const now = new Date();
    const diff = now.getTime() - d.getTime();
    return diff <= 7 * 24 * 60 * 60 * 1000;
  },
  mes: (d) => {
    const now = new Date();
    return d.getMonth() === now.getMonth() && d.getFullYear() === now.getFullYear();
  },
  total: () => true,
};

const parseDate = (value: string) => new Date(value.replace(' ', 'T'));



export default function Dashboard() {
  const { user, shops, shopsReady } = useApp();
  const shop = shops.find((s) => s.id === user?.shopId);

  if (!user || user.role !== 'barbearia') return <div>Área exclusiva para barbearias.</div>;

  // Enquanto as lojas não foram carregadas do Supabase, mostra o spinner
  if (!shopsReady) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '60vh' }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{
            width: 40, height: 40, border: '4px solid #e2e8f0', borderTopColor: '#6366f1',
            borderRadius: '50%', animation: 'spin 0.8s linear infinite', margin: '0 auto 12px'
          }} />
          <p style={{ color: '#64748b', fontSize: 14 }}>A preparar painel...</p>
          <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
        </div>
      </div>
    );
  }
  if (!shop) return <div>Barbearia não encontrada.</div>;

  return <DashboardInner shop={shop} />;
}

function DashboardInner({ shop }: { shop: BarberShop }) {
  // Importa estado global interligado com Supabase (ex: updateAppointmentStatus reflete-se na BD)
  const {
    user,
    users,
    appointments,
    orders,
    updateAppointmentStatus,
    updateOrderStatus,
    addService,
    addProduct,
    addBarber,
    updateProduct,
    deleteProduct,
    deleteService,
    deleteBarber,
    updateBarber,
    updateShopDetails,
  } = useApp();

  const [activeTab, setActiveTab] = useState<TabId>('overview');
  const [period, setPeriod] = useState<keyof typeof periods>('semana');
  const [currentWeek, setCurrentWeek] = useState(new Date());

  // Form states
  const [svcName, setSvcName] = useState('');
  const [svcPrice, setSvcPrice] = useState<number>(50);
  const [svcDuration, setSvcDuration] = useState<number>(30);

  const [prodName, setProdName] = useState('');
  const [prodPrice, setProdPrice] = useState<number>(30);
  const [prodStock, setProdStock] = useState<number>(10);

  const [barberName, setBarberName] = useState('');
  const [barberSpecs, setBarberSpecs] = useState('');
  const [barberSearchQuery, setBarberSearchQuery] = useState('');

  // Settings states
  const [editShopName, setEditShopName] = useState(shop.name);
  const [editShopAddress, setEditShopAddress] = useState(shop.address || '');
  const [editPaymentMethods, setEditPaymentMethods] = useState(shop.paymentMethods?.join(', ') || 'Dinheiro, Cartão de Crédito, Cartão de Débito');
  const [editSocials, setEditSocials] = useState(shop.socialNetworks || { whatsapp: '', instagram: '', facebook: '' });
  const [editContacts, setEditContacts] = useState(shop.contacts || { phone1: '', phone2: '' });
  const [editSchedule, setEditSchedule] = useState<ShopSchedule[]>(shop.schedule || [
    { day: 'Segunda-feira', open: '09:00', close: '19:30' },
    { day: 'Terça-feira', open: '09:00', close: '19:30' },
    { day: 'Quarta-feira', open: '09:00', close: '19:30' },
    { day: 'Quinta-feira', open: '09:00', close: '19:30' },
    { day: 'Sexta-feira', open: '09:00', close: '19:30' },
    { day: 'Sábado', open: '09:00', close: '19:00' },
    { day: 'Domingo', open: '', close: '', closed: true },
  ]);

  const [isSavingSettings, setIsSavingSettings] = useState(false);
  const [showSaveSuccess, setShowSaveSuccess] = useState(false);

  useEffect(() => {
    if (shop) {
      setEditShopName(shop.name || '');
      setEditShopAddress(shop.address || '');
      setEditPaymentMethods(shop.paymentMethods?.join(', ') || 'Dinheiro, Cartão de Crédito, Cartão de Débito');
      setEditSocials(shop.socialNetworks || { whatsapp: '', instagram: '', facebook: '' });
      setEditContacts(shop.contacts || { phone1: '', phone2: '' });
      
      if (shop.schedule && shop.schedule.length > 0) {
        setEditSchedule(shop.schedule);
      }
    }
  }, [shop]);

  const periodMatch = periods[period];

  // Agendamentos filtrados pela barbearia logada e pela janela de tempo selecionada
  const allShopAppointments = appointments.filter((a) => a.shopId === shop.id && periodMatch(parseDate(a.date)));

  // Agendamentos ativos (não concluídos e não cancelados)
  const shopAppointments = allShopAppointments.filter((a) => a.status !== 'concluido' && a.status !== 'cancelado');

  // Pedidos apenas com produtos (não serviços)
  const shopOrders = orders.filter(
    (o) => o.shopId === shop.id && periodMatch(new Date(o.createdAt))
  );

  const pendingOrders = orders.filter((o) => o.shopId === shop.id && o.status === 'pendente').length;
  const pendingAppts = shopAppointments.filter((a) => a.status === 'pendente').length;
  const confirmedAppts = shopAppointments.filter((a) => a.status === 'confirmado').length;



  const totalRevenue = shopOrders.reduce((s, o) => s + o.total, 0);
  const lowStock = shop.products.filter((p) => p.stock <= 3);

  const comparisonData = useMemo(() => {
    const totals = shopOrders.reduce(
      (acc, order) => {
        order.items.forEach((item) => {
          if (item.type === 'service') {
            acc.services += item.qty;
          } else {
            acc.products += item.qty;
          }
        });
        return acc;
      },
      { services: 0, products: 0 }
    );
    return [
      { name: 'Serviços', value: totals.services },
      { name: 'Produtos', value: totals.products },
    ];
  }, [shopOrders]);

  const topServices = useMemo(() => {
    const map = new Map<string, { name: string; qty: number }>();
    shopOrders.forEach((o) =>
      o.items
        .filter((i) => i.type === 'service')
        .forEach((i) => {
          const svc = shop.services.find((s) => s.id === i.refId);
          if (!svc) return;
          const prev = map.get(i.refId)?.qty ?? 0;
          map.set(i.refId, { name: svc.name, qty: prev + i.qty });
        })
    );
    return Array.from(map.values())
      .sort((a, b) => b.qty - a.qty)
      .slice(0, 5);
  }, [shopOrders, shop.services]);

  const topProducts = useMemo(() => {
    const map = new Map<string, { name: string; qty: number }>();
    shopOrders.forEach((o) =>
      o.items
        .filter((i) => i.type === 'product')
        .forEach((i) => {
          const prod = shop.products.find((p) => p.id === i.refId);
          if (!prod) return;
          const prev = map.get(i.refId)?.qty ?? 0;
          map.set(i.refId, { name: prod.name, qty: prev + i.qty });
        })
    );
    return Array.from(map.values())
      .sort((a, b) => b.qty - a.qty)
      .slice(0, 5);
  }, [shopOrders, shop.products]);

  const updateProductStock = (product: Product, delta: number) => {
    const next = { ...product, stock: Math.max(0, product.stock + delta) };
    updateProduct(shop.id, next);
  };

  const addNewService = () => {
    if (!svcName.trim()) return;
    addService(shop.id, { name: svcName, price: Number(svcPrice) || 0, duration: Number(svcDuration) || 30, barberIds: [] });
    setSvcName('');
    setSvcPrice(50);
    setSvcDuration(30);
  };

  const addNewProduct = () => {
    if (!prodName.trim()) return;
    addProduct(shop.id, { name: prodName, price: Number(prodPrice) || 0, stock: Number(prodStock) || 0 });
    setProdName('');
    setProdPrice(30);
    setProdStock(10);
  };

  const addNewBarber = () => {
    if (!barberName.trim()) return;
    addBarber(shop.id, {
      name: barberName,
      imageUrl: '', 
      specialties: [],
      schedule: [],
    });
    setBarberName('');
  };

  const [uploadingBarberId, setUploadingBarberId] = useState<string | null>(null);

  const handleBarberImageUpload = async (barberId: string, e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file || !shop) return;
    setUploadingBarberId(barberId);

    try {
      const fileExt = file.name.split('.').pop();
      const fileName = `${barberId}-${Math.random()}.${fileExt}`;
      const filePath = `barbers/${fileName}`;

      const { error: uploadError } = await supabase.storage
        .from('shops')
        .upload(filePath, file);

      if (uploadError) throw uploadError;

      const { data } = supabase.storage
        .from('shops')
        .getPublicUrl(filePath);

      const barber = shop.barbers.find(b => b.id === barberId);
      if (barber) {
        await updateBarber(shop.id, { ...barber, imageUrl: data.publicUrl });
        alert('Foto do barbeiro atualizada!');
      }
    } catch (error: any) {
      console.error('Erro ao fazer upload da imagem do barbeiro:', error);
      alert(`Erro: ${error?.message}`);
    } finally {
      setUploadingBarberId(null);
    }
  };

  const [isUploading, setIsUploading] = useState(false);

  const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file || !shop) return;
    setIsUploading(true);

    try {
      const fileExt = file.name.split('.').pop();
      const fileName = `${shop.id}-${Math.random()}.${fileExt}`;
      const filePath = `covers/${fileName}`;

      const { error: uploadError } = await supabase.storage
        .from('shops')
        .upload(filePath, file);

      if (uploadError) throw uploadError;

      const { data } = supabase.storage
        .from('shops')
        .getPublicUrl(filePath);

      await updateShopDetails(shop.id, { imageUrl: data.publicUrl });
      alert('Foto de capa atualizada com sucesso!');
    } catch (error: any) {
      console.error('Erro ao fazer upload da imagem:', error);
      alert(`Erro ao fazer upload: ${error?.message || 'Erro desconhecido'}\n\nSe disser "bucket not found", certifique-se que criou o bucket "shops" no Storage do Supabase como Public.`);
    } finally {
      setIsUploading(false);
    }
  };

  const handleSaveSettings = async () => {
    setIsSavingSettings(true);
    setShowSaveSuccess(false);
    try {
      await updateShopDetails(shop.id, {
        name: editShopName,
        address: editShopAddress,
        paymentMethods: editPaymentMethods.split(',').map(s => s.trim()).filter(Boolean),
        socialNetworks: editSocials,
        contacts: editContacts,
        schedule: editSchedule,
      });
      setShowSaveSuccess(true);
      setTimeout(() => setShowSaveSuccess(false), 3000);
    } catch (err) {
      console.error('Error saving settings:', err);
      alert('Erro ao guardar as definições. Tente novamente.');
    } finally {
      setIsSavingSettings(false);
    }
  };

  const sidebarTabs: SidebarTab[] = [
    { id: 'overview', label: 'Visão Geral', icon: BarChart3 },
    { id: 'appointments', label: 'Agendamentos', icon: Calendar, badge: pendingAppts > 0 ? pendingAppts : undefined },
    { id: 'history', label: 'Histórico', icon: History },
    { id: 'orders', label: 'Pedidos', icon: ShoppingBag, badge: pendingOrders > 0 ? pendingOrders : undefined },
    { id: 'services', label: 'Serviços', icon: Scissors },
    { id: 'products', label: 'Produtos', icon: Package },
    { id: 'barbers', label: 'Profissionais', icon: Users },
    { id: 'settings', label: 'Definições', icon: Settings },
  ];

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-4">
        <div>
          <h1 className="text-xl sm:text-2xl font-bold text-slate-900">{shop.name}</h1>
          <p className="text-sm text-slate-600">{shop.address}</p>
        </div>
        <div className="flex items-center gap-1.5 sm:gap-2 overflow-x-auto scrollbar-hide pb-1">
          {(['hoje', 'semana', 'mes', 'total'] as const).map((p) => (
            <button
              key={p}
              onClick={() => setPeriod(p)}
              className={`px-2.5 sm:px-3 py-1.5 rounded-lg text-[11px] sm:text-xs font-medium border transition-all whitespace-nowrap shrink-0 ${period === p
                ? 'border-indigo-500 bg-indigo-50 text-indigo-700 shadow-sm'
                : 'border-slate-200 text-slate-700 hover:border-indigo-300 hover:bg-indigo-50/50'
                }`}
            >
              {p === 'mes' ? 'Mês' : p === 'hoje' ? 'Hoje' : p === 'semana' ? 'Semana' : 'Total'}
            </button>
          ))}
        </div>
      </div>

      {/* Tabs */}
      <div className="w-full max-w-[100vw] overflow-hidden">
        <Tabs tabs={sidebarTabs.map((t) => ({ id: t.id, label: t.label, badge: t.badge }))} active={activeTab} onChange={(v) => setActiveTab(v as TabId)} />
      </div>

      {/* Tab Content */}
      {activeTab === 'overview' && (
        <div className="space-y-6">
          {/* Saudação */}
          <div className="space-y-1">
            <h1 className="text-2xl font-bold text-slate-900">
              {new Date().toLocaleDateString('pt-PT', { weekday: 'long', day: 'numeric', month: 'long' })}
            </h1>
            <p className="text-slate-600">
              {(() => {
                const hour = new Date().getHours();
                if (hour < 12) return 'Bom dia';
                if (hour < 18) return 'Boa tarde';
                return 'Boa noite';
              })()}, {user?.name}
            </p>
          </div>

          {/* Stats Cards Principais */}
          <div className="grid md:grid-cols-3 gap-3">
            <Card className="p-4 sm:p-6">
              <div className="flex items-center justify-between mb-2 sm:mb-3">
                <div className="p-2 sm:p-3 bg-indigo-500 rounded-lg text-white">
                  <Calendar size={20} className="sm:hidden" />
                  <Calendar size={24} className="hidden sm:block" />
                </div>
              </div>
              <p className="text-xs sm:text-sm text-slate-600 mb-0.5 sm:mb-1">Total de reservas</p>
              <p className="text-2xl sm:text-3xl font-bold text-slate-900">{allShopAppointments.length}</p>
              <p className="text-[10px] sm:text-xs text-slate-500 mt-1.5 sm:mt-2">Reservas da plataforma: {allShopAppointments.length}</p>
            </Card>

            <Card className="p-4 sm:p-6">
              <div className="flex items-center justify-between mb-2 sm:mb-3">
                <div className="p-2 sm:p-3 bg-blue-500 rounded-lg text-white">
                  <Globe size={20} className="sm:hidden" />
                  <Globe size={24} className="hidden sm:block" />
                </div>
              </div>
              <p className="text-xs sm:text-sm text-slate-600 mb-0.5 sm:mb-1">Reservas online</p>
              <p className="text-2xl sm:text-3xl font-bold text-slate-900">{allShopAppointments.length}</p>
              <p className="text-[10px] sm:text-xs text-slate-500 mt-1.5 sm:mt-2">Marcações feitas pela plataforma</p>
            </Card>

            <Card className="p-4 sm:p-6">
              <div className="flex items-center justify-between mb-2 sm:mb-3">
                <div className="p-2 sm:p-3 bg-green-500 rounded-lg text-white">
                  <UserPlus size={20} className="sm:hidden" />
                  <UserPlus size={24} className="hidden sm:block" />
                </div>
              </div>
              <p className="text-xs sm:text-sm text-slate-600 mb-0.5 sm:mb-1">Novos clientes</p>
              <p className="text-2xl sm:text-3xl font-bold text-slate-900">
                {new Set(allShopAppointments.map(a => a.customerId)).size}
              </p>
              <p className="text-[10px] sm:text-xs text-slate-500 mt-1.5 sm:mt-2">Clientes únicos</p>
            </Card>
          </div>

          {/* Layout em duas colunas */}
          <div className="grid md:grid-cols-3 gap-6">
            {/* Coluna Principal - Esquerda */}
            <div className="md:col-span-2 space-y-6">
              {/* Calendário de Visão Geral */}
              <Card className="p-6">
                <div className="flex items-center justify-between mb-4">
                  <div className="flex items-center gap-3">
                    <div className="p-2 bg-indigo-100 rounded-lg">
                      <Calendar size={20} className="text-indigo-600" />
                    </div>
                    <div>
                      <h3 className="text-lg font-bold text-slate-900">Calendário de Reservas</h3>
                      <p className="text-sm text-slate-600">Visão panorâmica da semana atual</p>
                    </div>
                  </div>
                  <Button variant="outline" size="sm" onClick={() => setActiveTab('appointments')}>
                    Gerir Pedidos
                    <ArrowRight size={16} className="ml-2" />
                  </Button>
                </div>

                {/* Reutiliza o Componente de Calendário Inteiro na aba Overview */}
                <CalendarWeekView
                  week={currentWeek}
                  appointments={shopAppointments}
                  shop={shop}
                  onWeekChange={setCurrentWeek}
                  onStatusChange={updateAppointmentStatus}
                />
              </Card>
            </div>

            {/* Coluna Lateral - Direita */}
            <div className="space-y-6">
              {/* Ajuda */}
              <Card className="p-6">
                <h3 className="text-lg font-bold text-slate-900 mb-4">Tem alguma pergunta?</h3>
                <div className="space-y-3">
                  <a
                    href="https://wa.me/351931410547?text=Olá!%20Preciso%20de%20ajuda%20com%20a%20Plataforma%20Barbearia."
                    target="_blank"
                    rel="noopener noreferrer"
                    className="w-full flex items-center gap-3 p-3 border border-slate-200 rounded-lg hover:bg-slate-50 transition-colors text-left"
                  >
                    <div className="p-2 bg-blue-100 rounded-lg">
                      <MessageCircle size={18} className="text-blue-600" />
                    </div>
                    <span className="font-medium text-slate-900">Contacte-nos (WhatsApp)</span>
                  </a>
                </div>
              </Card>

              {/* Próximos Agendamentos */}
              <Card className="p-6">
                <h3 className="text-lg font-bold text-slate-900 mb-4">Seguinte</h3>
                {(() => {
                  const upcoming = allShopAppointments
                    .filter(a => {
                      const aptDate = new Date(a.date.replace(' ', 'T'));
                      return aptDate > new Date() && a.status !== 'cancelado';
                    })
                    .sort((a, b) => {
                      const dateA = new Date(a.date.replace(' ', 'T'));
                      const dateB = new Date(b.date.replace(' ', 'T'));
                      return dateA.getTime() - dateB.getTime();
                    })
                    .slice(0, 3);

                  if (upcoming.length === 0) {
                    return (
                      <p className="text-sm text-slate-500 text-center py-4">Sem agendamentos futuros</p>
                    );
                  }

                  return (
                    <div className="space-y-3">
                      {upcoming.map(a => {
                        const svc = shop.services.find(s => s.id === a.serviceId);
                        const barber = shop.barbers.find(b => b.id === a.barberId);
                        const customer = users.find(u => u.id === a.customerId);
                        const aptDate = new Date(a.date.replace(' ', 'T'));
                        const timeStr = aptDate.toLocaleTimeString('pt-PT', { hour: '2-digit', minute: '2-digit' });

                        return (
                          <div key={a.id} className="flex items-start gap-3 p-3 border border-slate-200 rounded-lg">
                            <div className="p-1.5 bg-indigo-100 rounded">
                              <Clock size={14} className="text-indigo-600" />
                            </div>
                            <div className="flex-1 min-w-0">
                              <p className="font-semibold text-slate-900 truncate">{customer?.name || 'Cliente'}</p>
                              <p className="text-sm text-slate-600">{timeStr}</p>
                              <p className="text-xs text-slate-500 truncate">{svc?.name || 'Serviço'}</p>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  );
                })()}
              </Card>
            </div>
          </div>

        </div>
      )}

      {activeTab === 'appointments' && (
        <div className="space-y-6">
          <div className="flex items-center justify-between mb-2">
            <div>
              <h2 className="text-xl font-bold text-slate-900">Caixa de Pedidos</h2>
              <p className="text-sm text-slate-600">Aprove ou recuse os pedidos pendentes e conclua os serviços de hoje.</p>
            </div>
            <Badge color="indigo" variant="soft">{pendingAppts} Novos Pedidos</Badge>
          </div>

          {/* Secção de Pedidos Pendentes */}
          <Card className="p-6 border-indigo-200">
            <div className="flex items-center gap-2 mb-4 pb-4 border-b border-slate-100">
              <Clock className="text-indigo-500" size={20} />
              <h3 className="font-bold text-slate-900">Aguardam Aprovação</h3>
              <Badge color="slate" variant="soft" className="ml-auto">{pendingAppts}</Badge>
            </div>
            {shopAppointments.filter(a => a.status === 'pendente').length > 0 ? (
              <div className="space-y-3">
                {shopAppointments.filter(a => a.status === 'pendente').map((a) => {
                  const svc = shop.services.find((s) => s.id === a.serviceId);
                  const barber = shop.barbers.find((b) => b.id === a.barberId);
                  const customer = users.find((u) => u.id === a.customerId);
                  const aptDate = new Date(a.date.replace(' ', 'T'));

                  return (
                    <div key={a.id} className="flex flex-col sm:flex-row sm:items-center justify-between p-4 bg-indigo-50/50 border border-indigo-100 rounded-lg gap-4">
                      <div className="flex-1 grid grid-cols-1 sm:grid-cols-3 gap-4">
                        <div>
                          <p className="text-xs text-slate-500 mb-1">Cliente</p>
                          <p className="font-semibold text-slate-900">{customer?.name || 'Cliente'}</p>
                        </div>
                        <div>
                          <p className="text-xs text-slate-500 mb-1">Serviço</p>
                          <p className="font-semibold text-slate-900">{svc?.name ?? 'Serviço'}</p>
                          <p className="text-xs text-slate-500">com {barber?.name ?? 'Barbeiro'}</p>
                        </div>
                        <div>
                          <p className="text-xs text-slate-500 mb-1">Data / Hora</p>
                          <p className="font-semibold text-indigo-700">
                            {aptDate.toLocaleDateString('pt-PT', { day: 'numeric', month: 'short' })} às {aptDate.toLocaleTimeString('pt-PT', { hour: '2-digit', minute: '2-digit' })}
                          </p>
                        </div>
                      </div>
                      <div className="flex items-center gap-2 mt-2 sm:mt-0">
                        <Button
                          variant="outline"
                          className="text-red-600 border-red-200 hover:bg-red-50 hover:border-red-300"
                          onClick={() => updateAppointmentStatus(a.id, 'cancelado')}
                        >
                          Recusar
                        </Button>
                        <Button
                          className="bg-indigo-600 hover:bg-indigo-700 text-white"
                          onClick={() => updateAppointmentStatus(a.id, 'confirmado')}
                        >
                          Aceitar
                        </Button>
                      </div>
                    </div>
                  );
                })}
              </div>
            ) : (
              <div className="text-center py-8">
                <CheckCircle2 size={40} className="mx-auto text-slate-300 mb-2" />
                <p className="text-slate-500 text-sm">Não há pedidos pendentes no momento.</p>
              </div>
            )}
          </Card>

          {/* Secção de Pedidos Confirmados */}
          <Card className="p-6">
            <div className="flex items-center gap-2 mb-4 pb-4 border-b border-slate-100">
              <Calendar className="text-green-500" size={20} />
              <h3 className="font-bold text-slate-900">Agendamentos Aprovados</h3>
              <Badge color="slate" variant="soft" className="ml-auto">{confirmedAppts}</Badge>
            </div>
            {shopAppointments.filter(a => a.status === 'confirmado').length > 0 ? (
              <div className="space-y-3">
                {shopAppointments.filter(a => a.status === 'confirmado').map((a) => {
                  const svc = shop.services.find((s) => s.id === a.serviceId);
                  const barber = shop.barbers.find((b) => b.id === a.barberId);
                  const customer = users.find((u) => u.id === a.customerId);
                  const aptDate = new Date(a.date.replace(' ', 'T'));

                  return (
                    <div key={a.id} className="flex flex-col sm:flex-row sm:items-center justify-between p-4 border border-slate-200 rounded-lg gap-4">
                      <div className="flex-1 grid grid-cols-1 sm:grid-cols-3 gap-4">
                        <div>
                          <p className="text-xs text-slate-500 mb-1">Cliente</p>
                          <p className="font-semibold text-slate-900">{customer?.name || 'Cliente'}</p>
                        </div>
                        <div>
                          <p className="text-xs text-slate-500 mb-1">Serviço</p>
                          <p className="font-semibold text-slate-900">{svc?.name ?? 'Serviço'}</p>
                          <p className="text-xs text-slate-500">com {barber?.name ?? 'Barbeiro'}</p>
                        </div>
                        <div>
                          <p className="text-xs text-slate-500 mb-1">Data / Hora</p>
                          <p className="font-semibold text-slate-900">
                            {aptDate.toLocaleDateString('pt-PT', { day: 'numeric', month: 'short' })} às {aptDate.toLocaleTimeString('pt-PT', { hour: '2-digit', minute: '2-digit' })}
                          </p>
                        </div>
                      </div>
                      <div className="flex items-center gap-2 mt-2 sm:mt-0">
                        <Button
                          variant="outline"
                          className="text-red-600 border-red-200 hover:bg-red-50 hover:border-red-300"
                          onClick={() => {
                            if (window.confirm('Tem a certeza que deseja cancelar esta marcação?')) {
                              updateAppointmentStatus(a.id, 'cancelado');
                            }
                          }}
                        >
                          Cancelar
                        </Button>
                        <Button
                          className="bg-green-600 hover:bg-green-700 text-white"
                          onClick={() => updateAppointmentStatus(a.id, 'concluido')}
                        >
                          Concluir Serviço
                        </Button>
                      </div>
                    </div>
                  );
                })}
              </div>
            ) : (
              <div className="text-center py-8">
                <Calendar size={40} className="mx-auto text-slate-300 mb-2" />
                <p className="text-slate-500 text-sm">Próximos serviços irão aparecer aqui.</p>
              </div>
            )}
          </Card>
        </div>
      )}

      {activeTab === 'history' && (() => {
        // O histórico agora compreende marcacões permanentemente finalizadas (Cancelados e Concluídos)
        const historyAppointments = allShopAppointments.filter(a => a.status === 'concluido' || a.status === 'cancelado');

        return (
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-bold text-slate-900">Histórico de Agendamentos</h2>
              <Badge color="slate" variant="soft">{historyAppointments.length} registos</Badge>
            </div>
            <div className="space-y-3">
              {historyAppointments.length > 0 ? (
                historyAppointments.map((a) => {
                  const svc = shop.services.find((s) => s.id === a.serviceId);
                  const barber = shop.barbers.find((b) => b.id === a.barberId);
                  const customer = users.find((u) => u.id === a.customerId);
                  const aptDate = new Date(a.date.replace(' ', 'T'));

                  return (
                    <div key={a.id} className="flex items-center justify-between p-4 border border-slate-200 rounded-lg bg-slate-50/50">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          <p className="font-bold text-slate-900">{svc?.name ?? 'Serviço'}</p>
                          <Badge color={a.status === 'concluido' ? 'green' : 'red'} variant="soft">
                            {a.status === 'concluido' ? 'Concluído' : 'Cancelado'}
                          </Badge>
                        </div>
                        <p className="text-sm text-slate-600">
                          {customer?.name || 'Cliente'} c/ {barber?.name ?? 'Barbeiro'} ·
                          {aptDate.toLocaleDateString('pt-PT', { day: 'numeric', month: 'short' })}
                        </p>
                        <p className="text-xs text-slate-500 mt-1">{currency(a.total)}</p>
                      </div>
                    </div>
                  );
                })
              ) : (
                <div className="text-center py-12">
                  <History size={48} className="mx-auto text-slate-300 mb-3" />
                  <p className="text-slate-600 font-medium">Nenhum registo no período selecionado</p>
                  <p className="text-sm text-slate-500 mt-1">Os agendamentos cancelados ou concluídos aparecerão aqui.</p>
                </div>
              )}
            </div>
          </Card>
        );
      })()}

      {activeTab === 'orders' && (
        <Card className="p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-bold text-slate-900">Pedidos de Produtos</h2>
            <Badge color="slate" variant="soft">{shopOrders.length} no período</Badge>
          </div>
          <div className="space-y-3">
            {shopOrders.length > 0 ? (
              shopOrders.map((o) => {
                const productItems = o.items.filter((i) => i.type === 'product');
                const productTotal = productItems.reduce((sum, item) => {
                  const prod = shop.products.find((p) => p.id === item.refId);
                  return sum + (prod?.price ?? 0) * item.qty;
                }, 0);
                return (
                  <div key={o.id} className="p-4 border border-slate-200 rounded-lg hover:border-indigo-300 transition-colors">
                    <div className="flex items-center justify-between mb-3">
                      <div className="flex items-center gap-2">
                        <p className="font-bold text-indigo-700">{currency(productTotal)}</p>
                        <Badge color={o.status === 'pendente' ? 'indigo' : o.status === 'confirmado' ? 'green' : o.status === 'concluido' ? 'green' : 'red'}>
                          {o.status === 'pendente' ? 'Pendente' : o.status === 'confirmado' ? 'Confirmado' : o.status === 'concluido' ? 'Concluído' : 'Cancelado'}
                        </Badge>
                      </div>
                      <select
                        className="text-sm border border-slate-300 rounded-lg px-3 py-2 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/30"
                        value={o.status}
                        onChange={(e) => updateOrderStatus(o.id, e.target.value as any)}
                      >
                        {['pendente', 'confirmado', 'concluido', 'cancelado'].map((s) => (
                          <option key={s} value={s}>
                            {s === 'pendente' ? 'Pendente' : s === 'confirmado' ? 'Confirmado' : s === 'concluido' ? 'Concluído' : 'Cancelado'}
                          </option>
                        ))}
                      </select>
                    </div>
                    <p className="text-sm text-slate-600 mb-2">{new Date(o.createdAt).toLocaleString('pt-BR')}</p>
                    <div className="space-y-1">
                      {productItems.map((item) => {
                        const prod = shop.products.find((p) => p.id === item.refId);
                        return (
                          <div key={item.refId} className="flex items-center justify-between text-sm bg-slate-50 rounded px-2 py-1">
                            <span className="text-slate-700">{prod?.name ?? 'Produto'} x{item.qty}</span>
                            <span className="text-indigo-600 font-semibold">{currency((prod?.price ?? 0) * item.qty)}</span>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                );
              })
            ) : (
              <div className="text-center py-12">
                <ShoppingBag size={48} className="mx-auto text-slate-300 mb-3" />
                <p className="text-slate-600 font-medium">Nenhum pedido de produtos no período</p>
                <p className="text-sm text-slate-500 mt-1">Apenas pedidos com produtos aparecem aqui</p>
              </div>
            )}
          </div>
        </Card>
      )}

      {activeTab === 'services' && (
        <div className="space-y-6">
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-bold text-slate-900">Serviços</h2>
              <Badge color="slate" variant="soft">{shop.services.length} serviços</Badge>
            </div>
            <div className="space-y-3 mb-6">
              {shop.services.map((s) => (
                <div key={s.id} className="flex items-center justify-between p-4 border border-slate-200 rounded-lg">
                  <div className="flex-1">
                    <p className="font-bold text-slate-900">{s.name}</p>
                    <p className="text-sm text-slate-600">Duração: {s.duration} min</p>
                  </div>
                  <div className="flex items-center gap-4">
                    <span className="text-lg font-bold text-indigo-600">{currency(s.price)}</span>
                    <Button variant="danger" size="sm" onClick={() => deleteService(shop.id, s.id)}>
                      <Trash2 size={16} />
                    </Button>
                  </div>
                </div>
              ))}
            </div>
            <div className="border-t border-slate-200 pt-4">
              <h3 className="text-base font-semibold text-slate-900 mb-3">Adicionar novo serviço</h3>
              <div className="grid md:grid-cols-4 gap-3">
                <Input label="Nome" placeholder="Ex: Corte Fade" value={svcName} onChange={(e) => setSvcName(e.target.value)} />
                <Input label="Preço" type="number" placeholder="50" value={svcPrice} onChange={(e) => setSvcPrice(Number(e.target.value))} />
                <Input label="Duração (min)" type="number" placeholder="30" value={svcDuration} onChange={(e) => setSvcDuration(Number(e.target.value))} />
                <div className="flex items-end">
                  <Button onClick={addNewService} className="w-full">
                    <PlusIcon size={16} className="mr-2" />
                    Adicionar
                  </Button>
                </div>
              </div>
            </div>
          </Card>
        </div>
      )}

      {activeTab === 'products' && (
        <div className="space-y-6">
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-bold text-slate-900">Produtos</h2>
              <Badge color="slate" variant="soft">{shop.products.length} produtos</Badge>
            </div>
            {lowStock.length > 0 && (
              <div className="mb-4 p-3 bg-indigo-50 border border-indigo-200 rounded-lg">
                <p className="text-sm font-semibold text-indigo-800 flex items-center gap-2">
                  <AlertTriangle size={16} />
                  Atenção: {lowStock.length} {lowStock.length === 1 ? 'produto com stock baixo' : 'produtos com stock baixo'}
                </p>
              </div>
            )}
            <div className="space-y-3 mb-6">
              {shop.products.map((p) => (
                <div
                  key={p.id}
                  className={`flex items-center justify-between p-4 border rounded-lg ${p.stock <= 3 ? 'border-indigo-300 bg-indigo-50' : 'border-slate-200'
                    }`}
                >
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-1">
                      <p className="font-bold text-slate-900">{p.name}</p>
                      {p.stock <= 3 && <Badge color="indigo" variant="solid">Stock baixo</Badge>}
                    </div>
                    <p className="text-sm text-slate-600">Stock: {p.stock} unidades</p>
                  </div>
                  <div className="flex items-center gap-4">
                    <span className="text-lg font-bold text-indigo-600">{currency(p.price)}</span>
                    <div className="flex items-center gap-2">
                      <Button variant="outline" size="sm" onClick={() => updateProductStock(p, -1)}>
                        <Minus size={14} />
                      </Button>
                      <Button variant="outline" size="sm" onClick={() => updateProductStock(p, 1)}>
                        <Plus size={14} />
                      </Button>
                      <Button variant="danger" size="sm" onClick={() => deleteProduct(shop.id, p.id)}>
                        <Trash2 size={16} />
                      </Button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
            <div className="border-t border-slate-200 pt-4">
              <h3 className="text-base font-semibold text-slate-900 mb-3">Adicionar novo produto</h3>
              <div className="grid md:grid-cols-4 gap-3">
                <Input label="Nome" placeholder="Ex: Pomada" value={prodName} onChange={(e) => setProdName(e.target.value)} />
                <Input label="Preço" type="number" placeholder="30" value={prodPrice} onChange={(e) => setProdPrice(Number(e.target.value))} />
                <Input label="Stock inicial" type="number" placeholder="10" value={prodStock} onChange={(e) => setProdStock(Number(e.target.value))} />
                <div className="flex items-end">
                  <Button onClick={addNewProduct} className="w-full">
                    <PlusIcon size={16} className="mr-2" />
                    Adicionar
                  </Button>
                </div>
              </div>
            </div>
          </Card>
        </div>
      )}

      {activeTab === 'barbers' && (
        <div className="space-y-6">
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <h2 className="text-2xl font-bold text-slate-900">Profissionais</h2>
          </div>

          {/* Barra de Pesquisa Estilo Screenshot */}
          <div className="relative group">
            <div className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 group-focus-within:text-indigo-500 transition-colors">
              <Search size={20} />
            </div>
            <input
              type="text"
              placeholder="Pesquisar"
              value={barberSearchQuery}
              onChange={(e) => setBarberSearchQuery(e.target.value)}
              className="w-full h-14 pl-12 pr-4 bg-[#0d0d0d] border border-white/5 rounded-xl text-white placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500/20 transition-all font-medium"
            />
          </div>

          {/* Grelha de Profissionais */}
          <div className="grid md:grid-cols-2 gap-4">
            {shop.barbers
              .filter(b => b.name.toLowerCase().includes(barberSearchQuery.toLowerCase()))
              .map((b) => (
                <div key={b.id} className="group relative flex items-center gap-4 p-4 bg-[#0d0d0d] border border-white/5 rounded-[2rem] hover:border-indigo-500/30 transition-all duration-300 shadow-xl">
                  {/* Avatar squircle robusto */}
                  <div className="relative">
                    <div className="w-24 h-24 rounded-[1.5rem] overflow-hidden border-2 border-white/5 bg-slate-900 flex items-center justify-center transition-transform group-hover:scale-105 duration-500">
                      {b.imageUrl ? (
                        <img src={b.imageUrl} alt={b.name} className="w-full h-full object-cover" />
                      ) : (
                        <Users size={32} className="text-slate-700" />
                      )}
                    </div>
                    
                    {/* Botão de Upload Escondido */}
                    <input
                      type="file"
                      id={`barber-img-${b.id}`}
                      className="hidden"
                      accept="image/*"
                      onChange={(e) => handleBarberImageUpload(b.id, e)}
                    />
                    <label
                      htmlFor={`barber-img-${b.id}`}
                      className="absolute inset-0 bg-black/40 text-white flex items-center justify-center rounded-[1.5rem] opacity-0 group-hover:opacity-100 cursor-pointer transition-opacity"
                    >
                      {uploadingBarberId === b.id ? <RefreshCw size={20} className="animate-spin" /> : <Plus size={20} />}
                    </label>
                  </div>

                  {/* Info Profissional */}
                  <div className="flex-1">
                    <h3 className="text-xl font-bold text-white tracking-tight leading-tight">{b.name}</h3>
                    {/* O utilizador pediu para ignorar observações/especialidades, removido para o look "mais limpo" do screenshot */}
                  </div>

                  {/* Ações Rápidas */}
                  <div className="flex flex-col gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                    <Button 
                      variant="danger" 
                      size="sm" 
                      className="rounded-xl h-10 w-10 p-0 flex items-center justify-center bg-transparent border-white/10 hover:bg-red-500/20"
                      onClick={() => deleteBarber(shop.id, b.id)}
                    >
                      <Trash2 size={16} />
                    </Button>
                  </div>
                </div>
              ))}
            
            {shop.barbers.filter(b => b.name.toLowerCase().includes(barberSearchQuery.toLowerCase())).length === 0 && (
              <div className="col-span-full py-12 text-center bg-[#0d0d0d] border border-white/5 rounded-[2rem]">
                <Users size={48} className="mx-auto text-slate-800 mb-3" />
                <p className="text-slate-500 font-medium italic">Nenhum profissional encontrado com esse nome.</p>
              </div>
            )}
          </div>

          {/* Formulário de Adição (Mantido mas modernizado) */}
          <div className="pt-8 mt-4 border-t border-slate-200">
            <h3 className="text-base font-semibold text-slate-900 mb-4">Novo Profissional</h3>
            <div className="grid md:grid-cols-3 gap-3">
              <div className="md:col-span-2">
                <Input
                  label="Nome do Profissional"
                  placeholder="Ex: João Silva"
                  value={barberName}
                  onChange={(e) => setBarberName(e.target.value)}
                />
              </div>
              <div className="flex items-end">
                <Button onClick={addNewBarber} className="w-full bg-indigo-600 hover:bg-indigo-700 h-11">
                  <PlusIcon size={16} className="mr-2" />
                  Adicionar
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}

      {activeTab === 'settings' && (
        <div className="space-y-6">
          <Card className="p-6">
            <h2 className="text-lg font-bold text-slate-900 mb-6">Definições da Barbearia</h2>

            <div className="space-y-6 max-w-2xl">
              <div>
                <h3 className="text-sm font-semibold text-slate-900 mb-2">Foto de Capa</h3>
                <p className="text-sm text-slate-500 mb-4">
                  Esta foto será exibida na página de detalhes da sua barbearia para todos os clientes.
                </p>

                <div className="flex flex-col gap-4">
                  {shop.imageUrl ? (
                    <div className="relative h-48 w-full md:w-96 rounded-lg overflow-hidden border border-slate-200">
                      <img
                        src={shop.imageUrl}
                        alt="Capa da Barbearia"
                        className="w-full h-full object-cover"
                      />
                    </div>
                  ) : (
                    <div className="h-48 w-full md:w-96 rounded-lg border-2 border-dashed border-slate-300 bg-slate-50 flex flex-col items-center justify-center text-slate-500">
                      <Globe size={32} className="mb-2 text-slate-400" />
                      <p className="text-sm font-medium">Sem foto de capa</p>
                    </div>
                  )}

                  <div>
                    <input
                      type="file"
                      id="cover-upload"
                      className="hidden"
                      accept="image/png, image/jpeg, image/webp"
                      onChange={handleImageUpload}
                      disabled={isUploading}
                    />
                    <label
                      htmlFor="cover-upload"
                      className={`inline-flex items-center justify-center rounded-lg bg-indigo-600 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 cursor-pointer transition-colors ${isUploading ? 'opacity-50 cursor-not-allowed' : ''}`}
                    >
                      {isUploading ? (
                        <div className="flex items-center gap-2">
                          <RefreshCw size={16} className="animate-spin" />
                          <span>A carregar...</span>
                        </div>
                      ) : (
                        <div className="flex items-center gap-2">
                          <Store size={16} />
                          <span>{shop.imageUrl ? 'Alterar Foto' : 'Carregar Foto'}</span>
                        </div>
                      )}
                    </label>
                  </div>
                </div>
              </div>

              <div className="pt-6 border-t border-slate-200">
                <h3 className="text-sm font-semibold text-slate-900 mb-4">Informações da Barbearia</h3>
                <div className="space-y-4">
                  <Input
                    label="Nome da Barbearia"
                    value={editShopName}
                    onChange={(e) => setEditShopName(e.target.value)}
                    placeholder="O nome da sua barbearia"
                  />
                  <Input
                    label="Morada Completa"
                    value={editShopAddress}
                    onChange={(e) => setEditShopAddress(e.target.value)}
                    placeholder="Rua, Número, Código Postal, Localidade"
                  />

                  <div className="pt-4 border-t border-slate-200">
                    <h3 className="text-sm font-semibold text-slate-900 mb-4">Contactos e Redes Sociais</h3>
                    <div className="grid md:grid-cols-2 gap-4">
                      <Input
                        label="Telefone Principal"
                        type="tel"
                        maxLength={9}
                        value={editContacts.phone1 || ''}
                        onChange={(e) => {
                          const val = e.target.value.replace(/\D/g, '').slice(0, 9);
                          setEditContacts({ ...editContacts, phone1: val });
                        }}
                        placeholder="Ex: 910000000"
                      />
                      <Input
                        label="Telefone Secundário"
                        type="tel"
                        maxLength={9}
                        value={editContacts.phone2 || ''}
                        onChange={(e) => {
                          const val = e.target.value.replace(/\D/g, '').slice(0, 9);
                          setEditContacts({ ...editContacts, phone2: val });
                        }}
                        placeholder="Ex: 252000000"
                      />
                      <Input
                        label="Link do WhatsApp"
                        value={editSocials.whatsapp || ''}
                        onChange={(e) => setEditSocials({ ...editSocials, whatsapp: e.target.value })}
                        placeholder="https://wa.me/351910000000"
                      />
                      <Input
                        label="Link do Instagram"
                        value={editSocials.instagram || ''}
                        onChange={(e) => setEditSocials({ ...editSocials, instagram: e.target.value })}
                        placeholder="https://instagram.com/suabarbearia"
                      />
                      <Input
                        label="Link do Facebook"
                        value={editSocials.facebook || ''}
                        onChange={(e) => setEditSocials({ ...editSocials, facebook: e.target.value })}
                        placeholder="https://facebook.com/suabarbearia"
                      />
                    </div>
                  </div>

                  <div className="pt-4 border-t border-slate-200">
                    <h3 className="text-sm font-semibold text-slate-900 mb-4">Horário de Atendimento</h3>
                    <div className="space-y-3">
                      {editSchedule.map((slot, idx) => (
                        <div key={idx} className="flex items-center gap-3">
                          <div className="w-32">
                            <span className={`text-sm font-medium ${slot.closed ? 'text-slate-400' : 'text-slate-700'}`}>{slot.day}</span>
                          </div>
                          {!slot.closed ? (
                            <>
                              <Input
                                type="time"
                                value={slot.open}
                                onChange={(e) => {
                                  const newSchedule = [...editSchedule];
                                  newSchedule[idx].open = e.target.value;
                                  setEditSchedule(newSchedule);
                                }}
                                className="w-28"
                              />
                              <span className="text-slate-400">-</span>
                              <Input
                                type="time"
                                value={slot.close}
                                onChange={(e) => {
                                  const newSchedule = [...editSchedule];
                                  newSchedule[idx].close = e.target.value;
                                  setEditSchedule(newSchedule);
                                }}
                                className="w-28"
                              />
                            </>
                          ) : (
                            <div className="flex-1 text-sm text-slate-400 italic">Fechado</div>
                          )}
                          <Button
                            variant="outline"
                            size="sm"
                            className="ml-auto"
                            onClick={() => {
                              const newSchedule = [...editSchedule];
                              newSchedule[idx].closed = !newSchedule[idx].closed;
                              setEditSchedule(newSchedule);
                            }}
                          >
                            {slot.closed ? 'Abrir' : 'Fechar'}
                          </Button>
                        </div>
                      ))}
                    </div>
                  </div>

                  <div className="pt-4 border-t border-slate-200 mb-6">
                    <h3 className="text-sm font-semibold text-slate-900 mb-4">Formas de Pagamento</h3>
                    <Input
                      label="Métodos aceites (separados por vírgula)"
                      value={editPaymentMethods}
                      onChange={(e) => setEditPaymentMethods(e.target.value)}
                      placeholder="Ex: Dinheiro, Cartão de Crédito, MBWay"
                    />
                  </div>

                  <div className="pt-2 flex items-center gap-4">
                    <Button
                      onClick={handleSaveSettings}
                      disabled={isSavingSettings}
                      className="bg-indigo-600 hover:bg-indigo-700 w-full sm:w-auto"
                    >
                      {isSavingSettings ? 'A Guardar...' : 'Guardar Alterações'}
                    </Button>

                    {showSaveSuccess && (
                      <span className="text-sm font-medium text-emerald-600 flex items-center gap-1 animate-in fade-in duration-300">
                        <CheckCircle2 size={16} />
                        Guardado com sucesso!
                      </span>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </Card>
        </div>
      )}
    </div>
  );
}
