"use client";

import { useState, useEffect } from "react";
import type { Lang } from "@/lib/config";
import {
  ClipboardList,
  Check,
  RefreshCcw,
  X,
  Users,
  ChevronRight,
  Plus,
  Trash2,
  Edit2,
  UserPlus,
  Eye,
  ChevronLeft,
} from "lucide-react";

// Category configuration
const CATEGORIES = [
  {
    value: "product",
    label: "Product Launch",
    labelAr: "إطلاق منتج",
    color: "bg-blue-100 text-blue-700",
  },
  {
    value: "feature",
    label: "New Feature",
    labelAr: "ميزة جديدة",
    color: "bg-purple-100 text-purple-700",
  },
  {
    value: "service",
    label: "Service",
    labelAr: "خدمة",
    color: "bg-green-100 text-green-700",
  },
  {
    value: "event",
    label: "Event",
    labelAr: "حدث",
    color: "bg-amber-100 text-amber-700",
  },
  {
    value: "help",
    label: "Help/Support",
    labelAr: "مساعدة/دعم",
    color: "bg-pink-100 text-pink-700",
  },
  {
    value: "general",
    label: "General",
    labelAr: "عام",
    color: "bg-slate-100 text-slate-700",
  },
];

interface PublicWaitlist {
  id: string;
  title: string;
  titleAr: string | null;
  description: string | null;
  descriptionAr: string | null;
  category?: string;
  createdAt: string;
  signupCount: number;
  isSignedUp: boolean;
}

interface MyWaitlist {
  id: string;
  title: string;
  titleAr: string | null;
  description: string | null;
  descriptionAr: string | null;
  category: string;
  isActive: boolean;
  isPublic: boolean;
  createdAt: string;
  updatedAt: string;
  signupCount: number;
  isOwner: boolean;
}

interface WaitlistSignup {
  id: string;
  name: string;
  email: string;
  mobile: string;
  notes?: string | null;
  createdAt: string;
}

interface WaitlistsPanelProps {
  lang: Lang;
  session: {
    user?: {
      name?: string | null;
      email?: string | null;
    } | null;
  };
}

type ViewMode = "browse" | "my-waitlists" | "view-signups" | "add-user";

