'use client';
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { AppLayout } from '@/components/layout/app-layout';
import { ClientCard } from '@/components/clients/client-card';
import { ClientModal } from '@/components/clients/client-modal';
import api from '@/lib/api';
import { Search, Plus, UserPlus } from 'lucide-react';
import { useDebounce } from '@/hooks/useDebounce';

export default function ClientsPage() {
  const [search, setSearch] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [editingClient, setEditingClient] = useState<any>(null);
  const debouncedSearch = useDebounce(search, 300);

  const { data, isLoading, refetch } = useQuery({
    queryKey: ['clients', debouncedSearch],
    queryFn: async () => {
      const { data } = await api.get('/clients', { params: { search: debouncedSearch, limit: 50 } });
      return data;
    },
  });

  const handleEdit = (client: any) => {
    setEditingClient(client);
    setShowModal(true);
  };

  const handleClose = () => {
    setShowModal(false);
    setEditingClient(null);
    refetch();
  };

  return (
    <AppLayout title="Clientes">
      <div className="space-y-4">
        <div className="flex items-center gap-3">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="search"
              placeholder="Buscar por nome, telefone ou email..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none"
            />
          </div>
          <button
            onClick={() => setShowModal(true)}
            className="flex items-center gap-2 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2.5 rounded-lg text-sm font-medium transition-colors whitespace-nowrap"
          >
            <Plus className="w-4 h-4" />
            <span className="hidden sm:inline">Novo Cliente</span>
          </button>
        </div>

        {isLoading && (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {[...Array(6)].map((_, i) => <div key={i} className="bg-white rounded-xl h-40 animate-pulse" />)}
          </div>
        )}

        {!isLoading && data?.data?.length === 0 && (
          <div className="text-center py-16">
            <UserPlus className="w-12 h-12 text-gray-300 mx-auto mb-4" />
            <p className="text-gray-500 font-medium">Nenhum cliente encontrado</p>
            <p className="text-gray-400 text-sm mt-1">Adicione seu primeiro cliente</p>
            <button
              onClick={() => setShowModal(true)}
              className="mt-4 bg-blue-600 text-white px-4 py-2 rounded-lg text-sm"
            >
              Adicionar cliente
            </button>
          </div>
        )}

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {data?.data?.map((client: any) => (
            <ClientCard key={client.id} client={client} onEdit={handleEdit} />
          ))}
        </div>

        <div className="text-sm text-gray-500 text-center">
          {data?.total} cliente{data?.total !== 1 ? 's' : ''} encontrado{data?.total !== 1 ? 's' : ''}
        </div>
      </div>

      {showModal && (
        <ClientModal client={editingClient} onClose={handleClose} />
      )}
    </AppLayout>
  );
}
