"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import {
  X,
  Plus,
  Edit2,
  Trash2,
  Car,
  Loader2,
  Upload,
  Download,
  FileSpreadsheet,
  AlertCircle,
  CheckCircle2,
} from "lucide-react";
import { fetchWithCSRF } from "@/lib/csrf-client";
import type { Lang } from "@/lib/config";
import type { Vehicle, VehicleType } from "@/lib/types/vehicles.types";
import {
  VEHICLE_TYPE_LABELS,
  formatVehiclePrice,
} from "@/lib/types/vehicles.types";

const VEHICLE_TYPES: VehicleType[] = [
  "CAR",
  "SUV",
  "VAN",
  "TRUCK",
  "MOTORCYCLE",
  "BUS",
  "LUXURY",
  "ELECTRIC",
];
const FUEL_TYPES = ["PETROL", "DIESEL", "ELECTRIC", "HYBRID"] as const;
const TRANSMISSIONS = ["AUTOMATIC", "MANUAL"] as const;

interface FleetManagerModalProps {
  lang: Lang;
  isOpen: boolean;
  onClose: () => void;
  onFleetUpdated?: () => void;
}

interface FormState {
  make: string;
  model: string;
  year: string;
  type: VehicleType;
  color: string;
  licensePlate: string;
  seats: string;
  fuelType: string;
  transmission: string;
  pricePerDay: string;
  pricePerWeek: string;
  pricePerMonth: string;
  depositAmount: string;
  descriptionEn: string;
}

const EMPTY_FORM: FormState = {
  make: "",
  model: "",
  year: String(new Date().getFullYear()),
  type: "CAR",
  color: "",
  licensePlate: "",
  seats: "",
  fuelType: "PETROL",
  transmission: "AUTOMATIC",
  pricePerDay: "",
  pricePerWeek: "",
  pricePerMonth: "",
  depositAmount: "",
  descriptionEn: "",
};

interface ParsedVehicle {
  make: string;
  model: string;
  year: string;
  type: string;
  color: string;
  licensePlate: string;
  seats: string;
  fuelType: string;
  transmission: string;
  pricePerDay: string;
  pricePerWeek: string;
  pricePerMonth: string;
  depositAmount: string;
  descriptionEn: string;
}

type ModalView = "list" | "form" | "bulk-upload" | "bulk-preview";

