"use client";

import { useState, useEffect, useMemo } from "react";
import {
  Plus,
  Trash2,
  Edit,
  Users,
  Eye,
  EyeOff,
  RefreshCcw,
  Download,
  ChevronLeft,
  X,
  Check,
  ClipboardList,
  Phone,
  Mail,
  Calendar,
  Search,
  UserPlus,
  Tag,
} from "lucide-react";

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

const CATEGORIES = [
  {
    value: "product",
    label: "Product Release",
    color: "bg-purple-100 text-purple-700",
  },
  {
    value: "feature",
    label: "New Feature",
    color: "bg-blue-100 text-blue-700",
  },
  { value: "service", label: "Service", color: "bg-green-100 text-green-700" },
  { value: "event", label: "Event", color: "bg-amber-100 text-amber-700" },
  { value: "help", label: "Help/Support", color: "bg-red-100 text-red-700" },
  { value: "general", label: "General", color: "bg-gray-100 text-gray-700" },
];

interface Signup {
  id: string;
  name: string;
  email: string;
  mobile: string;
  notes: string | null;
  addedBy: string | null;
  createdAt: string;
  userId: string | null;
  user?: {
    id: string;
    name: string;
    email: string;
    companyName: string | null;
  } | null;
}

interface User {
  id: string;
  role: string;
}

