'use client';
import { useEffect, useState, useCallback } from 'react';
import Link from 'next/link';
import { Plus, Search, Edit, Trash2, Star, StarOff, Eye } from 'lucide-react';
import { toast } from 'sonner';
import { useLanguage } from '@/lib/i18n/language-context';

export default function VehiclesPage() {
  const [vehicles, setVehicles] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('ALL');
  const [loading, setLoading] = useState(true);
  const { t, locale } = useLanguage();

  const fetchVehicles = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({ page: String(page), perPage: '20', status: statusFilter });
      if (search) params.set('search', search);
      const res = await fetch(`/api/vehicles?${params.toString()}`);
      const data = await res?.json?.() ?? {};
      setVehicles(data?.vehicles ?? []);
      setTotal(data?.total ?? 0);
    } catch { toast?.error?.(t.admin.vehicles.loadError); }
    setLoading(false);
  }, [page, search, statusFilter]);

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

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

  const toggleFeatured = async (id: string, current: boolean) => {
    try {
      await fetch(`/api/vehicles/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ featured: !current }),
      });
      toast?.success?.(t.admin.vehicles.featuredUpdated);
      fetchVehicles();
    } catch { toast?.error?.('Error'); }
  };

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

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="font-display text-2xl font-bold tracking-tight">{t.admin.vehicles.title}</h1>
        <Link href="/admin/vehicles/new" className="bg-red-600 hover:bg-red-700 text-white px-5 py-2.5 rounded-lg text-sm font-semibold transition flex items-center gap-2">
          <Plus className="w-4 h-4" /> {t.admin.vehicles.addNew}
        </Link>
      </div>

      {/* Filters */}
      <div className="bg-white rounded-xl shadow-sm p-4 mb-6 flex flex-wrap gap-4 items-center">
        <div className="relative flex-1 min-w-[200px]">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
          <input type="text" value={search} onChange={(e: any) => setSearch(e?.target?.value ?? '')} onKeyDown={(e: any) => e?.key === 'Enter' && fetchVehicles()} placeholder={t.admin.vehicles.searchPlaceholder} className="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg text-sm" />
        </div>
        <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.vehicles.all}</option>
          <option value="AVAILABLE">{t.admin.vehicles.available}</option>
          <option value="SOLD">{t.admin.vehicles.sold}</option>
        </select>
        <span className="text-sm text-gray-500">{total} {t.admin.vehicles.title?.toLowerCase()}</span>
      </div>

      {/* Table */}
      <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>
        ) : (vehicles?.length ?? 0) > 0 ? (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-gray-50 text-xs text-gray-500 uppercase">
                <tr>
                  <th className="px-4 py-3 text-left">{t.admin.vehicles.title}</th>
                  <th className="px-4 py-3 text-left">{t.admin.categories.title}</th>
                  <th className="px-4 py-3 text-left">{t.admin.vehicleForm.price}</th>
                  <th className="px-4 py-3 text-left">{t.admin.vehicleForm.status}</th>
                  <th className="px-4 py-3 text-center">{t.admin.vehicles.views}</th>
                  <th className="px-4 py-3 text-center">{t.admin.vehicleForm.featured}</th>
                  <th className="px-4 py-3 text-right">{t.admin.categories.actions}</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-50">
                {(vehicles ?? [])?.map((v: any) => (
                  <tr key={v?.id} className="hover:bg-gray-50 transition">
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-3">
                        <div className="w-12 h-10 rounded-lg bg-gray-100 overflow-hidden relative shrink-0">
                          {v?.images?.[0]?.url && <img src={v.images[0].url} alt="" className="w-full h-full object-cover" />}
                        </div>
                        <div>
                          <p className="text-sm font-medium text-gray-900 truncate max-w-[200px]">{v?.title ?? ''}</p>
                          <p className="text-xs text-gray-400">{v?.year ?? ''} &middot; {v?.make ?? ''}</p>
                        </div>
                      </div>
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-600">{(locale === 'en' && v?.category?.nameEn) ? v.category.nameEn : (v?.category?.name ?? '-')}</td>
                    <td className="px-4 py-3 text-sm font-medium text-gray-900">${(v?.price ?? 0)?.toLocaleString()}</td>
                    <td className="px-4 py-3">
                      <button onClick={() => toggleStatus(v?.id, v?.status)} className={`text-xs px-2.5 py-1 rounded-full font-medium transition ${v?.status === 'SOLD' ? 'bg-gray-100 text-gray-600 hover:bg-gray-200' : 'bg-green-50 text-green-700 hover:bg-green-100'}`}>
                        {v?.status === 'SOLD' ? t.admin.vehicles.sold : t.admin.vehicles.available}
                      </button>
                    </td>
                    <td className="px-4 py-3 text-center text-sm text-gray-500">{v?.viewCount ?? 0}</td>
                    <td className="px-4 py-3 text-center">
                      <button onClick={() => toggleFeatured(v?.id, v?.featured)} className="text-gray-400 hover:text-yellow-500 transition">
                        {v?.featured ? <Star className="w-5 h-5 fill-yellow-400 text-yellow-400" /> : <StarOff className="w-5 h-5" />}
                      </button>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-end gap-2">
                        <Link href={`/admin/vehicles/${v?.id}`} className="p-2 text-gray-400 hover:text-blue-600 transition"><Edit className="w-4 h-4" /></Link>
                        <button onClick={() => handleDelete(v?.id)} className="p-2 text-gray-400 hover:text-red-600 transition"><Trash2 className="w-4 h-4" /></button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="text-center py-12">
            <p className="text-gray-400">{t.admin.dashboard.noData}</p>
            <Link href="/admin/vehicles/new" className="inline-flex items-center gap-2 text-red-600 hover:text-red-700 text-sm font-medium mt-2">
              <Plus className="w-4 h-4" /> {t.admin.vehicles.addNew}
            </Link>
          </div>
        )}
      </div>
    </div>
  );
}