export default function WaitlistsPanel({ lang, session }: WaitlistsPanelProps) {
  const isAr = lang === "ar";

  // View state - default to 'my-waitlists' to show user's own waitlists first
  const [viewMode, setViewMode] = useState<ViewMode>("my-waitlists");
  const [selectedWaitlist, setSelectedWaitlist] = useState<MyWaitlist | null>(
    null,
  );

  // Data state
  const [publicWaitlists, setPublicWaitlists] = useState<PublicWaitlist[]>([]);
  const [myWaitlists, setMyWaitlists] = useState<MyWaitlist[]>([]);
  const [signups, setSignups] = useState<WaitlistSignup[]>([]);

  // Loading states
  const [loading, setLoading] = useState(true);
  const [loadingSignups, setLoadingSignups] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  // Modal states
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showSignupModal, setShowSignupModal] = useState<string | null>(null);
  const [showAddUserModal, setShowAddUserModal] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState<string | null>(
    null,
  );

  // Form states
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  // Create/Edit waitlist form
  const [waitlistForm, setWaitlistForm] = useState({
    title: "",
    titleAr: "",
    description: "",
    descriptionAr: "",
    category: "general",
    isPublic: false,
  });

  // Signup form (for joining public waitlists)
  const [signupForm, setSignupForm] = useState({
    name: session?.user?.name || "",
    email: session?.user?.email || "",
    mobile: "",
  });

  // Add user form (for adding to own waitlists)
  const [addUserForm, setAddUserForm] = useState({
    name: "",
    email: "",
    mobile: "",
    notes: "",
  });

  const t = {
    // Page titles
    title: isAr ? "قوائم الانتظار" : "Waitlists",
    browseTab: isAr ? "تصفح" : "Browse",
    myWaitlistsTab: isAr ? "قوائمي" : "My Waitlists",
    subtitle: isAr
      ? "سجّل لتكون أول من يعرف عن الميزات والخدمات الجديدة"
      : "Sign up to be first to know about new features and services",
    mySubtitle: isAr
      ? "أنشئ وأدر قوائم الانتظار الخاصة بك"
      : "Create and manage your own waitlists",

    // Empty states
    noWaitlists: isAr
      ? "لا توجد قوائم انتظار متاحة حاليًا"
      : "No waitlists available right now",
    noMyWaitlists: isAr
      ? "لم تنشئ أي قوائم انتظار بعد"
      : "You haven't created any waitlists yet",
    noSignups: isAr
      ? "لا يوجد مسجلين في هذه القائمة بعد"
      : "No signups yet for this waitlist",

    // Actions
    createWaitlist: isAr ? "إنشاء قائمة انتظار" : "Create Waitlist",
    joinWaitlist: isAr ? "انضم للقائمة" : "Join Waitlist",
    addUser: isAr ? "إضافة مستخدم" : "Add User",
    viewSignups: isAr ? "عرض المسجلين" : "View Signups",
    edit: isAr ? "تعديل" : "Edit",
    delete: isAr ? "حذف" : "Delete",
    save: isAr ? "حفظ" : "Save",
    cancel: isAr ? "إلغاء" : "Cancel",
    back: isAr ? "رجوع" : "Back",
    confirm: isAr ? "تأكيد" : "Confirm",

    // Status
    alreadyJoined: isAr ? "مسجّل" : "Joined",
    signups: isAr ? "مسجّل" : "signed up",
    active: isAr ? "نشط" : "Active",
    inactive: isAr ? "غير نشط" : "Inactive",
    public: isAr ? "عام" : "Public",
    private: isAr ? "خاص" : "Private",

    // Form labels
    titleLabel: isAr ? "العنوان" : "Title",
    titleArLabel: isAr ? "العنوان (بالعربية)" : "Title (Arabic)",
    descriptionLabel: isAr ? "الوصف" : "Description",
    descriptionArLabel: isAr ? "الوصف (بالعربية)" : "Description (Arabic)",
    categoryLabel: isAr ? "الفئة" : "Category",
    isPublicLabel: isAr ? "عام (مرئي للجميع)" : "Public (visible to everyone)",
    name: isAr ? "الاسم" : "Name",
    email: isAr ? "البريد الإلكتروني" : "Email",
    mobile: isAr ? "رقم الجوال" : "Mobile Number",
    notes: isAr ? "ملاحظات" : "Notes",

    // Messages
    successCreated: isAr
      ? "تم إنشاء القائمة بنجاح!"
      : "Waitlist created successfully!",
    successUpdated: isAr
      ? "تم تحديث القائمة بنجاح!"
      : "Waitlist updated successfully!",
    successDeleted: isAr
      ? "تم حذف القائمة بنجاح!"
      : "Waitlist deleted successfully!",
    successSignup: isAr ? "تم التسجيل بنجاح!" : "Successfully signed up!",
    successUserAdded: isAr
      ? "تم إضافة المستخدم بنجاح!"
      : "User added successfully!",
    successUserRemoved: isAr
      ? "تم حذف المستخدم بنجاح!"
      : "User removed successfully!",
    errorGeneric: isAr
      ? "حدث خطأ. حاول مرة أخرى."
      : "Something went wrong. Please try again.",
    alreadySignedUp: isAr
      ? "أنت مسجّل بالفعل في هذه القائمة"
      : "You are already signed up for this waitlist",
    deleteConfirmTitle: isAr ? "تأكيد الحذف" : "Confirm Delete",
    deleteConfirmMessage: isAr
      ? "هل أنت متأكد من حذف هذه القائمة؟ سيتم حذف جميع المسجلين أيضًا."
      : "Are you sure you want to delete this waitlist? All signups will also be deleted.",
    deleteUserConfirm: isAr
      ? "هل أنت متأكد من حذف هذا المستخدم من القائمة؟"
      : "Are you sure you want to remove this user from the waitlist?",

    // Signups view
    signupsTitle: isAr ? "المسجلين" : "Signups",
    addedOn: isAr ? "تاريخ التسجيل" : "Added on",
  };

  // Fetch public waitlists
  const fetchPublicWaitlists = async () => {
    try {
      const response = await fetch("/api/waitlists", {
        credentials: "include",
      });
      if (response.ok) {
        const data = await response.json();
        setPublicWaitlists(data.waitlists || []);
      }
    } catch (err) {
      console.error("Failed to fetch public waitlists:", err);
    }
  };

  // Fetch user's own waitlists
  const fetchMyWaitlists = async () => {
    try {
      const response = await fetch("/api/waitlists?mine=true", {
        credentials: "include",
      });
      if (response.ok) {
        const data = await response.json();
        setMyWaitlists(data.waitlists || []);
      }
    } catch (err) {
      console.error("Failed to fetch my waitlists:", err);
    }
  };

  // Fetch signups for a waitlist
  const fetchSignups = async (waitlistId: string) => {
    setLoadingSignups(true);
    try {
      const response = await fetch(`/api/waitlists/${waitlistId}/signups`, {
        credentials: "include",
      });
      if (response.ok) {
        const data = await response.json();
        setSignups(data.signups || []);
      }
    } catch (err) {
      console.error("Failed to fetch signups:", err);
    } finally {
      setLoadingSignups(false);
    }
  };

  useEffect(() => {
    const loadData = async () => {
      setLoading(true);
      await Promise.all([fetchPublicWaitlists(), fetchMyWaitlists()]);
      setLoading(false);
    };
    loadData();
  }, []);

  // Handle creating a new waitlist
  const handleCreateWaitlist = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setSubmitting(true);

    try {
      const response = await fetch("/api/waitlists", {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(waitlistForm),
      });

      const data = await response.json();

      if (response.ok) {
        setSuccess(t.successCreated);
        await fetchMyWaitlists();
        setTimeout(() => {
          setShowCreateModal(false);
          setSuccess(null);
          setWaitlistForm({
            title: "",
            titleAr: "",
            description: "",
            descriptionAr: "",
            category: "general",
            isPublic: false,
          });
        }, 1500);
      } else {
        setError(data.error || t.errorGeneric);
      }
    } catch (err) {
      console.error("Create waitlist error:", err);
      setError(t.errorGeneric);
    } finally {
      setSubmitting(false);
    }
  };

  // Handle updating a waitlist
  const handleUpdateWaitlist = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedWaitlist) return;
    setError(null);
    setSubmitting(true);

    try {
      const response = await fetch(`/api/waitlists/${selectedWaitlist.id}`, {
        method: "PATCH",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(waitlistForm),
      });

      const data = await response.json();

      if (response.ok) {
        setSuccess(t.successUpdated);
        await fetchMyWaitlists();
        setTimeout(() => {
          setShowEditModal(false);
          setSuccess(null);
          setSelectedWaitlist(null);
        }, 1500);
      } else {
        setError(data.error || t.errorGeneric);
      }
    } catch (err) {
      console.error("Update waitlist error:", err);
      setError(t.errorGeneric);
    } finally {
      setSubmitting(false);
    }
  };

  // Handle deleting a waitlist
  const handleDeleteWaitlist = async (waitlistId: string) => {
    setSubmitting(true);
    try {
      const response = await fetch(`/api/waitlists/${waitlistId}`, {
        method: "DELETE",
        credentials: "include",
      });

      if (response.ok) {
        setSuccess(t.successDeleted);
        await fetchMyWaitlists();
        setShowDeleteConfirm(null);
        if (
          viewMode === "view-signups" &&
          selectedWaitlist?.id === waitlistId
        ) {
          setViewMode("my-waitlists");
          setSelectedWaitlist(null);
        }
        setTimeout(() => setSuccess(null), 2000);
      } else {
        const data = await response.json();
        setError(data.error || t.errorGeneric);
      }
    } catch (err) {
      console.error("Delete waitlist error:", err);
      setError(t.errorGeneric);
    } finally {
      setSubmitting(false);
    }
  };

  // Handle signing up for a public waitlist
  const handleSignup = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!showSignupModal) return;
    setError(null);
    setSubmitting(true);

    try {
      const response = await fetch(`/api/waitlists/${showSignupModal}/signup`, {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(signupForm),
      });

      const data = await response.json();

      if (response.ok) {
        setSuccess(t.successSignup);
        setPublicWaitlists((prev) =>
          prev.map((w) =>
            w.id === showSignupModal
              ? { ...w, isSignedUp: true, signupCount: w.signupCount + 1 }
              : w,
          ),
        );
        setTimeout(() => {
          setShowSignupModal(null);
          setSuccess(null);
        }, 1500);
      } else {
        if (response.status === 409) {
          setError(t.alreadySignedUp);
        } else {
          setError(data.error || t.errorGeneric);
        }
      }
    } catch (err) {
      console.error("Signup error:", err);
      setError(t.errorGeneric);
    } finally {
      setSubmitting(false);
    }
  };

  // Handle adding a user to own waitlist
  const handleAddUser = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedWaitlist) return;
    setError(null);
    setSubmitting(true);

    try {
      const response = await fetch(
        `/api/waitlists/${selectedWaitlist.id}/signups`,
        {
          method: "POST",
          credentials: "include",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(addUserForm),
        },
      );

      const data = await response.json();

      if (response.ok) {
        setSuccess(t.successUserAdded);
        await fetchSignups(selectedWaitlist.id);
        await fetchMyWaitlists();
        setTimeout(() => {
          setShowAddUserModal(false);
          setSuccess(null);
          setAddUserForm({ name: "", email: "", mobile: "", notes: "" });
        }, 1500);
      } else {
        setError(data.error || t.errorGeneric);
      }
    } catch (err) {
      console.error("Add user error:", err);
      setError(t.errorGeneric);
    } finally {
      setSubmitting(false);
    }
  };

  // Handle removing a signup
  const handleRemoveSignup = async (signupId: string) => {
    if (!selectedWaitlist) return;
    setSubmitting(true);

    try {
      const response = await fetch(
        `/api/waitlists/${selectedWaitlist.id}/signups?signupId=${signupId}`,
        {
          method: "DELETE",
          credentials: "include",
        },
      );

      if (response.ok) {
        setSuccess(t.successUserRemoved);
        await fetchSignups(selectedWaitlist.id);
        await fetchMyWaitlists();
        setTimeout(() => setSuccess(null), 2000);
      } else {
        const data = await response.json();
        setError(data.error || t.errorGeneric);
      }
    } catch (err) {
      console.error("Remove signup error:", err);
      setError(t.errorGeneric);
    } finally {
      setSubmitting(false);
    }
  };

  // Open edit modal with waitlist data
  const openEditModal = (waitlist: MyWaitlist) => {
    setSelectedWaitlist(waitlist);
    setWaitlistForm({
      title: waitlist.title,
      titleAr: waitlist.titleAr || "",
      description: waitlist.description || "",
      descriptionAr: waitlist.descriptionAr || "",
      category: waitlist.category,
      isPublic: waitlist.isPublic,
    });
    setError(null);
    setSuccess(null);
    setShowEditModal(true);
  };

  // Open signups view
  const openSignupsView = (waitlist: MyWaitlist) => {
    setSelectedWaitlist(waitlist);
    setViewMode("view-signups");
    fetchSignups(waitlist.id);
  };

  // Get category info
  const getCategoryInfo = (categoryValue: string) => {
    return CATEGORIES.find((c) => c.value === categoryValue) || CATEGORIES[5];
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[300px]">
        <RefreshCcw className="w-6 h-6 animate-spin text-slate-400" />
      </div>
    );
  }

  // Render signups view
  if (viewMode === "view-signups" && selectedWaitlist) {
    return (
      <div className="space-y-6 animate-fadeIn">
        {/* Header */}
        <div className="flex items-center gap-4">
          <button
            onClick={() => {
              setViewMode("my-waitlists");
              setSelectedWaitlist(null);
            }}
            className="p-2 hover:bg-slate-100 rounded-lg transition-colors"
          >
            <ChevronLeft className="w-5 h-5" />
          </button>
          <div className="flex-1">
            <h2 className="text-xl font-bold text-slate-900">
              {isAr && selectedWaitlist.titleAr
                ? selectedWaitlist.titleAr
                : selectedWaitlist.title}
            </h2>
            <p className="text-sm text-slate-500">
              {t.signupsTitle} ({signups.length})
            </p>
          </div>
          <button
            onClick={() => {
              setAddUserForm({ name: "", email: "", mobile: "", notes: "" });
              setError(null);
              setSuccess(null);
              setShowAddUserModal(true);
            }}
            className="flex items-center gap-2 px-4 py-2 bg-brand-green text-white rounded-xl hover:bg-brand-greenHover transition-colors font-semibold"
          >
            <UserPlus className="w-5 h-5" />
            {t.addUser}
          </button>
        </div>

        {/* Success/Error messages */}
        {success && (
          <div className="bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-lg text-sm flex items-center gap-2">
            <Check className="w-5 h-5" />
            {success}
          </div>
        )}
        {error && (
          <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg text-sm">
            {error}
          </div>
        )}

        {/* Signups list */}
        {loadingSignups ? (
          <div className="flex items-center justify-center py-12">
            <RefreshCcw className="w-6 h-6 animate-spin text-slate-400" />
          </div>
        ) : signups.length === 0 ? (
          <div className="text-center py-12 bg-slate-50 rounded-2xl">
            <Users className="w-12 h-12 text-slate-300 mx-auto mb-3" />
            <p className="text-slate-500">{t.noSignups}</p>
          </div>
        ) : (
          <div className="bg-white rounded-2xl border border-slate-200 overflow-hidden">
            <table className="w-full">
              <thead className="bg-slate-50">
                <tr>
                  <th className="text-start px-4 py-3 text-sm font-semibold text-slate-600">
                    {t.name}
                  </th>
                  <th className="text-start px-4 py-3 text-sm font-semibold text-slate-600">
                    {t.email}
                  </th>
                  <th className="text-start px-4 py-3 text-sm font-semibold text-slate-600">
                    {t.mobile}
                  </th>
                  <th className="text-start px-4 py-3 text-sm font-semibold text-slate-600">
                    {t.addedOn}
                  </th>
                  <th className="w-12"></th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {signups.map((signup) => (
                  <tr key={signup.id} className="hover:bg-slate-50">
                    <td className="px-4 py-3 text-sm text-slate-900">
                      {signup.name}
                    </td>
                    <td className="px-4 py-3 text-sm text-slate-600">
                      {signup.email}
                    </td>
                    <td className="px-4 py-3 text-sm text-slate-600 font-mono">
                      {signup.mobile}
                    </td>
                    <td className="px-4 py-3 text-sm text-slate-500">
                      {new Date(signup.createdAt).toLocaleDateString(
                        isAr ? "ar-SA" : "en-US",
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <button
                        onClick={() => handleRemoveSignup(signup.id)}
                        disabled={submitting}
                        className="p-1.5 text-red-500 hover:bg-red-50 rounded-lg transition-colors disabled:opacity-50"
                        title={t.delete}
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {/* Add User Modal */}
        {showAddUserModal && (
          <div className="fixed inset-0 bg-slate-900/20 backdrop-blur-sm flex items-center justify-center z-[100] p-4">
            <div
              className="bg-white rounded-2xl shadow-2xl max-w-md w-full overflow-hidden border border-slate-200"
              dir={isAr ? "rtl" : "ltr"}
            >
              <div className="flex items-center justify-between p-4 border-b border-slate-200">
                <h2 className="text-lg font-bold text-slate-900">
                  {t.addUser}
                </h2>
                <button
                  onClick={() => setShowAddUserModal(false)}
                  className="p-2 hover:bg-slate-100 rounded-lg transition-colors"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>

              <form onSubmit={handleAddUser} className="p-4 space-y-4">
                {error && (
                  <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg text-sm">
                    {error}
                  </div>
                )}
                {success && (
                  <div className="bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-lg text-sm flex items-center gap-2">
                    <Check className="w-5 h-5" />
                    {success}
                  </div>
                )}

                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">
                    {t.name} *
                  </label>
                  <input
                    type="text"
                    required
                    value={addUserForm.name}
                    onChange={(e) =>
                      setAddUserForm({ ...addUserForm, name: e.target.value })
                    }
                    className="w-full px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-transparent"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">
                    {t.email} *
                  </label>
                  <input
                    type="email"
                    required
                    value={addUserForm.email}
                    onChange={(e) =>
                      setAddUserForm({ ...addUserForm, email: e.target.value })
                    }
                    className="w-full px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-transparent"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">
                    {t.mobile} *
                  </label>
                  <input
                    type="tel"
                    required
                    value={addUserForm.mobile}
                    onChange={(e) =>
                      setAddUserForm({ ...addUserForm, mobile: e.target.value })
                    }
                    className="w-full px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-transparent"
                    placeholder="+974 5555 5555"
                    dir="ltr"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">
                    {t.notes}
                  </label>
                  <textarea
                    value={addUserForm.notes}
                    onChange={(e) =>
                      setAddUserForm({ ...addUserForm, notes: e.target.value })
                    }
                    className="w-full px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-transparent"
                    rows={2}
                  />
                </div>

                <div className="flex gap-3 pt-4">
                  <button
                    type="button"
                    onClick={() => setShowAddUserModal(false)}
                    className="flex-1 px-4 py-2.5 border border-slate-200 text-slate-700 rounded-xl hover:bg-slate-50 transition-colors font-medium"
                  >
                    {t.cancel}
                  </button>
                  <button
                    type="submit"
                    disabled={submitting || !!success}
                    className="flex-1 px-4 py-2.5 bg-brand-green text-white rounded-xl hover:bg-brand-greenHover disabled:opacity-50 transition-colors font-semibold"
                  >
                    {submitting ? (
                      <RefreshCcw className="w-5 h-5 animate-spin mx-auto" />
                    ) : (
                      t.addUser
                    )}
                  </button>
                </div>
              </form>
            </div>
          </div>
        )}
      </div>
    );
  }

  return (
    <div className="space-y-6 animate-fadeIn">
      {/* Header with tabs */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-bold text-slate-900">{t.title}</h2>
          <p className="text-sm text-slate-500 mt-1">
            {viewMode === "my-waitlists" ? t.mySubtitle : t.subtitle}
          </p>
        </div>

        {/* Tabs */}
        <div className="flex items-center gap-2">
          <div className="flex items-center bg-slate-100 rounded-xl p-1">
            <button
              onClick={() => setViewMode("browse")}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                viewMode === "browse"
                  ? "bg-white text-slate-900 shadow-sm"
                  : "text-slate-600 hover:text-slate-900"
              }`}
            >
              {t.browseTab}
            </button>
            <button
              onClick={() => setViewMode("my-waitlists")}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                viewMode === "my-waitlists"
                  ? "bg-white text-slate-900 shadow-sm"
                  : "text-slate-600 hover:text-slate-900"
              }`}
            >
              {t.myWaitlistsTab}
              {myWaitlists.length > 0 && (
                <span className="ml-2 px-1.5 py-0.5 bg-brand-green text-white text-xs rounded-full">
                  {myWaitlists.length}
                </span>
              )}
            </button>
          </div>

          {viewMode === "my-waitlists" && (
            <button
              onClick={() => {
                setWaitlistForm({
                  title: "",
                  titleAr: "",
                  description: "",
                  descriptionAr: "",
                  category: "general",
                  isPublic: false,
                });
                setError(null);
                setSuccess(null);
                setShowCreateModal(true);
              }}
              className="flex items-center gap-2 px-4 py-2 bg-brand-green text-white rounded-xl hover:bg-brand-greenHover transition-colors font-semibold"
            >
              <Plus className="w-5 h-5" />
              {t.createWaitlist}
            </button>
          )}
        </div>
      </div>

      {/* Success/Error messages */}
      {success && (
        <div className="bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-lg text-sm flex items-center gap-2">
          <Check className="w-5 h-5" />
          {success}
        </div>
      )}
      {error && (
        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg text-sm">
          {error}
        </div>
      )}

      {/* Browse public waitlists */}
      {viewMode === "browse" && (
        <>
          {publicWaitlists.length === 0 ? (
            <div className="text-center py-12 bg-slate-50 rounded-2xl">
              <ClipboardList className="w-12 h-12 text-slate-300 mx-auto mb-3" />
              <p className="text-slate-500">{t.noWaitlists}</p>
            </div>
          ) : (
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
              {publicWaitlists.map((waitlist) => {
                const cat = getCategoryInfo(waitlist.category || "general");
                return (
                  <div
                    key={waitlist.id}
                    className="group bg-white rounded-2xl border border-slate-200/80 p-5 hover:shadow-lg hover:border-brand-green/30 transition-all duration-300"
                  >
                    <div className="flex items-start justify-between mb-3">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          <span
                            className={`px-2 py-0.5 text-xs font-medium rounded-full ${cat.color}`}
                          >
                            {isAr ? cat.labelAr : cat.label}
                          </span>
                        </div>
                        <h3 className="font-semibold text-slate-900 group-hover:text-brand-green transition-colors">
                          {isAr && waitlist.titleAr
                            ? waitlist.titleAr
                            : waitlist.title}
                        </h3>
                      </div>
                      {waitlist.isSignedUp && (
                        <span className="flex items-center gap-1 px-2 py-1 bg-emerald-100 text-emerald-700 text-xs font-semibold rounded-full">
                          <Check className="w-3 h-3" />
                          {t.alreadyJoined}
                        </span>
                      )}
                    </div>

                    {(waitlist.description || waitlist.descriptionAr) && (
                      <p className="text-sm text-slate-500 mb-4 line-clamp-2">
                        {isAr && waitlist.descriptionAr
                          ? waitlist.descriptionAr
                          : waitlist.description}
                      </p>
                    )}

                    <div className="flex items-center justify-between mt-auto pt-3 border-t border-slate-100">
                      <span className="flex items-center gap-1.5 text-xs text-slate-400">
                        <Users className="w-4 h-4" />
                        {waitlist.signupCount} {t.signups}
                      </span>

                      {waitlist.isSignedUp ? (
                        <span className="text-sm text-emerald-600 font-medium">
                          {isAr ? "شكرًا لتسجيلك" : "You're in!"}
                        </span>
                      ) : (
                        <button
                          onClick={() => {
                            setSignupForm({
                              name: session?.user?.name || "",
                              email: session?.user?.email || "",
                              mobile: "",
                            });
                            setError(null);
                            setSuccess(null);
                            setShowSignupModal(waitlist.id);
                          }}
                          className="flex items-center gap-1 px-3 py-1.5 bg-brand-green text-white text-sm font-semibold rounded-lg hover:bg-brand-greenHover transition-colors"
                        >
                          {t.joinWaitlist}
                          <ChevronRight className="w-4 h-4" />
                        </button>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </>
      )}

      {/* My waitlists */}
      {viewMode === "my-waitlists" && (
        <>
          {myWaitlists.length === 0 ? (
            <div className="text-center py-12 bg-slate-50 rounded-2xl">
              <ClipboardList className="w-12 h-12 text-slate-300 mx-auto mb-3" />
              <p className="text-slate-500">{t.noMyWaitlists}</p>
              <button
                onClick={() => {
                  setWaitlistForm({
                    title: "",
                    titleAr: "",
                    description: "",
                    descriptionAr: "",
                    category: "general",
                    isPublic: false,
                  });
                  setError(null);
                  setSuccess(null);
                  setShowCreateModal(true);
                }}
                className="mt-4 inline-flex items-center gap-2 px-4 py-2 bg-brand-green text-white rounded-xl hover:bg-brand-greenHover transition-colors font-semibold"
              >
                <Plus className="w-5 h-5" />
                {t.createWaitlist}
              </button>
            </div>
          ) : (
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
              {myWaitlists.map((waitlist) => {
                const cat = getCategoryInfo(waitlist.category);
                return (
                  <div
                    key={waitlist.id}
                    className="group bg-white rounded-2xl border border-slate-200/80 p-5 hover:shadow-lg transition-all duration-300"
                  >
                    <div className="flex items-start justify-between mb-3">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          <span
                            className={`px-2 py-0.5 text-xs font-medium rounded-full ${cat.color}`}
                          >
                            {isAr ? cat.labelAr : cat.label}
                          </span>
                          <span
                            className={`px-2 py-0.5 text-xs font-medium rounded-full ${
                              waitlist.isActive
                                ? "bg-emerald-100 text-emerald-700"
                                : "bg-slate-100 text-slate-600"
                            }`}
                          >
                            {waitlist.isActive ? t.active : t.inactive}
                          </span>
                          {waitlist.isPublic && (
                            <span className="px-2 py-0.5 text-xs font-medium rounded-full bg-blue-100 text-blue-700">
                              {t.public}
                            </span>
                          )}
                        </div>
                        <h3 className="font-semibold text-slate-900">
                          {isAr && waitlist.titleAr
                            ? waitlist.titleAr
                            : waitlist.title}
                        </h3>
                      </div>
                    </div>

                    {(waitlist.description || waitlist.descriptionAr) && (
                      <p className="text-sm text-slate-500 mb-4 line-clamp-2">
                        {isAr && waitlist.descriptionAr
                          ? waitlist.descriptionAr
                          : waitlist.description}
                      </p>
                    )}

                    <div className="flex items-center justify-between mt-auto pt-3 border-t border-slate-100">
                      <span className="flex items-center gap-1.5 text-xs text-slate-400">
                        <Users className="w-4 h-4" />
                        {waitlist.signupCount} {t.signups}
                      </span>

                      <div className="flex items-center gap-1">
                        <button
                          onClick={() => openSignupsView(waitlist)}
                          className="p-1.5 text-slate-500 hover:bg-slate-100 rounded-lg transition-colors"
                          title={t.viewSignups}
                        >
                          <Eye className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => openEditModal(waitlist)}
                          className="p-1.5 text-slate-500 hover:bg-slate-100 rounded-lg transition-colors"
                          title={t.edit}
                        >
                          <Edit2 className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => setShowDeleteConfirm(waitlist.id)}
                          className="p-1.5 text-red-500 hover:bg-red-50 rounded-lg transition-colors"
                          title={t.delete}
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </>
      )}

      {/* Signup Modal (for public waitlists) */}
      {showSignupModal && (
        <div className="fixed inset-0 bg-slate-900/20 backdrop-blur-sm flex items-center justify-center z-[100] p-4">
          <div
            className="bg-white rounded-2xl shadow-2xl max-w-md w-full overflow-hidden border border-slate-200"
            dir={isAr ? "rtl" : "ltr"}
          >
            <div className="flex items-center justify-between p-4 border-b border-slate-200">
              <h2 className="text-lg font-bold text-slate-900">
                {t.joinWaitlist}
              </h2>
              <button
                onClick={() => setShowSignupModal(null)}
                className="p-2 hover:bg-slate-100 rounded-lg transition-colors"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <form onSubmit={handleSignup} className="p-4 space-y-4">
              {error && (
                <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg text-sm">
                  {error}
                </div>
              )}
              {success && (
                <div className="bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-lg text-sm flex items-center gap-2">
                  <Check className="w-5 h-5" />
                  {success}
                </div>
              )}

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  {t.name} *
                </label>
                <input
                  type="text"
                  required
                  value={signupForm.name}
                  onChange={(e) =>
                    setSignupForm({ ...signupForm, name: e.target.value })
                  }
                  className="w-full px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-transparent"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  {t.email} *
                </label>
                <input
                  type="email"
                  required
                  value={signupForm.email}
                  onChange={(e) =>
                    setSignupForm({ ...signupForm, email: e.target.value })
                  }
                  className="w-full px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-transparent"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  {t.mobile} *
                </label>
                <input
                  type="tel"
                  required
                  value={signupForm.mobile}
                  onChange={(e) =>
                    setSignupForm({ ...signupForm, mobile: e.target.value })
                  }
                  className="w-full px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-transparent"
                  placeholder="+974 5555 5555"
                  dir="ltr"
                />
              </div>

              <div className="flex gap-3 pt-4">
                <button
                  type="button"
                  onClick={() => setShowSignupModal(null)}
                  className="flex-1 px-4 py-2.5 border border-slate-200 text-slate-700 rounded-xl hover:bg-slate-50 transition-colors font-medium"
                >
                  {t.cancel}
                </button>
                <button
                  type="submit"
                  disabled={submitting || !!success}
                  className="flex-1 px-4 py-2.5 bg-brand-green text-white rounded-xl hover:bg-brand-greenHover disabled:opacity-50 transition-colors font-semibold"
                >
                  {submitting ? (
                    <RefreshCcw className="w-5 h-5 animate-spin mx-auto" />
                  ) : (
                    t.joinWaitlist
                  )}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Create Waitlist Modal */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-slate-900/20 backdrop-blur-sm flex items-center justify-center z-[100] p-4">
          <div
            className="bg-white rounded-2xl shadow-2xl max-w-lg w-full overflow-hidden max-h-[90vh] overflow-y-auto border border-slate-200"
            dir={isAr ? "rtl" : "ltr"}
          >
            <div className="flex items-center justify-between p-4 border-b border-slate-200 sticky top-0 bg-white">
              <h2 className="text-lg font-bold text-slate-900">
                {t.createWaitlist}
              </h2>
              <button
                onClick={() => setShowCreateModal(false)}
                className="p-2 hover:bg-slate-100 rounded-lg transition-colors"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <form onSubmit={handleCreateWaitlist} className="p-4 space-y-4">
              {error && (
                <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg text-sm">
                  {error}
                </div>
              )}
              {success && (
                <div className="bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-lg text-sm flex items-center gap-2">
                  <Check className="w-5 h-5" />
                  {success}
                </div>
              )}

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  {t.titleLabel} *
                </label>
                <input
                  type="text"
                  required
                  value={waitlistForm.title}
                  onChange={(e) =>
                    setWaitlistForm({ ...waitlistForm, title: e.target.value })
                  }
                  className="w-full px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-transparent"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  {t.titleArLabel}
                </label>
                <input
                  type="text"
                  value={waitlistForm.titleAr}
                  onChange={(e) =>
                    setWaitlistForm({
                      ...waitlistForm,
                      titleAr: e.target.value,
                    })
                  }
                  className="w-full px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-transparent"
                  dir="rtl"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  {t.descriptionLabel}
                </label>
                <textarea
                  value={waitlistForm.description}
                  onChange={(e) =>
                    setWaitlistForm({
                      ...waitlistForm,
                      description: e.target.value,
                    })
                  }
                  className="w-full px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-transparent"
                  rows={2}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  {t.descriptionArLabel}
                </label>
                <textarea
                  value={waitlistForm.descriptionAr}
                  onChange={(e) =>
                    setWaitlistForm({
                      ...waitlistForm,
                      descriptionAr: e.target.value,
                    })
                  }
                  className="w-full px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-transparent"
                  rows={2}
                  dir="rtl"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  {t.categoryLabel}
                </label>
                <select
                  value={waitlistForm.category}
                  onChange={(e) =>
                    setWaitlistForm({
                      ...waitlistForm,
                      category: e.target.value,
                    })
                  }
                  className="w-full px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-transparent"
                >
                  {CATEGORIES.map((cat) => (
                    <option key={cat.value} value={cat.value}>
                      {isAr ? cat.labelAr : cat.label}
                    </option>
                  ))}
                </select>
              </div>

              <div className="flex items-center gap-3">
                <input
                  type="checkbox"
                  id="isPublic"
                  checked={waitlistForm.isPublic}
                  onChange={(e) =>
                    setWaitlistForm({
                      ...waitlistForm,
                      isPublic: e.target.checked,
                    })
                  }
                  className="w-4 h-4 text-brand-green border-slate-300 rounded focus:ring-brand-green"
                />
                <label htmlFor="isPublic" className="text-sm text-slate-700">
                  {t.isPublicLabel}
                </label>
              </div>

              <div className="flex gap-3 pt-4">
                <button
                  type="button"
                  onClick={() => setShowCreateModal(false)}
                  className="flex-1 px-4 py-2.5 border border-slate-200 text-slate-700 rounded-xl hover:bg-slate-50 transition-colors font-medium"
                >
                  {t.cancel}
                </button>
                <button
                  type="submit"
                  disabled={submitting || !!success}
                  className="flex-1 px-4 py-2.5 bg-brand-green text-white rounded-xl hover:bg-brand-greenHover disabled:opacity-50 transition-colors font-semibold"
                >
                  {submitting ? (
                    <RefreshCcw className="w-5 h-5 animate-spin mx-auto" />
                  ) : (
                    t.createWaitlist
                  )}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Edit Waitlist Modal */}
      {showEditModal && selectedWaitlist && (
        <div className="fixed inset-0 bg-slate-900/20 backdrop-blur-sm flex items-center justify-center z-[100] p-4">
          <div
            className="bg-white rounded-2xl shadow-2xl max-w-lg w-full overflow-hidden max-h-[90vh] overflow-y-auto border border-slate-200"
            dir={isAr ? "rtl" : "ltr"}
          >
            <div className="flex items-center justify-between p-4 border-b border-slate-200 sticky top-0 bg-white">
              <h2 className="text-lg font-bold text-slate-900">{t.edit}</h2>
              <button
                onClick={() => {
                  setShowEditModal(false);
                  setSelectedWaitlist(null);
                }}
                className="p-2 hover:bg-slate-100 rounded-lg transition-colors"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <form onSubmit={handleUpdateWaitlist} className="p-4 space-y-4">
              {error && (
                <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg text-sm">
                  {error}
                </div>
              )}
              {success && (
                <div className="bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-lg text-sm flex items-center gap-2">
                  <Check className="w-5 h-5" />
                  {success}
                </div>
              )}

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  {t.titleLabel} *
                </label>
                <input
                  type="text"
                  required
                  value={waitlistForm.title}
                  onChange={(e) =>
                    setWaitlistForm({ ...waitlistForm, title: e.target.value })
                  }
                  className="w-full px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-transparent"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  {t.titleArLabel}
                </label>
                <input
                  type="text"
                  value={waitlistForm.titleAr}
                  onChange={(e) =>
                    setWaitlistForm({
                      ...waitlistForm,
                      titleAr: e.target.value,
                    })
                  }
                  className="w-full px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-transparent"
                  dir="rtl"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  {t.descriptionLabel}
                </label>
                <textarea
                  value={waitlistForm.description}
                  onChange={(e) =>
                    setWaitlistForm({
                      ...waitlistForm,
                      description: e.target.value,
                    })
                  }
                  className="w-full px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-transparent"
                  rows={2}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  {t.descriptionArLabel}
                </label>
                <textarea
                  value={waitlistForm.descriptionAr}
                  onChange={(e) =>
                    setWaitlistForm({
                      ...waitlistForm,
                      descriptionAr: e.target.value,
                    })
                  }
                  className="w-full px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-transparent"
                  rows={2}
                  dir="rtl"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  {t.categoryLabel}
                </label>
                <select
                  value={waitlistForm.category}
                  onChange={(e) =>
                    setWaitlistForm({
                      ...waitlistForm,
                      category: e.target.value,
                    })
                  }
                  className="w-full px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-transparent"
                >
                  {CATEGORIES.map((cat) => (
                    <option key={cat.value} value={cat.value}>
                      {isAr ? cat.labelAr : cat.label}
                    </option>
                  ))}
                </select>
              </div>

              <div className="flex items-center gap-3">
                <input
                  type="checkbox"
                  id="isPublicEdit"
                  checked={waitlistForm.isPublic}
                  onChange={(e) =>
                    setWaitlistForm({
                      ...waitlistForm,
                      isPublic: e.target.checked,
                    })
                  }
                  className="w-4 h-4 text-brand-green border-slate-300 rounded focus:ring-brand-green"
                />
                <label
                  htmlFor="isPublicEdit"
                  className="text-sm text-slate-700"
                >
                  {t.isPublicLabel}
                </label>
              </div>

              <div className="flex gap-3 pt-4">
                <button
                  type="button"
                  onClick={() => {
                    setShowEditModal(false);
                    setSelectedWaitlist(null);
                  }}
                  className="flex-1 px-4 py-2.5 border border-slate-200 text-slate-700 rounded-xl hover:bg-slate-50 transition-colors font-medium"
                >
                  {t.cancel}
                </button>
                <button
                  type="submit"
                  disabled={submitting || !!success}
                  className="flex-1 px-4 py-2.5 bg-brand-green text-white rounded-xl hover:bg-brand-greenHover disabled:opacity-50 transition-colors font-semibold"
                >
                  {submitting ? (
                    <RefreshCcw className="w-5 h-5 animate-spin mx-auto" />
                  ) : (
                    t.save
                  )}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Delete Confirmation Modal */}
      {showDeleteConfirm && (
        <div className="fixed inset-0 bg-slate-900/20 backdrop-blur-sm flex items-center justify-center z-[100] p-4">
          <div
            className="bg-white rounded-2xl shadow-2xl max-w-md w-full overflow-hidden border border-slate-200"
            dir={isAr ? "rtl" : "ltr"}
          >
            <div className="p-6 text-center">
              <div className="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <Trash2 className="w-6 h-6 text-red-600" />
              </div>
              <h3 className="text-lg font-bold text-slate-900 mb-2">
                {t.deleteConfirmTitle}
              </h3>
              <p className="text-slate-500 mb-6">{t.deleteConfirmMessage}</p>
              <div className="flex gap-3">
                <button
                  onClick={() => setShowDeleteConfirm(null)}
                  className="flex-1 px-4 py-2.5 border border-slate-200 text-slate-700 rounded-xl hover:bg-slate-50 transition-colors font-medium"
                >
                  {t.cancel}
                </button>
                <button
                  onClick={() => handleDeleteWaitlist(showDeleteConfirm)}
                  disabled={submitting}
                  className="flex-1 px-4 py-2.5 bg-red-600 text-white rounded-xl hover:bg-red-700 disabled:opacity-50 transition-colors font-semibold"
                >
                  {submitting ? (
                    <RefreshCcw className="w-5 h-5 animate-spin mx-auto" />
                  ) : (
                    t.delete
                  )}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
