'use client';
import { useQuery } from '@tanstack/react-query';
import { AppLayout } from '@/components/layout/app-layout';
import { StatCard } from '@/components/dashboard/stat-card';
import { ClientAlertList } from '@/components/dashboard/client-alert-list';
import { RevenueChart } from '@/components/dashboard/revenue-chart';
import api from '@/lib/api';
import { Users, ClipboardList, CheckCircle, AlertTriangle, DollarSign, Clock } from 'lucide-react';
import { formatCurrency } from '@/lib/utils';

export default function DashboardPage() {
  const { data, isLoading } = useQuery({
    queryKey: ['dashboard'],
    queryFn: async () => {
      const { data } = await api.get('/dashboard');
      return data;
    },
    refetchInterval: 30000,
  });

  const { data: revenue } = useQuery({
    queryKey: ['dashboard', 'revenue'],
    queryFn: async () => {
      const { data } = await api.get('/dashboard/revenue');
      return data;
    },
  });

  if (isLoading) {
    return (
      <AppLayout title="Dashboard">
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
          {[...Array(6)].map((_, i) => (
            <div key={i} className="bg-white rounded-xl p-5 animate-pulse h-28" />
          ))}
        </div>
      </AppLayout>
    );
  }

  const stats = data?.stats || {};

  return (
    <AppLayout title="Dashboard">
      <div className="space-y-6">
        {stats.overdueReminders > 0 && (
          <div className="bg-red-50 border border-red-200 rounded-xl p-4 flex items-center gap-3">
            <AlertTriangle className="w-5 h-5 text-red-600 flex-shrink-0" />
            <p className="text-red-700 font-medium text-sm">
              Atenção: você tem <strong>{stats.overdueReminders}</strong>{' '}
              {stats.overdueReminders === 1 ? 'cliente com manutenção atrasada' : 'clientes com manutenção atrasada'}.{' '}
              <a href="/reminders" className="underline">Ver lembretes</a>
            </p>
          </div>
        )}

        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
          <StatCard label="Total de Clientes" value={stats.totalClients} icon={Users} color="blue" />
          <StatCard label="OS Abertas" value={stats.openOrders} icon={ClipboardList} color="amber" />
          <StatCard label="OS Concluídas" value={stats.doneOrders} icon={CheckCircle} color="green" />
          <StatCard label="Manutenções Vencidas" value={stats.overdueReminders} icon={AlertTriangle} color="red" />
          <StatCard label="Para Hoje" value={stats.todayReminders} icon={Clock} color="purple" />
          <StatCard
            label="Faturamento Mensal"
            value={formatCurrency(stats.revenueThisMonth || 0)}
            icon={DollarSign}
            color="emerald"
            isText
          />
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <div className="lg:col-span-2">
            <RevenueChart data={revenue || []} />
          </div>
          <div>
            <ClientAlertList
              overdueClients={data?.overdueClients || []}
              todayClients={data?.todayClients || []}
            />
          </div>
        </div>
      </div>
    </AppLayout>
  );
}