export default function FleetManagerModal({
  lang,
  isOpen,
  onClose,
  onFleetUpdated,
}: FleetManagerModalProps) {
  const isAr = lang === "ar";
  const [vehicles, setVehicles] = useState<Vehicle[]>([]);
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [view, setView] = useState<ModalView>("list");
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState<FormState>(EMPTY_FORM);

  // Bulk upload state
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [parsedVehicles, setParsedVehicles] = useState<ParsedVehicle[]>([]);
  const [importResult, setImportResult] = useState<{
    imported: number;
    errors: string[];
  } | null>(null);
  const [importing, setImporting] = useState(false);

  const fetchVehicles = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/dashboard/vehicles");
      if (res.ok) {
        const data = await res.json();
        setVehicles(data.vehicles ?? []);
      }
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (isOpen) {
      fetchVehicles();
      setView("list");
      setImportResult(null);
    }
  }, [isOpen, fetchVehicles]);

  const openAddForm = () => {
    setEditingId(null);
    setForm(EMPTY_FORM);
    setView("form");
    setError(null);
  };

  const openEditForm = (v: Vehicle) => {
    setEditingId(v._id);
    setForm({
      make: v.make,
      model: v.model,
      year: String(v.year),
      type: v.type,
      color: v.color ?? "",
      licensePlate: v.licensePlate ?? "",
      seats: v.seats ? String(v.seats) : "",
      fuelType: v.fuelType ?? "PETROL",
      transmission: v.transmission ?? "AUTOMATIC",
      pricePerDay: String(v.pricePerDay / 100),
      pricePerWeek: v.pricePerWeek ? String(v.pricePerWeek / 100) : "",
      pricePerMonth: v.pricePerMonth ? String(v.pricePerMonth / 100) : "",
      depositAmount: v.depositAmount ? String(v.depositAmount / 100) : "",
      descriptionEn: v.descriptionEn ?? "",
    });
    setView("form");
    setError(null);
  };

  const handleSave = async () => {
    if (!form.make || !form.model || !form.pricePerDay) {
      setError(
        isAr
          ? "اسم السيارة والسعر اليومي مطلوبان"
          : "Make, model and daily price are required",
      );
      return;
    }
    setSaving(true);
    setError(null);
    try {
      const payload = {
        make: form.make,
        model: form.model,
        year: Number(form.year),
        type: form.type,
        color: form.color || undefined,
        licensePlate: form.licensePlate || undefined,
        seats: form.seats ? Number(form.seats) : undefined,
        fuelType: form.fuelType || undefined,
        transmission: form.transmission || undefined,
        pricePerDay: Number(form.pricePerDay),
        pricePerWeek: form.pricePerWeek ? Number(form.pricePerWeek) : undefined,
        pricePerMonth: form.pricePerMonth
          ? Number(form.pricePerMonth)
          : undefined,
        depositAmount: form.depositAmount
          ? Number(form.depositAmount)
          : undefined,
        descriptionEn: form.descriptionEn || undefined,
      };
      if (editingId) {
        await fetchWithCSRF(`/api/dashboard/vehicles/${editingId}`, {
          method: "PUT",
          body: JSON.stringify(payload),
        });
      } else {
        await fetchWithCSRF("/api/dashboard/vehicles", {
          method: "POST",
          body: JSON.stringify(payload),
        });
      }
      await fetchVehicles();
      onFleetUpdated?.();
      setView("list");
    } catch {
      setError(
        isAr
          ? "حدث خطأ، يرجى المحاولة مجدداً"
          : "An error occurred. Please try again.",
      );
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (
      !confirm(
        isAr ? "هل أنت متأكد من حذف هذه المركبة؟" : "Delete this vehicle?",
      )
    )
      return;
    await fetchWithCSRF(`/api/dashboard/vehicles/${id}`, { method: "DELETE" });
    await fetchVehicles();
    onFleetUpdated?.();
  };

  // --- Bulk Upload ---
  const openBulkUpload = () => {
    setView("bulk-upload");
    setError(null);
    setParsedVehicles([]);
    setImportResult(null);
  };

  const downloadTemplate = () => {
    window.open("/api/dashboard/vehicles/template", "_blank");
  };

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (!file.name.endsWith(".csv")) {
      setError(isAr ? "يرجى تحميل ملف CSV" : "Please upload a CSV file");
      return;
    }

    const reader = new FileReader();
    reader.onload = (evt) => {
      const text = evt.target?.result as string;
      const lines = text.split("\n").filter((l) => l.trim());
      if (lines.length < 2) {
        setError(
          isAr
            ? "الملف فارغ أو يحتوي على عنوان فقط"
            : "File is empty or contains only headers",
        );
        return;
      }

      // Parse header row
      const headerLine = lines[0].toLowerCase().trim();
      const headers = parseCSVLine(headerLine);

      // Map known header names to field indices
      const fieldMap: Record<string, number> = {};
      const knownFields = [
        "make",
        "model",
        "year",
        "type",
        "color",
        "licenseplate",
        "seats",
        "fueltype",
        "transmission",
        "priceperday",
        "priceperweek",
        "pricepermonth",
        "depositamount",
        "descriptionen",
      ];

      headers.forEach((h, idx) => {
        const normalized = h.replace(/[^a-z]/g, "");
        const match = knownFields.find((f) => f === normalized);
        if (match) fieldMap[match] = idx;
      });

      // Require at least make, model, priceperday
      if (
        fieldMap["make"] === undefined ||
        fieldMap["model"] === undefined ||
        fieldMap["priceperday"] === undefined
      ) {
        setError(
          isAr
            ? "الملف يجب أن يحتوي على أعمدة: make, model, pricePerDay"
            : "CSV must have columns: make, model, pricePerDay",
        );
        return;
      }

      const parsed: ParsedVehicle[] = [];
      for (let i = 1; i < lines.length; i++) {
        const cols = parseCSVLine(lines[i]);
        if (cols.length < 3) continue; // skip empty/short rows

        const getCol = (field: string) => {
          const idx = fieldMap[field];
          return idx !== undefined && idx < cols.length ? cols[idx].trim() : "";
        };

        parsed.push({
          make: getCol("make"),
          model: getCol("model"),
          year: getCol("year") || String(new Date().getFullYear()),
          type: getCol("type") || "CAR",
          color: getCol("color"),
          licensePlate: getCol("licenseplate"),
          seats: getCol("seats"),
          fuelType: getCol("fueltype"),
          transmission: getCol("transmission"),
          pricePerDay: getCol("priceperday"),
          pricePerWeek: getCol("priceperweek"),
          pricePerMonth: getCol("pricepermonth"),
          depositAmount: getCol("depositamount"),
          descriptionEn: getCol("descriptionen"),
        });
      }

      if (parsed.length === 0) {
        setError(isAr ? "لم يتم العثور على بيانات" : "No data rows found");
        return;
      }

      if (parsed.length > 100) {
        setError(
          isAr
            ? "الحد الأقصى 100 مركبة لكل عملية استيراد"
            : "Maximum 100 vehicles per import",
        );
        return;
      }

      setError(null);
      setParsedVehicles(parsed);
      setView("bulk-preview");
    };

    reader.readAsText(file);
    // Reset input so same file can be re-selected
    e.target.value = "";
  };

  const handleBulkImport = async () => {
    if (parsedVehicles.length === 0) return;
    setImporting(true);
    setError(null);

    try {
      const res = await fetchWithCSRF("/api/dashboard/vehicles/import", {
        method: "POST",
        body: JSON.stringify({ vehicles: parsedVehicles }),
      });
      const data = await res.json();

      if (data.success) {
        setImportResult({
          imported: data.imported,
          errors: data.errors || [],
        });
        await fetchVehicles();
        onFleetUpdated?.();
      } else {
        setError(data.error || (isAr ? "فشل الاستيراد" : "Import failed"));
      }
    } catch {
      setError(
        isAr ? "حدث خطأ أثناء الاستيراد" : "An error occurred during import",
      );
    } finally {
      setImporting(false);
    }
  };

  const removeFromPreview = (index: number) => {
    setParsedVehicles((prev) => prev.filter((_, i) => i !== index));
  };

  if (!isOpen) return null;

  const inputClass =
    "w-full border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-green/30";

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-2xl max-h-[90vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-brand-green/10 flex items-center justify-center">
              <Car className="w-5 h-5 text-brand-green" />
            </div>
            <div>
              <h2 className="text-lg font-semibold text-slate-900">
                {isAr ? "إدارة الأسطول" : "Manage Fleet"}
              </h2>
              <p className="text-sm text-slate-500">
                {isAr ? "أضف وعدّل مركباتك" : "Add and edit your vehicles"}
              </p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            {view === "list" && (
              <>
                <button
                  onClick={openBulkUpload}
                  className="flex items-center gap-2 px-3 py-2 border border-slate-200 text-slate-700 rounded-lg text-sm font-medium hover:bg-slate-50"
                >
                  <Upload className="w-4 h-4" />
                  {isAr ? "استيراد CSV" : "Import CSV"}
                </button>
                <button
                  onClick={openAddForm}
                  className="flex items-center gap-2 px-4 py-2 bg-brand-green text-white rounded-lg text-sm font-medium hover:bg-brand-green/90"
                >
                  <Plus className="w-4 h-4" />
                  {isAr ? "إضافة مركبة" : "Add Vehicle"}
                </button>
              </>
            )}
            {(view === "bulk-upload" || view === "bulk-preview") && (
              <button
                onClick={() => {
                  setView("list");
                  setError(null);
                  setImportResult(null);
                }}
                className="flex items-center gap-2 px-3 py-2 text-sm text-slate-600 hover:text-slate-800"
              >
                {isAr ? "رجوع" : "Back"}
              </button>
            )}
            {view === "form" && (
              <button
                onClick={() => setView("list")}
                className="flex items-center gap-2 px-3 py-2 text-sm text-slate-600 hover:text-slate-800"
              >
                {isAr ? "رجوع" : "Back"}
              </button>
            )}
            <button
              onClick={onClose}
              className="p-2 text-slate-400 hover:text-slate-600 rounded-lg"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>

        <div className="flex-1 overflow-y-auto p-6 space-y-4">
          {error && (
            <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm flex items-start gap-2">
              <AlertCircle className="w-4 h-4 mt-0.5 shrink-0" />
              <span>{error}</span>
            </div>
          )}

          {/* Bulk Upload View */}
          {view === "bulk-upload" && (
            <div className="space-y-6">
              <div className="text-center py-8 border-2 border-dashed border-slate-200 rounded-xl">
                <FileSpreadsheet className="w-12 h-12 text-slate-300 mx-auto mb-3" />
                <h3 className="font-medium text-slate-900 text-sm mb-1">
                  {isAr
                    ? "استيراد المركبات من ملف CSV"
                    : "Import Vehicles from CSV"}
                </h3>
                <p className="text-xs text-slate-500 mb-4 max-w-sm mx-auto">
                  {isAr
                    ? "قم بتحميل القالب، املأه ببيانات مركباتك، ثم ارفعه هنا"
                    : "Download the template, fill in your vehicle data, then upload it here"}
                </p>

                <div className="flex items-center justify-center gap-3">
                  <button
                    onClick={downloadTemplate}
                    className="flex items-center gap-2 px-4 py-2 border border-slate-200 text-slate-700 rounded-lg text-sm font-medium hover:bg-slate-50"
                  >
                    <Download className="w-4 h-4" />
                    {isAr ? "تحميل القالب" : "Download Template"}
                  </button>
                  <button
                    onClick={() => fileInputRef.current?.click()}
                    className="flex items-center gap-2 px-4 py-2 bg-brand-green text-white rounded-lg text-sm font-medium hover:bg-brand-green/90"
                  >
                    <Upload className="w-4 h-4" />
                    {isAr ? "رفع ملف CSV" : "Upload CSV"}
                  </button>
                </div>

                <input
                  ref={fileInputRef}
                  type="file"
                  accept=".csv"
                  onChange={handleFileSelect}
                  className="hidden"
                />
              </div>

              {/* CSV Format Guide */}
              <div className="bg-slate-50 rounded-xl p-4 space-y-3">
                <h4 className="text-sm font-medium text-slate-900">
                  {isAr ? "تنسيق الملف المطلوب" : "Required CSV Format"}
                </h4>
                <div className="space-y-2 text-xs text-slate-600">
                  <p>
                    <span className="font-medium text-slate-800">
                      {isAr ? "حقول مطلوبة:" : "Required fields:"}
                    </span>{" "}
                    make, model, year, type, pricePerDay
                  </p>
                  <p>
                    <span className="font-medium text-slate-800">
                      {isAr ? "حقول اختيارية:" : "Optional fields:"}
                    </span>{" "}
                    color, licensePlate, seats, fuelType, transmission,
                    pricePerWeek, pricePerMonth, depositAmount, descriptionEn
                  </p>
                  <div>
                    <span className="font-medium text-slate-800">
                      {isAr ? "أنواع المركبات:" : "Vehicle types:"}
                    </span>
                    <div className="flex flex-wrap gap-1 mt-1">
                      {VEHICLE_TYPES.map((t) => (
                        <span
                          key={t}
                          className="px-2 py-0.5 bg-white border border-slate-200 rounded text-xs"
                        >
                          {t}
                        </span>
                      ))}
                    </div>
                  </div>
                  <div>
                    <span className="font-medium text-slate-800">
                      {isAr ? "أنواع الوقود:" : "Fuel types:"}
                    </span>{" "}
                    {FUEL_TYPES.join(", ")}
                  </div>
                  <div>
                    <span className="font-medium text-slate-800">
                      {isAr ? "ناقل الحركة:" : "Transmission:"}
                    </span>{" "}
                    {TRANSMISSIONS.join(", ")}
                  </div>
                  <p className="text-slate-500">
                    {isAr
                      ? "الأسعار بالريال القطري (مثال: 150 = 150 ر.ق/يوم)"
                      : "Prices in QAR (e.g., 150 = 150 QAR/day)"}
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* Bulk Preview View */}
          {view === "bulk-preview" && (
            <div className="space-y-4">
              {/* Import Result */}
              {importResult && (
                <div
                  className={`p-4 rounded-lg border ${
                    importResult.errors.length === 0
                      ? "bg-green-50 border-green-200"
                      : "bg-yellow-50 border-yellow-200"
                  }`}
                >
                  <div className="flex items-center gap-2 mb-2">
                    <CheckCircle2 className="w-5 h-5 text-green-600" />
                    <p className="text-sm font-medium text-green-800">
                      {isAr
                        ? `تم استيراد ${importResult.imported} مركبة بنجاح`
                        : `Successfully imported ${importResult.imported} vehicle${importResult.imported !== 1 ? "s" : ""}`}
                    </p>
                  </div>
                  {importResult.errors.length > 0 && (
                    <div className="mt-2 space-y-1">
                      <p className="text-xs font-medium text-yellow-800">
                        {isAr
                          ? `${importResult.errors.length} أخطاء:`
                          : `${importResult.errors.length} error${importResult.errors.length !== 1 ? "s" : ""}:`}
                      </p>
                      {importResult.errors.map((err, i) => (
                        <p key={i} className="text-xs text-yellow-700">
                          {err}
                        </p>
                      ))}
                    </div>
                  )}
                  <button
                    onClick={() => {
                      setView("list");
                      setImportResult(null);
                    }}
                    className="mt-3 text-sm text-brand-green hover:underline"
                  >
                    {isAr ? "العودة لقائمة المركبات" : "Back to vehicle list"}
                  </button>
                </div>
              )}

              {/* Preview Table */}
              {!importResult && (
                <>
                  <div className="flex items-center justify-between">
                    <h3 className="font-medium text-slate-900 text-sm">
                      {isAr
                        ? `معاينة ${parsedVehicles.length} مركبة`
                        : `Preview ${parsedVehicles.length} vehicle${parsedVehicles.length !== 1 ? "s" : ""}`}
                    </h3>
                    <button
                      onClick={handleBulkImport}
                      disabled={importing || parsedVehicles.length === 0}
                      className="flex items-center gap-2 px-4 py-2 bg-brand-green text-white rounded-lg text-sm font-medium hover:bg-brand-green/90 disabled:opacity-50"
                    >
                      {importing && (
                        <Loader2 className="w-4 h-4 animate-spin" />
                      )}
                      {isAr
                        ? `استيراد ${parsedVehicles.length} مركبة`
                        : `Import ${parsedVehicles.length} Vehicle${parsedVehicles.length !== 1 ? "s" : ""}`}
                    </button>
                  </div>

                  <div className="border border-slate-200 rounded-xl overflow-hidden">
                    <div className="overflow-x-auto">
                      <table className="w-full text-xs">
                        <thead>
                          <tr className="bg-slate-50 text-slate-600">
                            <th className="text-left px-3 py-2 font-medium">
                              #
                            </th>
                            <th className="text-left px-3 py-2 font-medium">
                              {isAr ? "الشركة" : "Make"}
                            </th>
                            <th className="text-left px-3 py-2 font-medium">
                              {isAr ? "الطراز" : "Model"}
                            </th>
                            <th className="text-left px-3 py-2 font-medium">
                              {isAr ? "السنة" : "Year"}
                            </th>
                            <th className="text-left px-3 py-2 font-medium">
                              {isAr ? "النوع" : "Type"}
                            </th>
                            <th className="text-left px-3 py-2 font-medium">
                              {isAr ? "اللوحة" : "Plate"}
                            </th>
                            <th className="text-right px-3 py-2 font-medium">
                              {isAr ? "يومي" : "Day"}
                            </th>
                            <th className="text-right px-3 py-2 font-medium">
                              {isAr ? "أسبوعي" : "Week"}
                            </th>
                            <th className="text-right px-3 py-2 font-medium">
                              {isAr ? "شهري" : "Month"}
                            </th>
                            <th className="px-3 py-2"></th>
                          </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100">
                          {parsedVehicles.map((v, i) => (
                            <tr key={i} className="hover:bg-slate-50">
                              <td className="px-3 py-2 text-slate-400">
                                {i + 1}
                              </td>
                              <td className="px-3 py-2 font-medium text-slate-900">
                                {v.make}
                              </td>
                              <td className="px-3 py-2 text-slate-700">
                                {v.model}
                              </td>
                              <td className="px-3 py-2 text-slate-600">
                                {v.year}
                              </td>
                              <td className="px-3 py-2">
                                <span className="px-1.5 py-0.5 bg-slate-100 rounded text-slate-600">
                                  {v.type}
                                </span>
                              </td>
                              <td className="px-3 py-2 text-slate-600">
                                {v.licensePlate || "-"}
                              </td>
                              <td className="px-3 py-2 text-right text-slate-900">
                                {v.pricePerDay || "-"}
                              </td>
                              <td className="px-3 py-2 text-right text-slate-600">
                                {v.pricePerWeek || "-"}
                              </td>
                              <td className="px-3 py-2 text-right text-slate-600">
                                {v.pricePerMonth || "-"}
                              </td>
                              <td className="px-3 py-2">
                                <button
                                  onClick={() => removeFromPreview(i)}
                                  className="p-1 text-slate-300 hover:text-red-500"
                                  title={isAr ? "إزالة" : "Remove"}
                                >
                                  <X className="w-3.5 h-3.5" />
                                </button>
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </div>

                  <p className="text-xs text-slate-500">
                    {isAr
                      ? "راجع البيانات ثم اضغط استيراد. يمكنك إزالة صفوف غير صحيحة قبل الاستيراد."
                      : "Review the data and click Import. You can remove incorrect rows before importing."}
                  </p>
                </>
              )}
            </div>
          )}

          {/* Add/Edit Form */}
          {view === "form" && (
            <div className="border border-slate-200 rounded-xl p-5 bg-slate-50 space-y-4">
              <h3 className="font-medium text-slate-900 text-sm">
                {editingId
                  ? isAr
                    ? "تعديل المركبة"
                    : "Edit Vehicle"
                  : isAr
                    ? "مركبة جديدة"
                    : "New Vehicle"}
              </h3>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs text-slate-600 mb-1 block">
                    {isAr ? "الشركة المصنعة" : "Make"} *
                  </label>
                  <input
                    value={form.make}
                    onChange={(e) =>
                      setForm((f) => ({ ...f, make: e.target.value }))
                    }
                    placeholder="Toyota"
                    className={inputClass}
                  />
                </div>
                <div>
                  <label className="text-xs text-slate-600 mb-1 block">
                    {isAr ? "الطراز" : "Model"} *
                  </label>
                  <input
                    value={form.model}
                    onChange={(e) =>
                      setForm((f) => ({ ...f, model: e.target.value }))
                    }
                    placeholder="Camry"
                    className={inputClass}
                  />
                </div>
                <div>
                  <label className="text-xs text-slate-600 mb-1 block">
                    {isAr ? "السنة" : "Year"}
                  </label>
                  <input
                    type="number"
                    value={form.year}
                    onChange={(e) =>
                      setForm((f) => ({ ...f, year: e.target.value }))
                    }
                    className={inputClass}
                  />
                </div>
                <div>
                  <label className="text-xs text-slate-600 mb-1 block">
                    {isAr ? "النوع" : "Type"}
                  </label>
                  <select
                    value={form.type}
                    onChange={(e) =>
                      setForm((f) => ({
                        ...f,
                        type: e.target.value as VehicleType,
                      }))
                    }
                    className={inputClass}
                  >
                    {VEHICLE_TYPES.map((t) => (
                      <option key={t} value={t}>
                        {isAr
                          ? VEHICLE_TYPE_LABELS[t].ar
                          : VEHICLE_TYPE_LABELS[t].en}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="text-xs text-slate-600 mb-1 block">
                    {isAr ? "اللون" : "Color"}
                  </label>
                  <input
                    value={form.color}
                    onChange={(e) =>
                      setForm((f) => ({ ...f, color: e.target.value }))
                    }
                    placeholder="White"
                    className={inputClass}
                  />
                </div>
                <div>
                  <label className="text-xs text-slate-600 mb-1 block">
                    {isAr ? "رقم اللوحة" : "License Plate"}
                  </label>
                  <input
                    value={form.licensePlate}
                    onChange={(e) =>
                      setForm((f) => ({ ...f, licensePlate: e.target.value }))
                    }
                    className={inputClass}
                  />
                </div>
                <div>
                  <label className="text-xs text-slate-600 mb-1 block">
                    {isAr ? "عدد المقاعد" : "Seats"}
                  </label>
                  <input
                    type="number"
                    value={form.seats}
                    onChange={(e) =>
                      setForm((f) => ({ ...f, seats: e.target.value }))
                    }
                    className={inputClass}
                  />
                </div>
                <div>
                  <label className="text-xs text-slate-600 mb-1 block">
                    {isAr ? "نوع الوقود" : "Fuel Type"}
                  </label>
                  <select
                    value={form.fuelType}
                    onChange={(e) =>
                      setForm((f) => ({ ...f, fuelType: e.target.value }))
                    }
                    className={inputClass}
                  >
                    {FUEL_TYPES.map((t) => (
                      <option key={t} value={t}>
                        {t}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="text-xs text-slate-600 mb-1 block">
                    {isAr ? "ناقل الحركة" : "Transmission"}
                  </label>
                  <select
                    value={form.transmission}
                    onChange={(e) =>
                      setForm((f) => ({ ...f, transmission: e.target.value }))
                    }
                    className={inputClass}
                  >
                    {TRANSMISSIONS.map((t) => (
                      <option key={t} value={t}>
                        {t}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              {/* Pricing */}
              <div>
                <h4 className="text-xs font-medium text-slate-700 mb-2">
                  {isAr ? "التسعير (QAR)" : "Pricing (QAR)"}
                </h4>
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="text-xs text-slate-600 mb-1 block">
                      {isAr ? "سعر اليوم" : "Price/Day"} *
                    </label>
                    <input
                      type="number"
                      step="0.01"
                      value={form.pricePerDay}
                      onChange={(e) =>
                        setForm((f) => ({ ...f, pricePerDay: e.target.value }))
                      }
                      placeholder="150"
                      className={inputClass}
                    />
                  </div>
                  <div>
                    <label className="text-xs text-slate-600 mb-1 block">
                      {isAr ? "سعر الأسبوع" : "Price/Week"}
                    </label>
                    <input
                      type="number"
                      step="0.01"
                      value={form.pricePerWeek}
                      onChange={(e) =>
                        setForm((f) => ({ ...f, pricePerWeek: e.target.value }))
                      }
                      placeholder="900"
                      className={inputClass}
                    />
                  </div>
                  <div>
                    <label className="text-xs text-slate-600 mb-1 block">
                      {isAr ? "سعر الشهر" : "Price/Month"}
                    </label>
                    <input
                      type="number"
                      step="0.01"
                      value={form.pricePerMonth}
                      onChange={(e) =>
                        setForm((f) => ({
                          ...f,
                          pricePerMonth: e.target.value,
                        }))
                      }
                      placeholder="3000"
                      className={inputClass}
                    />
                  </div>
                  <div>
                    <label className="text-xs text-slate-600 mb-1 block">
                      {isAr ? "مبلغ التأمين" : "Deposit"}
                    </label>
                    <input
                      type="number"
                      step="0.01"
                      value={form.depositAmount}
                      onChange={(e) =>
                        setForm((f) => ({
                          ...f,
                          depositAmount: e.target.value,
                        }))
                      }
                      placeholder="500"
                      className={inputClass}
                    />
                  </div>
                </div>
              </div>

              {/* Description */}
              <div>
                <label className="text-xs text-slate-600 mb-1 block">
                  {isAr ? "الوصف" : "Description"}
                </label>
                <textarea
                  value={form.descriptionEn}
                  onChange={(e) =>
                    setForm((f) => ({ ...f, descriptionEn: e.target.value }))
                  }
                  rows={2}
                  className={inputClass}
                />
              </div>

              {/* Actions */}
              <div className="flex items-center gap-2 justify-end">
                <button
                  onClick={() => setView("list")}
                  className="px-4 py-2 text-sm text-slate-600 hover:text-slate-800"
                >
                  {isAr ? "إلغاء" : "Cancel"}
                </button>
                <button
                  onClick={handleSave}
                  disabled={saving}
                  className="flex items-center gap-2 px-4 py-2 bg-brand-green text-white rounded-lg text-sm font-medium hover:bg-brand-green/90 disabled:opacity-50"
                >
                  {saving && <Loader2 className="w-4 h-4 animate-spin" />}
                  {editingId
                    ? isAr
                      ? "حفظ التعديلات"
                      : "Save Changes"
                    : isAr
                      ? "إضافة"
                      : "Add Vehicle"}
                </button>
              </div>
            </div>
          )}

          {/* Vehicle List */}
          {view === "list" && (
            <>
              {loading ? (
                <div className="flex items-center justify-center py-12">
                  <Loader2 className="w-6 h-6 animate-spin text-slate-400" />
                </div>
              ) : vehicles.length === 0 ? (
                <div className="text-center py-12">
                  <Car className="w-12 h-12 text-slate-300 mx-auto mb-3" />
                  <p className="text-slate-500 text-sm">
                    {isAr ? "لا توجد مركبات بعد" : "No vehicles yet"}
                  </p>
                  <div className="flex items-center justify-center gap-3 mt-4">
                    <button
                      onClick={openAddForm}
                      className="text-sm text-brand-green hover:underline"
                    >
                      {isAr ? "أضف أول مركبة" : "Add your first vehicle"}
                    </button>
                    <span className="text-slate-300">|</span>
                    <button
                      onClick={openBulkUpload}
                      className="text-sm text-brand-green hover:underline flex items-center gap-1"
                    >
                      <Upload className="w-3.5 h-3.5" />
                      {isAr ? "استيراد من CSV" : "Import from CSV"}
                    </button>
                  </div>
                </div>
              ) : (
                <div className="space-y-3">
                  {vehicles.map((v) => (
                    <div
                      key={v._id}
                      className="flex items-center justify-between p-4 border border-slate-200 rounded-xl hover:border-slate-300 transition-colors"
                    >
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-lg bg-slate-100 flex items-center justify-center">
                          <Car className="w-5 h-5 text-slate-500" />
                        </div>
                        <div>
                          <p className="font-medium text-slate-900 text-sm">
                            {v.make} {v.model} {v.year}
                          </p>
                          <p className="text-xs text-slate-500">
                            {isAr
                              ? VEHICLE_TYPE_LABELS[v.type].ar
                              : VEHICLE_TYPE_LABELS[v.type].en}
                            {v.licensePlate && ` · ${v.licensePlate}`}
                            {" · "}
                            {formatVehiclePrice(v.pricePerDay, v.currency)}
                            {isAr ? "/يوم" : "/day"}
                          </p>
                        </div>
                      </div>
                      <div className="flex items-center gap-1">
                        <span
                          className={`px-2 py-1 rounded-full text-xs font-medium ${v.isAvailable ? "bg-green-100 text-green-700" : "bg-red-100 text-red-700"}`}
                        >
                          {v.isAvailable
                            ? isAr
                              ? "متاح"
                              : "Available"
                            : isAr
                              ? "مؤجر"
                              : "Rented"}
                        </span>
                        <button
                          onClick={() => openEditForm(v)}
                          className="p-2 text-slate-400 hover:text-slate-600 rounded-lg"
                        >
                          <Edit2 className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => handleDelete(v._id)}
                          className="p-2 text-slate-400 hover:text-red-500 rounded-lg"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
}

/** Parse a single CSV line handling quoted fields */
function parseCSVLine(line: string): string[] {
  const result: string[] = [];
  let current = "";
  let inQuotes = false;

  for (let i = 0; i < line.length; i++) {
    const ch = line[i];
    if (ch === '"') {
      if (inQuotes && i + 1 < line.length && line[i + 1] === '"') {
        current += '"';
        i++;
      } else {
        inQuotes = !inQuotes;
      }
    } else if (ch === "," && !inQuotes) {
      result.push(current.trim());
      current = "";
    } else {
      current += ch;
    }
  }
  result.push(current.trim());
  return result;
}