export default function WaitlistsManagement({ user }: { user: User }) {
  const [waitlists, setWaitlists] = useState<Waitlist[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isCreating, setIsCreating] = useState(false);
  const [isEditing, setIsEditing] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [togglingId, setTogglingId] = useState<string | null>(null);
  const [deletingId, setDeletingId] = useState<string | null>(null);

  // Signups view state
  const [viewingSignups, setViewingSignups] = useState<string | null>(null);
  const [signups, setSignups] = useState<Signup[]>([]);
  const [signupsLoading, setSignupsLoading] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");

  const [formData, setFormData] = useState({
    title: "",
    titleAr: "",
    description: "",
    descriptionAr: "",
    category: "general",
    isActive: true,
  });

  // Add User Modal State
  const [isAddingUser, setIsAddingUser] = useState(false);
  const [addingUserSubmitting, setAddingUserSubmitting] = useState(false);
  const [addUserForm, setAddUserForm] = useState({
    name: "",
    email: "",
    mobile: "",
    notes: "",
  });
  const [addUserError, setAddUserError] = useState<string | null>(null);

  const fetchWaitlists = async () => {
    try {
      const response = await fetch(
        "/api/staff/dashboard/waitlists?includeInactive=true",
        {
          credentials: "include",
        },
      );
      if (response.ok) {
        const data = await response.json();
        setWaitlists(data.waitlists || []);
        setError(null);
      } else {
        const maybeError = await response.json().catch(() => null);
        setError(maybeError?.error || "Failed to load waitlists");
      }
    } catch (err) {
      console.error("Failed to fetch waitlists:", err);
      setError("Failed to load waitlists. Please try refreshing.");
    } finally {
      setLoading(false);
    }
  };

  const fetchSignups = async (waitlistId: string) => {
    setSignupsLoading(true);
    try {
      const response = await fetch(
        `/api/staff/dashboard/waitlists/${waitlistId}/signups?limit=200`,
        { credentials: "include" },
      );
      if (response.ok) {
        const data = await response.json();
        setSignups(data.signups || []);
      } else {
        setSignups([]);
      }
    } catch (err) {
      console.error("Failed to fetch signups:", err);
      setSignups([]);
    } finally {
      setSignupsLoading(false);
    }
  };

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

  useEffect(() => {
    if (viewingSignups) {
      fetchSignups(viewingSignups);
    }
  }, [viewingSignups]);

  const stats = useMemo(() => {
    const active = waitlists.filter((w) => w.isActive).length;
    const totalSignups = waitlists.reduce((sum, w) => sum + w.signupCount, 0);
    return { active, total: waitlists.length, totalSignups };
  }, [waitlists]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setSubmitting(true);

    try {
      const url = isEditing
        ? `/api/staff/dashboard/waitlists/${isEditing}`
        : "/api/staff/dashboard/waitlists";
      const method = isEditing ? "PATCH" : "POST";

      const response = await fetch(url, {
        method,
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      });

      if (response.ok) {
        setIsCreating(false);
        setIsEditing(null);
        setFormData({
          title: "",
          titleAr: "",
          description: "",
          descriptionAr: "",
          category: "general",
          isActive: true,
        });
        fetchWaitlists();
      } else {
        const data = await response.json().catch(() => null);
        setError(data?.error || "Failed to save waitlist");
      }
    } catch (err) {
      console.error("Submit error:", err);
      setError("Network error. Please try again.");
    } finally {
      setSubmitting(false);
    }
  };

  const handleToggle = async (id: string, currentState: boolean) => {
    setTogglingId(id);
    try {
      const response = await fetch(`/api/staff/dashboard/waitlists/${id}`, {
        method: "PATCH",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ isActive: !currentState }),
      });

      if (response.ok) {
        setWaitlists((prev) =>
          prev.map((w) =>
            w.id === id ? { ...w, isActive: !currentState } : w,
          ),
        );
      }
    } catch (err) {
      console.error("Toggle error:", err);
    } finally {
      setTogglingId(null);
    }
  };

  const handleDelete = async (id: string) => {
    if (
      !confirm(
        "Are you sure you want to delete this waitlist? All signups will be removed.",
      )
    ) {
      return;
    }

    setDeletingId(id);
    try {
      const response = await fetch(`/api/staff/dashboard/waitlists/${id}`, {
        method: "DELETE",
        credentials: "include",
      });

      if (response.ok) {
        setWaitlists((prev) => prev.filter((w) => w.id !== id));
      }
    } catch (err) {
      console.error("Delete error:", err);
    } finally {
      setDeletingId(null);
    }
  };

  const handleRemoveSignup = async (signupId: string) => {
    if (!viewingSignups) return;

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

      if (response.ok) {
        setSignups((prev) => prev.filter((s) => s.id !== signupId));
        // Update count in waitlists
        setWaitlists((prev) =>
          prev.map((w) =>
            w.id === viewingSignups
              ? { ...w, signupCount: w.signupCount - 1 }
              : w,
          ),
        );
      }
    } catch (err) {
      console.error("Remove signup error:", err);
    }
  };

  const handleEdit = (waitlist: Waitlist) => {
    setFormData({
      title: waitlist.title,
      titleAr: waitlist.titleAr || "",
      description: waitlist.description || "",
      descriptionAr: waitlist.descriptionAr || "",
      category: waitlist.category || "general",
      isActive: waitlist.isActive,
    });
    setIsEditing(waitlist.id);
    setIsCreating(true);
  };

  const handleAddUser = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!viewingSignups) return;

    setAddUserError(null);
    setAddingUserSubmitting(true);

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

      const data = await response.json();

      if (response.ok) {
        // Add the new signup to the list
        setSignups((prev) => [
          {
            ...data.signup,
            notes: addUserForm.notes || null,
            addedBy: user.id,
            userId: null,
          },
          ...prev,
        ]);
        // Update signup count
        setWaitlists((prev) =>
          prev.map((w) =>
            w.id === viewingSignups
              ? { ...w, signupCount: w.signupCount + 1 }
              : w,
          ),
        );
        // Reset form and close modal
        setAddUserForm({ name: "", email: "", mobile: "", notes: "" });
        setIsAddingUser(false);
      } else {
        setAddUserError(data.error || "Failed to add user");
      }
    } catch (err) {
      console.error("Add user error:", err);
      setAddUserError("Network error. Please try again.");
    } finally {
      setAddingUserSubmitting(false);
    }
  };

  const exportToCsv = () => {
    if (signups.length === 0) return;

    const headers = ["Name", "Email", "Mobile", "Signed Up", "User Account"];
    const rows = signups.map((s) => [
      s.name,
      s.email,
      s.mobile,
      new Date(s.createdAt).toLocaleString(),
      s.user?.companyName || "N/A",
    ]);

    const csv = [
      headers.join(","),
      ...rows.map((r) => r.map((c) => `"${c}"`).join(",")),
    ].join("\n");

    const blob = new Blob([csv], { type: "text/csv" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `waitlist-signups-${viewingSignups}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const filteredSignups = useMemo(() => {
    if (!searchQuery) return signups;
    const q = searchQuery.toLowerCase();
    return signups.filter(
      (s) =>
        s.name.toLowerCase().includes(q) ||
        s.email.toLowerCase().includes(q) ||
        s.mobile.includes(q),
    );
  }, [signups, searchQuery]);

  const currentWaitlist = viewingSignups
    ? waitlists.find((w) => w.id === viewingSignups)
    : null;

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

  // Signups View
  if (viewingSignups && currentWaitlist) {
    return (
      <div className="p-6 space-y-6">
        {/* Header */}
        <div className="flex items-center gap-4">
          <button
            onClick={() => {
              setViewingSignups(null);
              setSignups([]);
              setSearchQuery("");
            }}
            className="p-2 rounded-lg hover:bg-gray-100 transition-colors"
          >
            <ChevronLeft className="w-5 h-5" />
          </button>
          <div className="flex-1">
            <h1 className="text-2xl font-bold text-gray-900">
              {currentWaitlist.title}
            </h1>
            <p className="text-sm text-gray-500">
              {currentWaitlist.signupCount} signups
            </p>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={() => {
                setAddUserForm({ name: "", email: "", mobile: "", notes: "" });
                setAddUserError(null);
                setIsAddingUser(true);
              }}
              className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
            >
              <UserPlus className="w-4 h-4" />
              Add User
            </button>
            <button
              onClick={exportToCsv}
              disabled={signups.length === 0}
              className="flex items-center gap-2 px-4 py-2 bg-brand-green text-white rounded-lg hover:bg-brand-greenHover disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              <Download className="w-4 h-4" />
              Export CSV
            </button>
          </div>
        </div>

        {/* Search */}
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
          <input
            type="text"
            placeholder="Search by name, email, or mobile..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full pl-10 pr-4 py-3 border border-gray-200 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-transparent"
          />
        </div>

        {/* Signups Table */}
        {signupsLoading ? (
          <div className="flex items-center justify-center py-12">
            <RefreshCcw className="w-6 h-6 animate-spin text-gray-400" />
          </div>
        ) : filteredSignups.length === 0 ? (
          <div className="text-center py-12 bg-gray-50 rounded-xl">
            <Users className="w-12 h-12 text-gray-300 mx-auto mb-3" />
            <p className="text-gray-500">No signups yet</p>
          </div>
        ) : (
          <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
            <table className="w-full">
              <thead className="bg-gray-50 border-b border-gray-200">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-gray-500 uppercase">
                    Name
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-gray-500 uppercase">
                    Email
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-gray-500 uppercase">
                    Mobile
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-gray-500 uppercase">
                    Signed Up
                  </th>
                  <th className="px-4 py-3 text-right text-xs font-semibold text-gray-500 uppercase">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {filteredSignups.map((signup) => (
                  <tr key={signup.id} className="hover:bg-gray-50">
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-2">
                        <div className="w-8 h-8 rounded-full bg-brand-green/10 flex items-center justify-center">
                          <span className="text-sm font-semibold text-brand-green">
                            {signup.name.charAt(0).toUpperCase()}
                          </span>
                        </div>
                        <span className="font-medium text-gray-900">
                          {signup.name}
                        </span>
                      </div>
                    </td>
                    <td className="px-4 py-3">
                      <a
                        href={`mailto:${signup.email}`}
                        className="flex items-center gap-1.5 text-sm text-gray-600 hover:text-brand-green"
                      >
                        <Mail className="w-4 h-4" />
                        {signup.email}
                      </a>
                    </td>
                    <td className="px-4 py-3">
                      <a
                        href={`tel:${signup.mobile}`}
                        className="flex items-center gap-1.5 text-sm text-gray-600 hover:text-brand-green"
                      >
                        <Phone className="w-4 h-4" />
                        {signup.mobile}
                      </a>
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-500">
                      {new Date(signup.createdAt).toLocaleDateString()}
                    </td>
                    <td className="px-4 py-3 text-right">
                      <button
                        onClick={() => handleRemoveSignup(signup.id)}
                        className="p-1.5 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors"
                        title="Remove signup"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {/* Add User Modal */}
        {isAddingUser && (
          <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-2xl shadow-xl max-w-md w-full max-h-[90vh] overflow-y-auto">
              <div className="flex items-center justify-between p-4 border-b border-gray-200">
                <h2 className="text-lg font-bold text-gray-900">
                  Add User to Waitlist
                </h2>
                <button
                  onClick={() => setIsAddingUser(false)}
                  className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>

              <form onSubmit={handleAddUser} className="p-4 space-y-4">
                {addUserError && (
                  <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg text-sm">
                    {addUserError}
                  </div>
                )}

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

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

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

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Notes (optional)
                  </label>
                  <textarea
                    value={addUserForm.notes}
                    onChange={(e) =>
                      setAddUserForm({ ...addUserForm, notes: e.target.value })
                    }
                    rows={2}
                    className="w-full px-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent"
                    placeholder="Any additional notes about this signup..."
                  />
                </div>

                <div className="flex gap-3 pt-4 border-t border-gray-200">
                  <button
                    type="button"
                    onClick={() => setIsAddingUser(false)}
                    className="flex-1 px-4 py-2 border border-gray-200 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    disabled={addingUserSubmitting}
                    className="flex-1 px-4 py-2 bg-brand-green text-white rounded-lg hover:bg-brand-greenHover disabled:opacity-50 transition-colors"
                  >
                    {addingUserSubmitting ? "Adding..." : "Add User"}
                  </button>
                </div>
              </form>
            </div>
          </div>
        )}
      </div>
    );
  }

  // Main Waitlists View
  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Waitlists</h1>
          <p className="text-sm text-gray-500 mt-1">
            Manage waitlists and view signups
          </p>
        </div>
        <button
          onClick={() => {
            setFormData({
              title: "",
              titleAr: "",
              description: "",
              descriptionAr: "",
              category: "general",
              isActive: true,
            });
            setIsEditing(null);
            setIsCreating(true);
          }}
          className="flex items-center gap-2 px-4 py-2 bg-brand-green text-white rounded-lg hover:bg-brand-greenHover transition-colors"
        >
          <Plus className="w-4 h-4" />
          New Waitlist
        </button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-3 gap-4">
        <div className="bg-white rounded-xl border border-gray-200 p-4">
          <p className="text-sm text-gray-500">Total Waitlists</p>
          <p className="text-2xl font-bold text-gray-900">{stats.total}</p>
        </div>
        <div className="bg-white rounded-xl border border-gray-200 p-4">
          <p className="text-sm text-gray-500">Active</p>
          <p className="text-2xl font-bold text-green-600">{stats.active}</p>
        </div>
        <div className="bg-white rounded-xl border border-gray-200 p-4">
          <p className="text-sm text-gray-500">Total Signups</p>
          <p className="text-2xl font-bold text-blue-600">
            {stats.totalSignups}
          </p>
        </div>
      </div>

      {/* Error */}
      {error && (
        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg">
          {error}
        </div>
      )}

      {/* Create/Edit Modal */}
      {isCreating && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-xl max-w-lg w-full max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between p-4 border-b border-gray-200">
              <h2 className="text-lg font-bold text-gray-900">
                {isEditing ? "Edit Waitlist" : "Create Waitlist"}
              </h2>
              <button
                onClick={() => {
                  setIsCreating(false);
                  setIsEditing(null);
                }}
                className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <form onSubmit={handleSubmit} className="p-4 space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Title (English) *
                </label>
                <input
                  type="text"
                  required
                  value={formData.title}
                  onChange={(e) =>
                    setFormData({ ...formData, title: e.target.value })
                  }
                  className="w-full px-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent"
                  placeholder="e.g., AI Voice Agent Beta Access"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Title (Arabic)
                </label>
                <input
                  type="text"
                  dir="rtl"
                  value={formData.titleAr}
                  onChange={(e) =>
                    setFormData({ ...formData, titleAr: e.target.value })
                  }
                  className="w-full px-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent"
                  placeholder="العنوان بالعربية"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Description (English)
                </label>
                <textarea
                  value={formData.description}
                  onChange={(e) =>
                    setFormData({ ...formData, description: e.target.value })
                  }
                  rows={3}
                  className="w-full px-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent"
                  placeholder="Brief description of this waitlist..."
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Description (Arabic)
                </label>
                <textarea
                  dir="rtl"
                  value={formData.descriptionAr}
                  onChange={(e) =>
                    setFormData({ ...formData, descriptionAr: e.target.value })
                  }
                  rows={3}
                  className="w-full px-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent"
                  placeholder="الوصف بالعربية..."
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Category *
                </label>
                <select
                  value={formData.category}
                  onChange={(e) =>
                    setFormData({ ...formData, category: e.target.value })
                  }
                  className="w-full px-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent"
                >
                  {CATEGORIES.map((cat) => (
                    <option key={cat.value} value={cat.value}>
                      {cat.label}
                    </option>
                  ))}
                </select>
              </div>

              <label className="flex items-center gap-3">
                <input
                  type="checkbox"
                  checked={formData.isActive}
                  onChange={(e) =>
                    setFormData({ ...formData, isActive: e.target.checked })
                  }
                  className="w-5 h-5 rounded border-gray-300 text-brand-green focus:ring-brand-green"
                />
                <span className="text-sm font-medium text-gray-700">
                  Active (visible to users)
                </span>
              </label>

              <div className="flex gap-3 pt-4 border-t border-gray-200">
                <button
                  type="button"
                  onClick={() => {
                    setIsCreating(false);
                    setIsEditing(null);
                  }}
                  className="flex-1 px-4 py-2 border border-gray-200 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={submitting}
                  className="flex-1 px-4 py-2 bg-brand-green text-white rounded-lg hover:bg-brand-greenHover disabled:opacity-50 transition-colors"
                >
                  {submitting ? "Saving..." : isEditing ? "Update" : "Create"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Waitlists List */}
      {waitlists.length === 0 ? (
        <div className="text-center py-12 bg-gray-50 rounded-xl">
          <ClipboardList className="w-12 h-12 text-gray-300 mx-auto mb-3" />
          <p className="text-gray-500">No waitlists yet</p>
          <p className="text-sm text-gray-400 mt-1">
            Create your first waitlist to get started
          </p>
        </div>
      ) : (
        <div className="space-y-4">
          {waitlists.map((waitlist) => (
            <div
              key={waitlist.id}
              className="bg-white rounded-xl border border-gray-200 p-4 hover:shadow-md transition-shadow"
            >
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <div className="flex items-center gap-3 flex-wrap">
                    <h3 className="font-semibold text-gray-900">
                      {waitlist.title}
                    </h3>
                    <span
                      className={`px-2 py-0.5 rounded-full text-xs font-medium ${
                        CATEGORIES.find((c) => c.value === waitlist.category)
                          ?.color || "bg-gray-100 text-gray-700"
                      }`}
                    >
                      {CATEGORIES.find((c) => c.value === waitlist.category)
                        ?.label || "General"}
                    </span>
                    <span
                      className={`px-2 py-0.5 rounded-full text-xs font-medium ${
                        waitlist.isActive
                          ? "bg-green-100 text-green-700"
                          : "bg-gray-100 text-gray-500"
                      }`}
                    >
                      {waitlist.isActive ? "Active" : "Hidden"}
                    </span>
                  </div>
                  {waitlist.titleAr && (
                    <p className="text-sm text-gray-500 mt-0.5" dir="rtl">
                      {waitlist.titleAr}
                    </p>
                  )}
                  {waitlist.description && (
                    <p className="text-sm text-gray-600 mt-2">
                      {waitlist.description}
                    </p>
                  )}
                  <div className="flex items-center gap-4 mt-3 text-sm text-gray-500">
                    <span className="flex items-center gap-1.5">
                      <Users className="w-4 h-4" />
                      {waitlist.signupCount} signups
                    </span>
                    <span className="flex items-center gap-1.5">
                      <Calendar className="w-4 h-4" />
                      Created{" "}
                      {new Date(waitlist.createdAt).toLocaleDateString()}
                    </span>
                  </div>
                </div>

                <div className="flex items-center gap-2">
                  {/* Toggle */}
                  <button
                    onClick={() => handleToggle(waitlist.id, waitlist.isActive)}
                    disabled={togglingId === waitlist.id}
                    className={`p-2 rounded-lg transition-colors ${
                      waitlist.isActive
                        ? "text-green-600 hover:bg-green-50"
                        : "text-gray-400 hover:bg-gray-100"
                    }`}
                    title={
                      waitlist.isActive ? "Hide waitlist" : "Show waitlist"
                    }
                  >
                    {togglingId === waitlist.id ? (
                      <RefreshCcw className="w-5 h-5 animate-spin" />
                    ) : waitlist.isActive ? (
                      <Eye className="w-5 h-5" />
                    ) : (
                      <EyeOff className="w-5 h-5" />
                    )}
                  </button>

                  {/* View Signups */}
                  <button
                    onClick={() => setViewingSignups(waitlist.id)}
                    className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                    title="View signups"
                  >
                    <Users className="w-5 h-5" />
                  </button>

                  {/* Edit */}
                  <button
                    onClick={() => handleEdit(waitlist)}
                    className="p-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
                    title="Edit"
                  >
                    <Edit className="w-5 h-5" />
                  </button>

                  {/* Delete */}
                  <button
                    onClick={() => handleDelete(waitlist.id)}
                    disabled={deletingId === waitlist.id}
                    className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                    title="Delete"
                  >
                    {deletingId === waitlist.id ? (
                      <RefreshCcw className="w-5 h-5 animate-spin" />
                    ) : (
                      <Trash2 className="w-5 h-5" />
                    )}
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
