'use client';
import { useState, useEffect, useRef, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { toast } from 'sonner';
import { Upload, X, ImageIcon, GripVertical, Star } from 'lucide-react';
import { useLanguage } from '@/lib/i18n/language-context';

export function VehicleForm({ vehicle }: { vehicle?: any }) {
  const router = useRouter();
  const isEdit = !!vehicle?.id;
  const [categories, setCategories] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [images, setImages] = useState<any[]>(vehicle?.images ?? []);
  const { t } = useLanguage();

  // Drag state
  const [dragIndex, setDragIndex] = useState<number | null>(null);
  const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);

  const [form, setForm] = useState({
    title: vehicle?.title ?? '',
    make: vehicle?.make ?? '',
    model: vehicle?.model ?? '',
    year: vehicle?.year ?? new Date().getFullYear(),
    price: vehicle?.price ?? '',
    mileage: vehicle?.mileage ?? '',
    engineType: vehicle?.engineType ?? '',
    transmission: vehicle?.transmission ?? '',
    fuelType: vehicle?.fuelType ?? '',
    horsepower: vehicle?.horsepower ?? '',
    color: vehicle?.color ?? '',
    vin: vehicle?.vin ?? '',
    stockNumber: vehicle?.stockNumber ?? '',
    condition: vehicle?.condition ?? 'Used',
    status: vehicle?.status ?? 'AVAILABLE',
    featured: vehicle?.featured ?? false,
    categoryId: vehicle?.categoryId ?? '',
    description: vehicle?.description ?? '',
  });

  useEffect(() => {
    fetch('/api/categories')
      .then((r: any) => r?.json?.())
      .then((d: any) => setCategories(Array.isArray(d) ? d : []))
      .catch(() => {});
  }, []);

  const handleImageUpload = async (e: any) => {
    const files = Array.from(e?.target?.files ?? []) as File[];
    if ((files?.length ?? 0) === 0) return;
    setUploading(true);
    
    for (const file of files) {
      try {
        const res = await fetch('/api/upload/presigned', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ fileName: file?.name ?? 'image.jpg', contentType: file?.type ?? 'image/jpeg', isPublic: true }),
        });
        const { uploadUrl, cloud_storage_path } = await res?.json?.() ?? {};
        if (!uploadUrl) throw new Error('No upload URL');

        const urlObj = new URL(uploadUrl);
        const signedHeaders = urlObj?.searchParams?.get('X-Amz-SignedHeaders') ?? '';
        const headers: Record<string, string> = { 'Content-Type': file?.type ?? 'image/jpeg' };
        if (signedHeaders?.includes('content-disposition')) {
          headers['Content-Disposition'] = 'attachment';
        }

        await fetch(uploadUrl, { method: 'PUT', headers, body: file });

        const publicUrl = uploadUrl?.split('?')?.[0] ?? '';

        setImages((prev: any[]) => [...(prev ?? []), {
          cloudStoragePath: cloud_storage_path,
          isPublic: true,
          url: publicUrl,
          alt: file?.name ?? '',
        }]);
      } catch (err: any) {
        console.error('Upload error:', err);
        toast?.error?.(`Error: ${file?.name ?? 'image'}`);
      }
    }
    setUploading(false);
  };

  const removeImage = (index: number) => {
    setImages((prev: any[]) => (prev ?? [])?.filter((_: any, i: number) => i !== index));
  };

  // Drag and drop handlers
  const handleDragStart = (index: number) => {
    setDragIndex(index);
  };

  const handleDragOver = (e: React.DragEvent, index: number) => {
    e.preventDefault();
    setDragOverIndex(index);
  };

  const handleDragLeave = () => {
    setDragOverIndex(null);
  };

  const handleDrop = (e: React.DragEvent, dropIndex: number) => {
    e.preventDefault();
    if (dragIndex === null || dragIndex === dropIndex) {
      setDragIndex(null);
      setDragOverIndex(null);
      return;
    }

    setImages((prev: any[]) => {
      const updated = [...(prev ?? [])];
      const [dragged] = updated.splice(dragIndex, 1);
      updated.splice(dropIndex, 0, dragged);
      return updated;
    });

    if (dropIndex === 0) {
      toast?.success?.('Foto principal actualizada');
    }

    setDragIndex(null);
    setDragOverIndex(null);
  };

  const handleDragEnd = () => {
    setDragIndex(null);
    setDragOverIndex(null);
  };

  // Set as primary (click to move to first position)
  const setPrimary = (index: number) => {
    if (index === 0) return;
    setImages((prev: any[]) => {
      const updated = [...(prev ?? [])];
      const [item] = updated.splice(index, 1);
      updated.unshift(item);
      return updated;
    });
    toast?.success?.('Foto principal actualizada');
  };

  const handleSubmit = async (e: any) => {
    e?.preventDefault?.();
    if (!form?.categoryId) {
      toast?.error?.(t.admin.vehicleForm.selectCategory);
      return;
    }
    setLoading(true);
    try {
      const url = isEdit ? `/api/vehicles/${vehicle?.id}` : '/api/vehicles';
      const method = isEdit ? 'PUT' : 'POST';
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...(form ?? {}), images: images ?? [] }),
      });
      if (res?.ok) {
        toast?.success?.(isEdit ? t.admin.vehicleForm.updated : t.admin.vehicleForm.created);
        router.push('/admin/vehicles');
      } else {
        toast?.error?.(t.admin.vehicleForm.error);
      }
    } catch {
      toast?.error?.(t.admin.vehicleForm.error);
    }
    setLoading(false);
  };

  const update = (key: string, value: any) => setForm((p: any) => ({ ...(p ?? {}), [key]: value }));

  return (
    <form onSubmit={handleSubmit} className="space-y-6 max-w-4xl">
      {/* Images */}
      <div className="bg-white rounded-xl shadow-sm p-6">
        <h2 className="font-semibold text-lg mb-2 flex items-center gap-2"><ImageIcon className="w-5 h-5 text-red-500" /> {t.admin.vehicleForm.images}</h2>
        <p className="text-xs text-gray-400 mb-4">Arrastra las fotos para cambiar el orden. La primera foto será la imagen principal.</p>
        <div className="grid grid-cols-3 md:grid-cols-5 gap-3 mb-4">
          {(images ?? [])?.map((img: any, i: number) => (
            <div
              key={`${img?.url ?? ''}-${i}`}
              draggable
              onDragStart={() => handleDragStart(i)}
              onDragOver={(e) => handleDragOver(e, i)}
              onDragLeave={handleDragLeave}
              onDrop={(e) => handleDrop(e, i)}
              onDragEnd={handleDragEnd}
              className={`relative aspect-square rounded-lg overflow-hidden bg-gray-100 group cursor-grab active:cursor-grabbing transition-all ${
                dragIndex === i ? 'opacity-40 scale-95' : ''
              } ${
                dragOverIndex === i && dragIndex !== i ? 'ring-2 ring-red-500 scale-105' : ''
              } ${
                i === 0 ? 'ring-2 ring-red-500' : ''
              }`}
            >
              <img src={img?.url ?? ''} alt={img?.alt ?? ''} className="w-full h-full object-cover" />
              {/* Drag handle overlay */}
              <div className="absolute inset-0 bg-black/0 group-hover:bg-black/30 transition flex items-center justify-center">
                <GripVertical className="w-6 h-6 text-white opacity-0 group-hover:opacity-100 transition drop-shadow-lg" />
              </div>
              {/* Remove button */}
              <button type="button" onClick={() => removeImage(i)} className="absolute top-1 right-1 bg-red-600 text-white p-1 rounded-full opacity-0 group-hover:opacity-100 transition z-10">
                <X className="w-3 h-3" />
              </button>
              {/* Set as primary button */}
              {i !== 0 && (
                <button type="button" onClick={() => setPrimary(i)} title="Establecer como principal" className="absolute top-1 left-1 bg-black/60 text-white p-1 rounded-full opacity-0 group-hover:opacity-100 transition z-10 hover:bg-red-600">
                  <Star className="w-3 h-3" />
                </button>
              )}
              {/* Primary badge */}
              {i === 0 && <span className="absolute bottom-1 left-1 bg-red-600 text-white text-[10px] px-1.5 py-0.5 rounded font-semibold flex items-center gap-1"><Star className="w-2.5 h-2.5" /> Principal</span>}
              {/* Order number */}
              {i > 0 && <span className="absolute bottom-1 left-1 bg-black/50 text-white text-[10px] px-1.5 py-0.5 rounded">{i + 1}</span>}
            </div>
          ))}
          <label className="aspect-square rounded-lg border-2 border-dashed border-gray-300 hover:border-red-500 flex flex-col items-center justify-center cursor-pointer transition text-gray-400 hover:text-red-500">
            <Upload className="w-6 h-6 mb-1" />
            <span className="text-xs">{t.admin.vehicleForm.uploadImages}</span>
            <input type="file" multiple accept="image/*" onChange={handleImageUpload} className="hidden" />
          </label>
        </div>
        {uploading && <p className="text-xs text-gray-400">{t.admin.vehicleForm.saving}...</p>}
      </div>

      {/* Basic info */}
      <div className="bg-white rounded-xl shadow-sm p-6">
        <h2 className="font-semibold text-lg mb-4">{t.admin.vehicleForm.title}</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="text-sm font-medium text-gray-700 mb-1 block">{t.admin.vehicleForm.title}</label>
            <input type="text" required value={form?.title ?? ''} onChange={(e: any) => update('title', e?.target?.value ?? '')} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm" placeholder="Ej: Kenworth T680 2020" />
          </div>
          <div>
            <label className="text-sm font-medium text-gray-700 mb-1 block">{t.admin.vehicleForm.category} *</label>
            <select required value={form?.categoryId ?? ''} onChange={(e: any) => update('categoryId', e?.target?.value ?? '')} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm">
              <option value="">{t.admin.vehicleForm.selectCategory}...</option>
              {(categories ?? [])?.map((c: any) => <option key={c?.id} value={c?.id}>{c?.name}{c?.nameEn ? ` (${c.nameEn})` : ''}</option>)}
            </select>
          </div>
          <div>
            <label className="text-sm font-medium text-gray-700 mb-1 block">{t.admin.vehicleForm.make} *</label>
            <input type="text" required value={form?.make ?? ''} onChange={(e: any) => update('make', e?.target?.value ?? '')} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm" />
          </div>
          <div>
            <label className="text-sm font-medium text-gray-700 mb-1 block">{t.admin.vehicleForm.model} *</label>
            <input type="text" required value={form?.model ?? ''} onChange={(e: any) => update('model', e?.target?.value ?? '')} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm" />
          </div>
          <div>
            <label className="text-sm font-medium text-gray-700 mb-1 block">{t.admin.vehicleForm.year} *</label>
            <input type="number" required value={form?.year ?? ''} onChange={(e: any) => update('year', e?.target?.value ?? '')} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm" />
          </div>
          <div>
            <label className="text-sm font-medium text-gray-700 mb-1 block">{t.admin.vehicleForm.price} *</label>
            <input type="number" required value={form?.price ?? ''} onChange={(e: any) => update('price', e?.target?.value ?? '')} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm" placeholder="0.00" />
          </div>
          <div>
            <label className="text-sm font-medium text-gray-700 mb-1 block">{t.admin.vehicleForm.mileage}</label>
            <input type="number" value={form?.mileage ?? ''} onChange={(e: any) => update('mileage', e?.target?.value ?? '')} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm" />
          </div>
          <div>
            <label className="text-sm font-medium text-gray-700 mb-1 block">{t.admin.vehicleForm.color}</label>
            <input type="text" value={form?.color ?? ''} onChange={(e: any) => update('color', e?.target?.value ?? '')} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm" />
          </div>
        </div>
      </div>

      {/* Specs */}
      <div className="bg-white rounded-xl shadow-sm p-6">
        <h2 className="font-semibold text-lg mb-4">{t.admin.vehicleForm.engineType}</h2>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="text-sm font-medium text-gray-700 mb-1 block">{t.admin.vehicleForm.engineType}</label>
            <input type="text" value={form?.engineType ?? ''} onChange={(e: any) => update('engineType', e?.target?.value ?? '')} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm" />
          </div>
          <div>
            <label className="text-sm font-medium text-gray-700 mb-1 block">{t.admin.vehicleForm.transmission}</label>
            <select value={form?.transmission ?? ''} onChange={(e: any) => update('transmission', e?.target?.value ?? '')} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm">
              <option value="">-</option>
              <option value="Automatic">Automatic</option>
              <option value="Manual">Manual</option>
              <option value="Semi-Automatic">Semi-Automatic</option>
            </select>
          </div>
          <div>
            <label className="text-sm font-medium text-gray-700 mb-1 block">{t.admin.vehicleForm.fuelType}</label>
            <select value={form?.fuelType ?? ''} onChange={(e: any) => update('fuelType', e?.target?.value ?? '')} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm">
              <option value="">-</option>
              <option value="Diesel">Diesel</option>
              <option value="Gasoline">Gasoline</option>
              <option value="Electric">Electric</option>
              <option value="Hybrid">Hybrid</option>
            </select>
          </div>
          <div>
            <label className="text-sm font-medium text-gray-700 mb-1 block">{t.admin.vehicleForm.horsepower}</label>
            <input type="text" value={form?.horsepower ?? ''} onChange={(e: any) => update('horsepower', e?.target?.value ?? '')} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm" placeholder="Ej: 450 HP" />
          </div>
          <div>
            <label className="text-sm font-medium text-gray-700 mb-1 block">{t.admin.vehicleForm.vin}</label>
            <input type="text" value={form?.vin ?? ''} onChange={(e: any) => update('vin', e?.target?.value ?? '')} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm" />
          </div>
          <div>
            <label className="text-sm font-medium text-gray-700 mb-1 block">{t.admin.vehicleForm.stockNumber}</label>
            <input type="text" value={form?.stockNumber ?? ''} onChange={(e: any) => update('stockNumber', e?.target?.value ?? '')} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm" />
          </div>
        </div>
      </div>

      {/* Status */}
      <div className="bg-white rounded-xl shadow-sm p-6">
        <h2 className="font-semibold text-lg mb-4">{t.admin.vehicleForm.status}</h2>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="text-sm font-medium text-gray-700 mb-1 block">{t.admin.vehicleForm.condition}</label>
            <select value={form?.condition ?? ''} onChange={(e: any) => update('condition', e?.target?.value ?? '')} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm">
              <option value="New">New</option>
              <option value="Used">Used</option>
              <option value="Certified">Certified</option>
            </select>
          </div>
          <div>
            <label className="text-sm font-medium text-gray-700 mb-1 block">{t.admin.vehicleForm.status}</label>
            <select value={form?.status ?? ''} onChange={(e: any) => update('status', e?.target?.value ?? '')} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm">
              <option value="AVAILABLE">{t.admin.vehicleForm.available}</option>
              <option value="SOLD">{t.admin.vehicleForm.sold}</option>
            </select>
          </div>
          <div className="flex items-end">
            <label className="flex items-center gap-2 cursor-pointer">
              <input type="checkbox" checked={form?.featured ?? false} onChange={(e: any) => update('featured', e?.target?.checked ?? false)} className="w-4 h-4 text-red-600 rounded" />
              <span className="text-sm font-medium text-gray-700">{t.admin.vehicleForm.featured}</span>
            </label>
          </div>
        </div>
        <div className="mt-4">
          <label className="text-sm font-medium text-gray-700 mb-1 block">{t.admin.vehicleForm.description}</label>
          <textarea rows={4} value={form?.description ?? ''} onChange={(e: any) => update('description', e?.target?.value ?? '')} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm resize-none" />
        </div>
      </div>

      {/* Actions */}
      <div className="flex items-center gap-3">
        <button type="submit" disabled={loading} className="bg-red-600 hover:bg-red-700 disabled:bg-gray-400 text-white px-8 py-3 rounded-lg font-semibold text-sm transition">
          {loading ? t.admin.vehicleForm.saving : t.admin.vehicleForm.save}
        </button>
        <button type="button" onClick={() => router.back()} className="px-8 py-3 rounded-lg text-sm font-medium text-gray-600 hover:bg-gray-100 transition">
          {t.admin.categories.cancel}
        </button>
      </div>
    </form>
  );
}
