'use client';
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { AppLayout } from '@/components/layout/app-layout';
import { OrderCard } from '@/components/orders/order-card';
import api from '@/lib/api';
import { Search, Plus } from 'lucide-react';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';

const STATUS_TABS = [
  { value: '', label: 'Todas' },
  { value: 'OPEN', label: 'Abertas' },
  { value: 'IN_PROGRESS', label: 'Em andamento' },
  { value: 'DONE', label: 'Concluídas' },
];

export default function OrdersPage() {
  const searchParams = useSearchParams();
  const [search, setSearch] = useState('');
  const [status, setStatus] = useState('');
  const clientId = searchParams.get('clientId') || undefined;

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

  return (
    <AppLayout title="Ordens de Serviço">
      <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 OS por cliente, descrição..."
              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 outline-none"
            />
          </div>
          <Link
            href="/orders/new"
            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">Nova OS</span>
          </Link>
        </div>

        <div className="flex gap-2 overflow-x-auto pb-1">
          {STATUS_TABS.map((tab) => (
            <button
              key={tab.value}
              onClick={() => setStatus(tab.value)}
              className={`px-3 py-1.5 rounded-lg text-sm font-medium whitespace-nowrap transition-colors ${
                status === tab.value
                  ? 'bg-blue-600 text-white'
                  : 'bg-white text-gray-600 hover:bg-gray-100 border border-gray-200'
              }`}
            >
              {tab.label}
            </button>
          ))}
        </div>

        {isLoading && (
          <div className="space-y-3">
            {[...Array(5)].map((_, i) => <div key={i} className="bg-white rounded-xl h-28 animate-pulse" />)}
          </div>
        )}

        <div className="space-y-3">
          {data?.data?.map((order: any) => (
            <OrderCard key={order.id} order={order} onUpdate={refetch} />
          ))}
        </div>

        {!isLoading && data?.data?.length === 0 && (
          <div className="text-center py-12 text-gray-400">
            Nenhuma ordem de serviço encontrada
          </div>
        )}
      </div>
    </AppLayout>
  );
}
