/**
 * Appointment Types Manager
 * Full CRUD panel for managing appointment/service types
 */

"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import type { Lang } from "@/lib/config";
import { fetchWithCSRF } from "@/lib/csrf-client";
import {
  Briefcase,
  Plus,
  Trash2,
  Edit3,
  ArrowUp,
  ArrowDown,
  Download,
  Upload,
  Loader2,
  Check,
  X,
  Clock,
  DollarSign,
  ToggleLeft,
  ToggleRight,
  Languages,
} from "lucide-react";

interface AppointmentType {
  id: string;
  nameEn: string;
  nameAr: string;
  duration: number;
  price: number | null;
  isActive: boolean;
  sortOrder: number;
}

interface FormData {
  nameEn: string;
  nameAr: string;
  duration: number;
  price: string;
}

interface AppointmentTypesManagerProps {
  lang: Lang;
  isOpen?: boolean;
  onClose?: () => void;
  userIndustry?: string | null;
}

const DURATION_OPTIONS = [5, 10, 15, 20, 30, 45, 60, 90, 120];

const emptyForm: FormData = { nameEn: "", nameAr: "", duration: 30, price: "" };

export default function AppointmentTypesManager({
  lang,
  isOpen,
  onClose,
  userIndustry: _userIndustry,
}: AppointmentTypesManagerProps) {
  const isAr = lang === "ar";

  const [types, setTypes] = useState<AppointmentType[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Form state
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState<FormData>(emptyForm);

  // Auto-translate state
  const [translating, setTranslating] = useState(false);

  // Import state
  const [showImportPreview, setShowImportPreview] = useState(false);
  const [importData, setImportData] = useState<FormData[]>([]);
  const [importing, setImporting] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Suggestions state
  type SuggestedType = {
    nameEn: string;
    nameAr: string;
    duration: number;
    price?: number;
    category: string;
    categoryAr: string;
    itemType: string;
  };
  const [suggestions, setSuggestions] = useState<SuggestedType[]>([]);
  const [_loadingSuggestions, setLoadingSuggestions] = useState(false);
  const [dismissedSuggestions, setDismissedSuggestions] = useState(false);
  const [addingSuggestion, setAddingSuggestion] = useState<string | null>(null);

  // Fetch types
  const fetchTypes = useCallback(async () => {
    try {
      setLoading(true);
      const res = await fetch("/api/dashboard/appointment-types");
      const data = await res.json();
      if (data.types) {
        setTypes(data.types);
      }
    } catch (err) {
      console.error("Failed to fetch appointment types:", err);
      setError(
        isAr ? "فشل في تحميل أنواع الخدمات" : "Failed to load service types",
      );
    } finally {
      setLoading(false);
    }
  }, [isAr]);

  useEffect(() => {
    if (isOpen !== false) fetchTypes();
  }, [isOpen, fetchTypes]);

  // Fetch industry suggestions
  useEffect(() => {
    const dismissed = localStorage.getItem("suggestions-dismissed");
    if (dismissed === "true") {
      setDismissedSuggestions(true);
      return;
    }
    setLoadingSuggestions(true);
    fetch("/api/dashboard/appointment-types/suggested")
      .then((r) => r.json())
      .then((data) => {
        if (data.suggestions) setSuggestions(data.suggestions);
      })
      .catch(console.error)
      .finally(() => setLoadingSuggestions(false));
  }, []);

  // Auto-translate English name to Qatari Arabic
  const handleAutoTranslate = async () => {
    if (!form.nameEn.trim()) {
      setError(
        isAr
          ? "يرجى إدخال الاسم بالإنجليزية أولاً"
          : "Please enter the English name first",
      );
      return;
    }
    setTranslating(true);
    setError(null);
    try {
      const res = await fetchWithCSRF(
        "/api/dashboard/appointment-types/translate",
        {
          method: "POST",
          body: JSON.stringify({ text: form.nameEn.trim() }),
        },
      );
      const data = await res.json();
      if (data.success && data.translation) {
        setForm((prev) => ({ ...prev, nameAr: data.translation }));
      } else {
        setError(isAr ? "فشل في الترجمة" : "Translation failed");
      }
    } catch (err) {
      console.error("Translation error:", err);
      setError(isAr ? "فشل في الترجمة التلقائية" : "Auto-translation failed");
    } finally {
      setTranslating(false);
    }
  };

  // Create or update
  const handleSubmit = async () => {
    if (!form.nameEn.trim()) {
      setError(
        isAr
          ? "يرجى إدخال اسم الخدمة بالإنجليزية"
          : "Please enter the English service name",
      );
      return;
    }

    setSaving(true);
    setError(null);

    try {
      const payload = {
        nameEn: form.nameEn.trim(),
        nameAr: form.nameAr.trim(),
        duration: form.duration,
        price: form.price ? parseFloat(form.price) : null,
      };

      if (editingId) {
        await fetchWithCSRF(`/api/dashboard/appointment-types/${editingId}`, {
          method: "PATCH",
          body: JSON.stringify(payload),
        });
      } else {
        await fetchWithCSRF("/api/dashboard/appointment-types", {
          method: "POST",
          body: JSON.stringify(payload),
        });
      }

      setShowForm(false);
      setEditingId(null);
      setForm(emptyForm);
      await fetchTypes();
    } catch (err) {
      console.error("Save error:", err);
      setError(isAr ? "فشل في حفظ نوع الخدمة" : "Failed to save service type");
    } finally {
      setSaving(false);
    }
  };

  // Toggle active
  const handleToggleActive = async (type: AppointmentType) => {
    try {
      await fetchWithCSRF(`/api/dashboard/appointment-types/${type.id}`, {
        method: "PATCH",
        body: JSON.stringify({ isActive: !type.isActive }),
      });
      await fetchTypes();
    } catch (err) {
      console.error("Toggle error:", err);
      setError(isAr ? "فشل في تحديث الحالة" : "Failed to update status");
    }
  };

  // Delete (soft deactivate)
  const handleDelete = async (typeId: string) => {
    try {
      await fetchWithCSRF(`/api/dashboard/appointment-types/${typeId}`, {
        method: "DELETE",
      });
      await fetchTypes();
    } catch (err) {
      console.error("Delete error:", err);
      setError(
        isAr ? "فشل في حذف نوع الخدمة" : "Failed to delete service type",
      );
    }
  };

  // Start editing
  const handleEdit = (type: AppointmentType) => {
    setEditingId(type.id);
    setForm({
      nameEn: type.nameEn,
      nameAr: type.nameAr,
      duration: type.duration,
      price: type.price != null ? String(type.price) : "",
    });
    setShowForm(true);
  };

  // Reorder
  const handleReorder = async (index: number, direction: "up" | "down") => {
    const swapIndex = direction === "up" ? index - 1 : index + 1;
    if (swapIndex < 0 || swapIndex >= types.length) return;

    const newOrder = [...types];
    [newOrder[index], newOrder[swapIndex]] = [
      newOrder[swapIndex],
      newOrder[index],
    ];

    // Optimistic update
    setTypes(newOrder);

    try {
      await fetchWithCSRF("/api/dashboard/appointment-types/reorder", {
        method: "PATCH",
        body: JSON.stringify({
          order: newOrder.map((t, i) => ({ id: t.id, sortOrder: i })),
        }),
      });
    } catch (err) {
      console.error("Reorder error:", err);
      await fetchTypes(); // Revert on failure
    }
  };

  // Add a suggested type
  const handleAddSuggestion = async (suggestion: SuggestedType) => {
    setAddingSuggestion(suggestion.nameEn);
    try {
      const res = await fetchWithCSRF("/api/dashboard/appointment-types", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          nameEn: suggestion.nameEn,
          nameAr: suggestion.nameAr,
          duration: suggestion.duration,
          price: suggestion.price ?? null,
          category: suggestion.category,
          categoryAr: suggestion.categoryAr,
          itemType: suggestion.itemType,
        }),
      });
      if (res.ok) {
        setSuggestions((prev) =>
          prev.filter((s) => s.nameEn !== suggestion.nameEn),
        );
        await fetchTypes();
      }
    } finally {
      setAddingSuggestion(null);
    }
  };

  // CSV import
  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!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 ? "ملف CSV فارغ أو غير صالح" : "CSV file is empty or invalid",
        );
        return;
      }

      // Skip header row
      const parsed: FormData[] = [];
      for (let i = 1; i < lines.length; i++) {
        const cols = lines[i].split(",").map((c) => c.trim());
        if (cols.length >= 2 && cols[0] && cols[1]) {
          parsed.push({
            nameEn: cols[0],
            nameAr: cols[1],
            duration: cols[2] ? parseInt(cols[2], 10) || 30 : 30,
            price: cols[3] || "",
          });
        }
      }

      if (parsed.length === 0) {
        setError(
          isAr
            ? "لا توجد بيانات صالحة في الملف"
            : "No valid data found in file",
        );
        return;
      }

      setImportData(parsed);
      setShowImportPreview(true);
    };
    reader.readAsText(file);

    // Reset input
    if (fileInputRef.current) fileInputRef.current.value = "";
  };

  const handleConfirmImport = async () => {
    setImporting(true);
    setError(null);

    try {
      const payload = importData.map((d) => ({
        nameEn: d.nameEn,
        nameAr: d.nameAr,
        duration: d.duration,
        price: d.price ? parseFloat(d.price) : null,
      }));

      const res = await fetchWithCSRF(
        "/api/dashboard/appointment-types/import",
        {
          method: "POST",
          body: JSON.stringify({ types: payload }),
        },
      );

      const data = await res.json();

      if (!res.ok || !data.success) {
        setError(
          data.error ||
            (isAr
              ? "فشل في استيراد أنواع الخدمات"
              : "Failed to import service types"),
        );
        return;
      }

      setShowImportPreview(false);
      setImportData([]);
      await fetchTypes();
    } catch (err) {
      console.error("Import error:", err);
      setError(
        isAr
          ? "فشل في استيراد أنواع الخدمات"
          : "Failed to import service types",
      );
    } finally {
      setImporting(false);
    }
  };

  // Support both modal usage (isOpen/onClose) and inline usage
  if (isOpen === false) return null;

  return (
    <div className="border-b border-slate-100 bg-slate-50/50 p-5">
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2">
          <Briefcase className="w-5 h-5 text-emerald-600" />
          <h3 className="text-base font-bold text-slate-900">
            {isAr ? "أنواع الخدمات" : "Service Types"}
          </h3>
          <span className="rounded-full bg-emerald-100 px-2 py-0.5 text-xs font-semibold text-emerald-700">
            {types.length}
          </span>
        </div>
        <div className="flex items-center gap-2">
          {/* Download Template */}
          <button
            onClick={() =>
              window.open("/api/dashboard/appointment-types/template", "_blank")
            }
            className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-medium text-slate-600 hover:border-slate-300 hover:bg-slate-50 transition-all"
          >
            <Download className="w-3.5 h-3.5" />
            <span className="hidden sm:inline">
              {isAr ? "تحميل قالب" : "Template"}
            </span>
          </button>

          {/* Import */}
          <label className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-medium text-slate-600 hover:border-slate-300 hover:bg-slate-50 transition-all cursor-pointer">
            <Upload className="w-3.5 h-3.5" />
            <span className="hidden sm:inline">
              {isAr ? "استيراد" : "Import"}
            </span>
            <input
              ref={fileInputRef}
              type="file"
              accept=".csv"
              className="hidden"
              onChange={handleFileSelect}
            />
          </label>

          {/* Add */}
          <button
            onClick={() => {
              setEditingId(null);
              setForm(emptyForm);
              setShowForm(true);
            }}
            className="inline-flex items-center gap-1.5 rounded-lg bg-emerald-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-emerald-700 transition-all"
          >
            <Plus className="w-3.5 h-3.5" />
            {isAr ? "إضافة" : "Add"}
          </button>

          {/* Close */}
          {onClose && (
            <button
              onClick={onClose}
              className="rounded-lg border border-slate-200 bg-white p-1.5 text-slate-400 hover:text-slate-600 hover:border-slate-300 transition-all"
            >
              <X className="w-4 h-4" />
            </button>
          )}
        </div>
      </div>

      {/* Suggested for your industry panel */}
      {!dismissedSuggestions && suggestions.length > 0 && (
        <div className="mb-4 rounded-xl border border-emerald-200 bg-emerald-50 p-4">
          <div className="flex items-center justify-between mb-3">
            <div>
              <h3 className="text-sm font-semibold text-slate-800">
                {isAr ? "مقترح لصناعتك" : "Suggested for your industry"}
              </h3>
              <p className="text-xs text-slate-500 mt-0.5">
                {isAr
                  ? "اضف الخدمات بنقرة واحدة"
                  : "Add services with one click"}
              </p>
            </div>
            <button
              onClick={() => {
                setDismissedSuggestions(true);
                localStorage.setItem("suggestions-dismissed", "true");
              }}
              className="text-slate-400 hover:text-slate-600 transition-colors"
              title={isAr ? "إخفاء" : "Dismiss"}
            >
              <X className="w-4 h-4" />
            </button>
          </div>
          <div className="flex flex-wrap gap-2">
            {suggestions.map((suggestion) => (
              <button
                key={suggestion.nameEn}
                onClick={() => handleAddSuggestion(suggestion)}
                disabled={addingSuggestion === suggestion.nameEn}
                className="inline-flex items-center gap-1.5 rounded-lg border border-emerald-300 bg-white px-3 py-1.5 text-xs font-medium text-slate-700 hover:border-emerald-500 hover:text-emerald-700 transition-all disabled:opacity-50"
              >
                {addingSuggestion === suggestion.nameEn ? (
                  <Loader2 className="w-3 h-3 animate-spin" />
                ) : (
                  <Plus className="w-3 h-3" />
                )}
                {isAr ? suggestion.nameAr : suggestion.nameEn}
                <span className="text-slate-400">{suggestion.duration}m</span>
              </button>
            ))}
          </div>
        </div>
      )}

      {/* Error message */}
      {error && (
        <div className="mb-4 rounded-lg bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700 flex items-center justify-between">
          <span>{error}</span>
          <button
            onClick={() => setError(null)}
            className="text-red-400 hover:text-red-600"
          >
            <X className="w-3.5 h-3.5" />
          </button>
        </div>
      )}

      {/* Inline Form */}
      {showForm && (
        <div className="mb-4 rounded-xl border border-emerald-200 bg-white p-4">
          <h4 className="text-sm font-semibold text-slate-800 mb-3">
            {editingId
              ? isAr
                ? "تعديل نوع الخدمة"
                : "Edit Service Type"
              : isAr
                ? "إضافة نوع خدمة جديد"
                : "Add New Service Type"}
          </h4>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            {/* Name EN */}
            <div>
              <label className="block text-xs font-medium text-slate-600 mb-1">
                {isAr ? "الاسم (إنجليزي)" : "Name (English)"}
              </label>
              <input
                type="text"
                value={form.nameEn}
                onChange={(e) => setForm({ ...form, nameEn: e.target.value })}
                placeholder="e.g. Consultation"
                className="w-full rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-800 placeholder:text-slate-400 focus:border-emerald-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-emerald-100 transition-all"
              />
            </div>

            {/* Name AR */}
            <div>
              <div className="flex items-center justify-between mb-1">
                <label className="text-xs font-medium text-slate-600">
                  {isAr ? "الاسم (عربي)" : "Name (Arabic)"}
                  <span className="text-slate-400 ml-1">
                    ({isAr ? "اختياري" : "optional"})
                  </span>
                </label>
                <button
                  type="button"
                  onClick={handleAutoTranslate}
                  disabled={translating || !form.nameEn.trim()}
                  className="inline-flex items-center gap-1 rounded-md bg-violet-50 border border-violet-200 px-2 py-0.5 text-[10px] font-semibold text-violet-700 hover:bg-violet-100 hover:border-violet-300 disabled:opacity-40 disabled:cursor-not-allowed transition-all"
                  title={
                    isAr
                      ? "ترجمة تلقائية للقطرية"
                      : "Auto-translate to Qatari Arabic"
                  }
                >
                  {translating ? (
                    <Loader2 className="w-3 h-3 animate-spin" />
                  ) : (
                    <Languages className="w-3 h-3" />
                  )}
                  {isAr ? "ترجمة" : "Translate"}
                </button>
              </div>
              <input
                type="text"
                dir="rtl"
                value={form.nameAr}
                onChange={(e) => setForm({ ...form, nameAr: e.target.value })}
                placeholder={
                  isAr
                    ? "سيُترجم تلقائياً من الإنجليزية"
                    : "Auto-translated from English if empty"
                }
                className="w-full rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-800 placeholder:text-slate-400 focus:border-emerald-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-emerald-100 transition-all"
              />
            </div>

            {/* Duration */}
            <div>
              <label className="block text-xs font-medium text-slate-600 mb-1">
                <Clock className="w-3 h-3 inline mr-1" />
                {isAr ? "المدة (دقائق)" : "Duration (minutes)"}
              </label>
              <select
                value={form.duration}
                onChange={(e) =>
                  setForm({ ...form, duration: parseInt(e.target.value, 10) })
                }
                className="w-full rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-800 focus:border-emerald-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-emerald-100 transition-all"
              >
                {DURATION_OPTIONS.map((d) => (
                  <option key={d} value={d}>
                    {d} {isAr ? "دقيقة" : "min"}
                  </option>
                ))}
              </select>
            </div>

            {/* Price */}
            <div>
              <label className="block text-xs font-medium text-slate-600 mb-1">
                <DollarSign className="w-3 h-3 inline mr-1" />
                {isAr ? "السعر (ريال قطري)" : "Price (QAR)"}{" "}
                <span className="text-slate-400">
                  ({isAr ? "اختياري" : "optional"})
                </span>
              </label>
              <input
                type="number"
                min="0"
                step="0.01"
                value={form.price}
                onChange={(e) => setForm({ ...form, price: e.target.value })}
                placeholder="0.00"
                className="w-full rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-800 placeholder:text-slate-400 focus:border-emerald-400 focus:bg-white focus:outline-none focus:ring-2 focus:ring-emerald-100 transition-all"
              />
            </div>
          </div>

          {/* Form Actions */}
          <div className="mt-3 flex items-center gap-2 justify-end">
            <button
              onClick={() => {
                setShowForm(false);
                setEditingId(null);
                setForm(emptyForm);
                setError(null);
              }}
              className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-medium text-slate-600 hover:bg-slate-50 transition-all"
            >
              <X className="w-3.5 h-3.5" />
              {isAr ? "إلغاء" : "Cancel"}
            </button>
            <button
              onClick={handleSubmit}
              disabled={saving}
              className="inline-flex items-center gap-1.5 rounded-lg bg-emerald-600 px-4 py-1.5 text-xs font-semibold text-white hover:bg-emerald-700 disabled:opacity-50 transition-all"
            >
              {saving ? (
                <Loader2 className="w-3.5 h-3.5 animate-spin" />
              ) : (
                <Check className="w-3.5 h-3.5" />
              )}
              {editingId ? (isAr ? "تحديث" : "Update") : isAr ? "حفظ" : "Save"}
            </button>
          </div>
        </div>
      )}

      {/* Import Preview */}
      {showImportPreview && (
        <div className="mb-4 rounded-xl border border-blue-200 bg-blue-50/50 p-4">
          <h4 className="text-sm font-semibold text-slate-800 mb-2">
            {isAr
              ? `معاينة الاستيراد (${importData.length} خدمة)`
              : `Import Preview (${importData.length} services)`}
          </h4>
          <div className="max-h-48 overflow-y-auto rounded-lg border border-slate-200 bg-white">
            <table className="w-full text-xs">
              <thead className="bg-slate-50 text-slate-600">
                <tr>
                  <th className="px-3 py-2 text-left font-medium">
                    {isAr ? "الاسم (EN)" : "Name (EN)"}
                  </th>
                  <th className="px-3 py-2 text-right font-medium">
                    {isAr ? "الاسم (AR)" : "Name (AR)"}
                  </th>
                  <th className="px-3 py-2 text-center font-medium">
                    {isAr ? "المدة" : "Duration"}
                  </th>
                  <th className="px-3 py-2 text-center font-medium">
                    {isAr ? "السعر" : "Price"}
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {importData.map((row, i) => (
                  <tr key={i} className="text-slate-700">
                    <td className="px-3 py-1.5">{row.nameEn}</td>
                    <td className="px-3 py-1.5 text-right" dir="rtl">
                      {row.nameAr}
                    </td>
                    <td className="px-3 py-1.5 text-center">{row.duration}m</td>
                    <td className="px-3 py-1.5 text-center">
                      {row.price || "—"}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div className="mt-3 flex items-center gap-2 justify-end">
            <button
              onClick={() => {
                setShowImportPreview(false);
                setImportData([]);
              }}
              className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-medium text-slate-600 hover:bg-slate-50 transition-all"
            >
              <X className="w-3.5 h-3.5" />
              {isAr ? "إلغاء" : "Cancel"}
            </button>
            <button
              onClick={handleConfirmImport}
              disabled={importing}
              className="inline-flex items-center gap-1.5 rounded-lg bg-blue-600 px-4 py-1.5 text-xs font-semibold text-white hover:bg-blue-700 disabled:opacity-50 transition-all"
            >
              {importing ? (
                <Loader2 className="w-3.5 h-3.5 animate-spin" />
              ) : (
                <Upload className="w-3.5 h-3.5" />
              )}
              {isAr
                ? `استيراد ${importData.length} خدمة`
                : `Import ${importData.length} services`}
            </button>
          </div>
        </div>
      )}

      {/* Loading */}
      {loading && (
        <div className="flex items-center justify-center py-8">
          <Loader2 className="w-5 h-5 animate-spin text-emerald-600" />
          <span className="ml-2 text-sm text-slate-500">
            {isAr ? "جاري التحميل..." : "Loading..."}
          </span>
        </div>
      )}

      {/* Empty State */}
      {!loading && types.length === 0 && (
        <div className="flex flex-col items-center justify-center py-10 text-center">
          <div className="w-14 h-14 rounded-full bg-slate-100 flex items-center justify-center mb-3">
            <Briefcase className="w-7 h-7 text-slate-400" />
          </div>
          <p className="text-sm font-medium text-slate-600">
            {isAr ? "لا توجد أنواع خدمات مسجلة" : "No service types configured"}
          </p>
          <p className="mt-1 text-xs text-slate-400 max-w-[280px]">
            {isAr
              ? "أضف خدماتك الأولى أو استوردها من ملف Excel"
              : "Add your first service or import from an Excel file"}
          </p>
          <div className="mt-4 flex items-center gap-2">
            <label className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs font-medium text-slate-600 hover:bg-slate-50 transition-all cursor-pointer">
              <Upload className="w-3.5 h-3.5" />
              {isAr ? "استيراد" : "Import CSV"}
              <input
                type="file"
                accept=".csv"
                className="hidden"
                onChange={handleFileSelect}
              />
            </label>
            <button
              onClick={() => {
                setEditingId(null);
                setForm(emptyForm);
                setShowForm(true);
              }}
              className="inline-flex items-center gap-1.5 rounded-lg bg-emerald-600 px-3 py-2 text-xs font-semibold text-white hover:bg-emerald-700 transition-all"
            >
              <Plus className="w-3.5 h-3.5" />
              {isAr ? "إضافة خدمة" : "Add Service"}
            </button>
          </div>
        </div>
      )}

      {/* Types Table */}
      {!loading && types.length > 0 && (
        <div className="rounded-xl border border-slate-200 bg-white overflow-hidden">
          <div className="divide-y divide-slate-100">
            {types.map((type, index) => (
              <div
                key={type.id}
                className={`flex items-center justify-between px-4 py-3 transition-all hover:bg-slate-50/80 ${
                  !type.isActive ? "opacity-50" : ""
                }`}
              >
                {/* Left: Name + duration + price */}
                <div className="flex items-center gap-3 min-w-0">
                  {/* Reorder buttons */}
                  <div className="flex flex-col gap-0.5">
                    <button
                      onClick={() => handleReorder(index, "up")}
                      disabled={index === 0}
                      className="rounded p-0.5 text-slate-400 hover:text-slate-600 hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition-all"
                    >
                      <ArrowUp className="w-3 h-3" />
                    </button>
                    <button
                      onClick={() => handleReorder(index, "down")}
                      disabled={index === types.length - 1}
                      className="rounded p-0.5 text-slate-400 hover:text-slate-600 hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition-all"
                    >
                      <ArrowDown className="w-3 h-3" />
                    </button>
                  </div>

                  {/* Name */}
                  <div className="min-w-0">
                    <p className="text-sm font-semibold text-slate-800 truncate">
                      {type.nameEn}
                    </p>
                    <p className="text-xs text-slate-500 truncate" dir="rtl">
                      {type.nameAr}
                    </p>
                  </div>
                </div>

                {/* Center: Badges */}
                <div className="hidden sm:flex items-center gap-2">
                  {/* Duration badge */}
                  <span className="inline-flex items-center gap-1 rounded-full bg-slate-100 px-2 py-0.5 text-xs font-medium text-slate-600">
                    <Clock className="w-3 h-3" />
                    {type.duration}
                    {isAr ? " د" : "m"}
                  </span>

                  {/* Price badge */}
                  {type.price != null ? (
                    <span className="inline-flex items-center gap-1 rounded-full bg-emerald-50 px-2 py-0.5 text-xs font-medium text-emerald-700">
                      <DollarSign className="w-3 h-3" />
                      {type.price} QAR
                    </span>
                  ) : (
                    <span className="inline-flex rounded-full bg-slate-50 px-2 py-0.5 text-xs text-slate-400">
                      —
                    </span>
                  )}

                  {/* Item type badge */}
                  {(type as AppointmentType & { itemType?: string })
                    .itemType && (
                    <span
                      className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${
                        {
                          service: "bg-blue-50 text-blue-700",
                          product: "bg-green-50 text-green-700",
                          menu_item: "bg-orange-50 text-orange-700",
                          fee: "bg-slate-100 text-slate-600",
                          rental: "bg-purple-50 text-purple-700",
                        }[
                          (type as AppointmentType & { itemType?: string })
                            .itemType!
                        ] ?? "bg-slate-100 text-slate-600"
                      }`}
                    >
                      {(
                        type as AppointmentType & { itemType?: string }
                      ).itemType!.replace("_", " ")}
                    </span>
                  )}
                </div>

                {/* Right: Actions */}
                <div className="flex items-center gap-1.5">
                  {/* Active toggle */}
                  <button
                    onClick={() => handleToggleActive(type)}
                    className={`rounded-lg p-1.5 transition-all ${
                      type.isActive
                        ? "text-emerald-600 hover:bg-emerald-50"
                        : "text-slate-400 hover:bg-slate-100"
                    }`}
                    title={
                      type.isActive
                        ? isAr
                          ? "نشط - اضغط للتعطيل"
                          : "Active - click to deactivate"
                        : isAr
                          ? "معطل - اضغط للتفعيل"
                          : "Inactive - click to activate"
                    }
                  >
                    {type.isActive ? (
                      <ToggleRight className="w-5 h-5" />
                    ) : (
                      <ToggleLeft className="w-5 h-5" />
                    )}
                  </button>

                  {/* Edit */}
                  <button
                    onClick={() => handleEdit(type)}
                    className="rounded-lg p-1.5 text-slate-400 hover:text-blue-600 hover:bg-blue-50 transition-all"
                    title={isAr ? "تعديل" : "Edit"}
                  >
                    <Edit3 className="w-4 h-4" />
                  </button>

                  {/* Delete */}
                  <button
                    onClick={() => handleDelete(type.id)}
                    className="rounded-lg p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 transition-all"
                    title={isAr ? "حذف" : "Delete"}
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
