'use client';
import { useEffect, useState, useCallback } from 'react';
import { toast } from 'sonner';
import { Users, Trash2, ChevronLeft, ChevronRight, Mail, Phone } from 'lucide-react';
import { useLanguage } from '@/lib/i18n/language-context';

const statusColors: any = {
  NEW: 'bg-orange-50 text-orange-600',
  CONTACTED: 'bg-blue-50 text-blue-600',
  CLOSED: 'bg-green-50 text-green-600',
  LOST: 'bg-gray-100 text-gray-600',
};

export default function LeadsPage() {
  const [leads, setLeads] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [statusFilter, setStatusFilter] = useState('ALL');
  const [loading, setLoading] = useState(true);
  const { t } = useLanguage();

  const fetchLeads = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({ page: String(page), status: statusFilter });
      const res = await fetch(`/api/leads?${params.toString()}`);
      const data = await res?.json?.() ?? {};
      setLeads(data?.leads ?? []);
      setTotal(data?.total ?? 0);
    } catch {} finally { setLoading(false); }
  }, [page, statusFilter]);

  useEffect(() => { fetchLeads(); }, [fetchLeads]);

  const updateStatus = async (id: string, status: string) => {
    try {
      await fetch(`/api/leads/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status }),
      });
      toast?.success?.(t.admin.leads.statusUpdated);
      fetchLeads();
    } catch { toast?.error?.('Error'); }
  };

  const handleDelete = async (id: string) => {
    if (!confirm(t.admin.leads.deleteConfirm)) return;
    try {
      await fetch(`/api/leads/${id}`, { method: 'DELETE' });
      toast?.success?.(t.admin.leads.deleted);
      fetchLeads();
    } catch { toast?.error?.('Error'); }
  };

  const totalPages = Math.ceil((total ?? 0) / 20);

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="font-display text-2xl font-bold tracking-tight">{t.admin.leads.title}</h1>
        <select value={statusFilter} onChange={(e: any) => { setStatusFilter(e?.target?.value ?? 'ALL'); setPage(1); }} className="border border-gray-200 rounded-lg px-3 py-2 text-sm">
          <option value="ALL">{t.admin.leads.all}</option>
          <option value="NEW">{t.admin.leads.new}</option>
          <option value="CONTACTED">{t.admin.leads.contacted}</option>
          <option value="CLOSED">{t.admin.leads.closed}</option>
          <option value="LOST">{t.admin.leads.lost}</option>
        </select>
      </div>

      <div className="bg-white rounded-xl shadow-sm overflow-hidden">
        {loading ? (
          <div className="flex justify-center py-10"><div className="animate-spin w-6 h-6 border-3 border-red-600 border-t-transparent rounded-full" /></div>
        ) : (leads?.length ?? 0) > 0 ? (
          <div className="divide-y divide-gray-50">
            {(leads ?? [])?.map((lead: any) => (
              <div key={lead?.id} className="p-4 hover:bg-gray-50 transition">
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <div className="flex items-center gap-3 mb-1">
                      <h3 className="font-medium text-gray-900">{lead?.name ?? ''}</h3>
                      <select value={lead?.status ?? 'NEW'} onChange={(e: any) => updateStatus(lead?.id, e?.target?.value ?? 'NEW')} className={`text-xs px-2 py-0.5 rounded-full font-medium border-0 cursor-pointer ${statusColors?.[lead?.status ?? 'NEW'] ?? 'bg-gray-100 text-gray-600'}`}>
                        <option value="NEW">{t.admin.leads.new}</option>
                        <option value="CONTACTED">{t.admin.leads.contacted}</option>
                        <option value="CLOSED">{t.admin.leads.closed}</option>
                        <option value="LOST">{t.admin.leads.lost}</option>
                      </select>
                    </div>
                    <div className="flex items-center gap-4 text-xs text-gray-500 mb-2">
                      <span className="flex items-center gap-1"><Mail className="w-3 h-3" /> {lead?.email ?? ''}</span>
                      {lead?.phone && <span className="flex items-center gap-1"><Phone className="w-3 h-3" /> {lead.phone}</span>}
                      <span>{lead?.source ?? ''}</span>
                    </div>
                    <p className="text-sm text-gray-600 line-clamp-2">{lead?.message ?? ''}</p>
                    {lead?.vehicle && <span className="text-xs text-red-600 mt-1 inline-block">{t.admin.leads.vehicle}: {lead.vehicle?.title ?? ''}</span>}
                    <p className="text-xs text-gray-400 mt-1">{lead?.createdAt ? new Date(lead.createdAt).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }) : ''}</p>
                  </div>
                  <button onClick={() => handleDelete(lead?.id)} className="p-2 text-gray-400 hover:text-red-600 transition"><Trash2 className="w-4 h-4" /></button>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="text-center py-12">
            <Users className="w-12 h-12 text-gray-300 mx-auto mb-3" />
            <p className="text-gray-400">{t.admin.leads.noLeads}</p>
          </div>
        )}
      </div>

      {totalPages > 1 && (
        <div className="flex justify-center items-center gap-2 mt-6">
          <button disabled={page <= 1} onClick={() => setPage(page - 1)} className="p-2 rounded-lg bg-white shadow-sm disabled:opacity-50"><ChevronLeft className="w-5 h-5" /></button>
          <span className="text-sm text-gray-500">{t.admin.leads.page} {page} {t.admin.leads.of} {totalPages}</span>
          <button disabled={page >= totalPages} onClick={() => setPage(page + 1)} className="p-2 rounded-lg bg-white shadow-sm disabled:opacity-50"><ChevronRight className="w-5 h-5" /></button>
        </div>
      )}
    </div>
  );
}
