'use client';
import { useState, useRef } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useQuery, useMutation } from '@tanstack/react-query';
import { AppLayout } from '@/components/layout/app-layout';
import { SignatureCanvas } from '@/components/orders/signature-canvas';
import api from '@/lib/api';
import { ArrowLeft, CheckCircle, Phone, MessageCircle } from 'lucide-react';
import Link from 'next/link';
import { formatDate, formatCurrency, buildWhatsappUrl } from '@/lib/utils';

export default function OrderDetailPage() {
  const { id } = useParams<{ id: string }>();
  const router = useRouter();
  const [showCompleteModal, setShowCompleteModal] = useState(false);
  const [recurrence, setRecurrence] = useState(6);
  const [signature, setSignature] = useState('');

  const { data: order, refetch } = useQuery({
    queryKey: ['orders', id],
    queryFn: async () => {
      const { data } = await api.get(`/orders/${id}`);
      return data;
    },
  });

  const complete = useMutation({
    mutationFn: () => api.patch(`/orders/${id}/complete`, {
      clientSignature: signature,
      recurrenceMonths: recurrence,
    }),
    onSuccess: () => { refetch(); setShowCompleteModal(false); },
  });

  if (!order) return <AppLayout title="OS"><div className="animate-pulse h-64 bg-white rounded-xl" /></AppLayout>;

  return (
    <AppLayout title={`OS #${order.number}`}>
      <div className="max-w-2xl mx-auto space-y-4">
        <Link href="/orders" className="flex items-center gap-2 text-gray-500 hover:text-gray-700 text-sm">
          <ArrowLeft className="w-4 h-4" />
          Voltar
        </Link>

        <div className="bg-white rounded-xl border border-gray-200 p-5 space-y-4">
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold">OS #{order.number}</h2>
            <span className={`px-3 py-1 rounded-full text-sm font-medium ${
              order.status === 'DONE' ? 'bg-green-100 text-green-700' :
              order.status === 'IN_PROGRESS' ? 'bg-amber-100 text-amber-700' :
              'bg-blue-100 text-blue-700'
            }`}>
              {order.status === 'DONE' ? 'Concluída' : order.status === 'IN_PROGRESS' ? 'Em andamento' : 'Aberta'}
            </span>
          </div>

          <div className="grid grid-cols-2 gap-4 text-sm">
            <div>
              <p className="text-gray-500">Cliente</p>
              <p className="font-medium">{order.client?.name}</p>
            </div>
            <div>
              <p className="text-gray-500">Tipo de Serviço</p>
              <p className="font-medium">{order.serviceType}</p>
            </div>
            <div>
              <p className="text-gray-500">Criada em</p>
              <p className="font-medium">{formatDate(order.createdAt)}</p>
            </div>
            {order.value && (
              <div>
                <p className="text-gray-500">Valor</p>
                <p className="font-medium text-green-600">{formatCurrency(Number(order.value))}</p>
              </div>
            )}
          </div>

          <div>
            <p className="text-sm text-gray-500 mb-1">Descrição</p>
            <p className="text-sm">{order.description}</p>
          </div>

          {order.notes && (
            <div>
              <p className="text-sm text-gray-500 mb-1">Observações</p>
              <p className="text-sm">{order.notes}</p>
            </div>
          )}

          {order.client && (
            <div className="flex gap-2 pt-2">
              <a href={`tel:${order.client.phone}`} className="flex items-center gap-1.5 text-xs bg-gray-100 hover:bg-gray-200 px-3 py-2 rounded-lg text-gray-700 font-medium">
                <Phone className="w-3.5 h-3.5" />
                Ligar
              </a>
              <a
                href={buildWhatsappUrl(order.client.whatsapp || order.client.phone, order.client.name)}
                target="_blank"
                rel="noopener noreferrer"
                className="flex items-center gap-1.5 text-xs bg-green-100 hover:bg-green-200 px-3 py-2 rounded-lg text-green-700 font-medium"
              >
                <MessageCircle className="w-3.5 h-3.5" />
                WhatsApp
              </a>
            </div>
          )}

          {order.status !== 'DONE' && order.status !== 'CANCELLED' && (
            <button
              onClick={() => setShowCompleteModal(true)}
              className="w-full flex items-center justify-center gap-2 bg-green-600 hover:bg-green-700 text-white px-4 py-3 rounded-lg font-medium transition-colors"
            >
              <CheckCircle className="w-5 h-5" />
              Concluir OS
            </button>
          )}

          {order.clientSignature && (
            <div>
              <p className="text-sm text-gray-500 mb-2">Assinatura do Cliente</p>
              <img src={order.clientSignature} alt="Assinatura" className="border rounded-lg max-h-24" />
            </div>
          )}
        </div>
      </div>

      {showCompleteModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl w-full max-w-md p-5 space-y-4">
            <h3 className="text-lg font-semibold">Concluir Ordem de Serviço</h3>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Agendar próxima manutenção em:
              </label>
              <div className="flex gap-2">
                {[3, 6, 12].map((m) => (
                  <button
                    key={m}
                    type="button"
                    onClick={() => setRecurrence(m)}
                    className={`flex-1 py-2 rounded-lg text-sm font-medium border transition-colors ${
                      recurrence === m ? 'bg-blue-600 text-white border-blue-600' : 'border-gray-300 hover:bg-gray-50'
                    }`}
                  >
                    {m} meses
                  </button>
                ))}
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Assinatura do Cliente</label>
              <SignatureCanvas onSave={setSignature} />
            </div>

            <div className="flex gap-3">
              <button onClick={() => setShowCompleteModal(false)} className="flex-1 px-4 py-2.5 border rounded-lg text-sm">
                Cancelar
              </button>
              <button
                onClick={() => complete.mutate()}
                disabled={complete.isPending}
                className="flex-1 bg-green-600 hover:bg-green-700 text-white px-4 py-2.5 rounded-lg text-sm font-medium disabled:opacity-60"
              >
                {complete.isPending ? 'Salvando...' : 'Confirmar'}
              </button>
            </div>
          </div>
        </div>
      )}
    </AppLayout>
  );
}
