'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useQuery, useMutation } from '@tanstack/react-query';
import { AppLayout } from '@/components/layout/app-layout';
import api from '@/lib/api';
import { ArrowLeft } from 'lucide-react';
import Link from 'next/link';

const schema = z.object({
  clientId: z.string().uuid('Selecione um cliente'),
  description: z.string().min(5, 'Descreva o serviço'),
  serviceType: z.string().min(2, 'Tipo obrigatório'),
  priority: z.enum(['LOW', 'NORMAL', 'HIGH', 'URGENT']).default('NORMAL'),
  scheduledAt: z.string().optional(),
  value: z.coerce.number().optional(),
  notes: z.string().optional(),
});

type FormData = z.infer<typeof schema>;

const SERVICE_TYPES = [
  'Manutenção Preventiva', 'Manutenção Corretiva', 'Instalação', 'Limpeza',
  'Recarga de Gás', 'Troca de Peças', 'Diagnóstico', 'Outro',
];

export default function NewOrderPage() {
  const router = useRouter();
  const [clientSearch, setClientSearch] = useState('');

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

  const { register, handleSubmit, formState: { errors } } = useForm<FormData>({
    resolver: zodResolver(schema),
    defaultValues: { priority: 'NORMAL' },
  });

  const mutation = useMutation({
    mutationFn: (data: FormData) => api.post('/orders', data),
    onSuccess: (res) => router.push(`/orders/${res.data.id}`),
  });

  return (
    <AppLayout title="Nova Ordem de Serviço">
      <div className="max-w-2xl mx-auto">
        <Link href="/orders" className="flex items-center gap-2 text-gray-500 hover:text-gray-700 mb-6 text-sm">
          <ArrowLeft className="w-4 h-4" />
          Voltar para OS
        </Link>

        <div className="bg-white rounded-xl border border-gray-200 p-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-5">Detalhes da Ordem</h2>

          <form onSubmit={handleSubmit((d) => mutation.mutate(d))} className="space-y-5">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Cliente *</label>
              <input
                placeholder="Buscar cliente..."
                value={clientSearch}
                onChange={(e) => setClientSearch(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 outline-none mb-2"
              />
              <select
                {...register('clientId')}
                size={3}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 outline-none"
              >
                <option value="">-- Selecione --</option>
                {clients?.map((c: any) => <option key={c.id} value={c.id}>{c.name} - {c.phone}</option>)}
              </select>
              {errors.clientId && <p className="text-red-500 text-xs mt-1">{errors.clientId.message}</p>}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Tipo de Serviço *</label>
              <select
                {...register('serviceType')}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 outline-none"
              >
                <option value="">-- Selecione --</option>
                {SERVICE_TYPES.map((t) => <option key={t} value={t}>{t}</option>)}
              </select>
              {errors.serviceType && <p className="text-red-500 text-xs mt-1">{errors.serviceType.message}</p>}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Descrição *</label>
              <textarea
                {...register('description')}
                rows={3}
                placeholder="Descreva o problema ou serviço a realizar..."
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 outline-none resize-none"
              />
              {errors.description && <p className="text-red-500 text-xs mt-1">{errors.description.message}</p>}
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Prioridade</label>
                <select
                  {...register('priority')}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 outline-none"
                >
                  <option value="LOW">Baixa</option>
                  <option value="NORMAL">Normal</option>
                  <option value="HIGH">Alta</option>
                  <option value="URGENT">Urgente</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Valor (R$)</label>
                <input
                  {...register('value')}
                  type="number"
                  step="0.01"
                  placeholder="0,00"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 outline-none"
                />
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Data Agendada</label>
              <input
                {...register('scheduledAt')}
                type="datetime-local"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 outline-none"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Observações</label>
              <textarea
                {...register('notes')}
                rows={2}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 outline-none resize-none"
              />
            </div>

            {mutation.isError && (
              <div className="text-red-600 text-sm bg-red-50 p-3 rounded-lg">Erro ao criar OS. Tente novamente.</div>
            )}

            <div className="flex gap-3 pt-2">
              <Link href="/orders" className="flex-1 text-center px-4 py-2.5 border border-gray-300 rounded-lg text-sm font-medium hover:bg-gray-50">
                Cancelar
              </Link>
              <button
                type="submit"
                disabled={mutation.isPending}
                className="flex-1 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2.5 rounded-lg text-sm font-medium disabled:opacity-60"
              >
                {mutation.isPending ? 'Criando...' : 'Criar OS'}
              </button>
            </div>
          </form>
        </div>
      </div>
    </AppLayout>
  );
}
