'use client';
import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { AppLayout } from '@/components/layout/app-layout';
import api from '@/lib/api';
import { formatDate, buildWhatsappUrl } from '@/lib/utils';
import { CheckCircle, MessageCircle, Phone, Calendar } from 'lucide-react';

const TABS = [
  { value: 'overdue', label: 'Vencidos', color: 'text-red-600 border-red-500' },
  { value: 'today', label: 'Hoje', color: 'text-amber-600 border-amber-500' },
  { value: 'all', label: 'Todos', color: 'text-blue-600 border-blue-500' },
];

export default function RemindersPage() {
  const [tab, setTab] = useState('overdue');
  const qc = useQueryClient();

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

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

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

  const markDone = useMutation({
    mutationFn: (id: string) => api.patch(`/reminders/${id}/done`),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ['reminders'] }); qc.invalidateQueries({ queryKey: ['dashboard'] }); },
  });

  const items = tab === 'overdue' ? overdue : tab === 'today' ? today : all;

  return (
    <AppLayout title="Lembretes de Manutenção">
      <div className="space-y-4">
        <div className="flex gap-1 bg-gray-100 p-1 rounded-xl w-fit">
          {TABS.map((t) => (
            <button
              key={t.value}
              onClick={() => setTab(t.value)}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                tab === t.value ? 'bg-white shadow-sm text-gray-900' : 'text-gray-500 hover:text-gray-700'
              }`}
            >
              {t.label}
              {t.value === 'overdue' && overdue?.length > 0 && (
                <span className="ml-1.5 bg-red-500 text-white text-xs px-1.5 py-0.5 rounded-full">
                  {overdue.length}
                </span>
              )}
              {t.value === 'today' && today?.length > 0 && (
                <span className="ml-1.5 bg-amber-500 text-white text-xs px-1.5 py-0.5 rounded-full">
                  {today.length}
                </span>
              )}
            </button>
          ))}
        </div>

        {!items?.length && (
          <div className="text-center py-16">
            <Calendar className="w-12 h-12 text-gray-200 mx-auto mb-3" />
            <p className="text-gray-500">Nenhum lembrete {tab === 'overdue' ? 'vencido' : tab === 'today' ? 'para hoje' : ''}</p>
          </div>
        )}

        <div className="space-y-3">
          {items?.map((reminder: any) => (
            <div
              key={reminder.id}
              className={`bg-white rounded-xl border p-4 ${
                reminder.status === 'OVERDUE' ? 'border-red-200 bg-red-50/30' :
                reminder.status === 'PENDING' ? 'border-amber-200 bg-amber-50/30' : 'border-gray-200'
              }`}
            >
              <div className="flex items-start justify-between gap-3">
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-1">
                    <h3 className="font-semibold text-gray-900">{reminder.client?.name}</h3>
                    <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${
                      reminder.status === 'OVERDUE' ? 'bg-red-100 text-red-700' :
                      reminder.status === 'PENDING' ? 'bg-amber-100 text-amber-700' : 'bg-green-100 text-green-700'
                    }`}>
                      {reminder.status === 'OVERDUE' ? 'Vencido' : reminder.status === 'PENDING' ? 'Pendente' : 'Concluído'}
                    </span>
                  </div>
                  <p className="text-sm text-gray-600">
                    Próxima manutenção: <strong>{formatDate(reminder.nextMaintenanceDate)}</strong>
                  </p>
                  {reminder.order && (
                    <p className="text-xs text-gray-400 mt-0.5">Ref: OS #{reminder.order.number} — {reminder.order.serviceType}</p>
                  )}
                  <p className="text-xs text-gray-400 mt-0.5">Recorrência: a cada {reminder.recurrenceMonths} meses</p>
                </div>

                <div className="flex flex-col gap-1.5">
                  <a
                    href={buildWhatsappUrl(reminder.client?.whatsapp || reminder.client?.phone, reminder.client?.name)}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center gap-1 text-xs bg-green-100 hover:bg-green-200 text-green-700 px-2.5 py-1.5 rounded-lg font-medium transition-colors whitespace-nowrap"
                  >
                    <MessageCircle className="w-3.5 h-3.5" />
                    WhatsApp
                  </a>
                  <a
                    href={`tel:${reminder.client?.phone}`}
                    className="flex items-center gap-1 text-xs bg-gray-100 hover:bg-gray-200 text-gray-700 px-2.5 py-1.5 rounded-lg font-medium transition-colors"
                  >
                    <Phone className="w-3.5 h-3.5" />
                    Ligar
                  </a>
                  {reminder.status !== 'DONE' && (
                    <button
                      onClick={() => markDone.mutate(reminder.id)}
                      className="flex items-center gap-1 text-xs bg-blue-100 hover:bg-blue-200 text-blue-700 px-2.5 py-1.5 rounded-lg font-medium transition-colors"
                    >
                      <CheckCircle className="w-3.5 h-3.5" />
                      Resolver
                    </button>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </AppLayout>
  );
}
