"use client";

import { useEffect, useState } from "react";
import { collection, getDocs, doc, updateDoc } from "firebase/firestore";
import { db } from "@/lib/firebase";

// Define a proper type for the user data
interface User {
  id: string;
  restaurant: string;
  email: string;
  phone: string;
  trialStart?: any; // Firestore timestamp
  trialEnds?: any;
  isActive: boolean;
  // add other fields as needed
}

export default function RestaurantsPage() {
  const [restaurants, setRestaurants] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");

  // Load restaurants from Firestore
  useEffect(() => {
    const loadRestaurants = async () => {
      try {
        const snap = await getDocs(collection(db, "users"));
        const data: User[] = snap.docs.map((doc) => ({
          id: doc.id,
          ...doc.data(),
        })) as User[];
        setRestaurants(data);
      } catch (error) {
        console.error("Error loading restaurants:", error);
        // Optionally show an error toast
      } finally {
        setLoading(false);
      }
    };

    loadRestaurants();
  }, []);

  // Toggle account status
  const toggleAccount = async (user: User) => {
    const originalStatus = user.isActive;
    // Optimistic update
    setRestaurants((prev) =>
      prev.map((r) => (r.id === user.id ? { ...r, isActive: !r.isActive } : r))
    );

    try {
      const endpoint = user.isActive ? "/api/admin/disableUser" : "/api/admin/enableUser";
      const response = await fetch(endpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ uid: user.id }),
      });

      if (!response.ok) throw new Error("Failed to update user in auth");

      await updateDoc(doc(db, "users", user.id), {
        isActive: !user.isActive,
      });
    } catch (error) {
      console.error("Error toggling account:", error);
      // Revert optimistic update on error
      setRestaurants((prev) =>
        prev.map((r) => (r.id === user.id ? { ...r, isActive: originalStatus } : r))
      );
      // Optionally show an error message to the user
    }
  };

  // Format date from Firestore timestamp or string
  const formatDate = (timestamp: any) => {
    if (!timestamp) return "—";
    try {
      const date = timestamp.toDate ? timestamp.toDate() : new Date(timestamp);
      return date.toLocaleDateString("en-US", {
        year: "numeric",
        month: "short",
        day: "numeric",
      });
    } catch {
      return "—";
    }
  };

  // Filter restaurants based on search term
  const filteredRestaurants = restaurants.filter((user) =>
    user.restaurant?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    user.email?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div className="min-h-screen bg-gray-50 py-8 px-4 sm:px-6 lg:px-8">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="mb-8 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <h1 className="text-3xl font-bold text-gray-900">Restaurants</h1>
          <div className="relative">
            <input
              type="text"
              placeholder="Search by name or email..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full sm:w-64 pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
            <svg
              className="absolute left-3 top-2.5 h-5 w-5 text-gray-400"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
              />
            </svg>
          </div>
        </div>

        {/* Table Card */}
        <div className="bg-white rounded-xl shadow-lg overflow-hidden border border-gray-200">
          {loading ? (
            // Skeleton loader
            <div className="animate-pulse">
              <div className="h-12 bg-gray-100" />
              {[...Array(5)].map((_, i) => (
                <div key={i} className="flex items-center p-4 border-b border-gray-100">
                  <div className="flex-1 h-6 bg-gray-200 rounded mr-4" />
                  <div className="flex-1 h-6 bg-gray-200 rounded mr-4" />
                  <div className="flex-1 h-6 bg-gray-200 rounded mr-4" />
                  <div className="flex-1 h-6 bg-gray-200 rounded mr-4" />
                  <div className="flex-1 h-6 bg-gray-200 rounded mr-4" />
                  <div className="w-24 h-6 bg-gray-200 rounded" />
                </div>
              ))}
            </div>
          ) : filteredRestaurants.length === 0 ? (
            // Empty state
            <div className="text-center py-12">
              <svg
                className="mx-auto h-12 w-12 text-gray-400"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"
                />
              </svg>
              <h3 className="mt-2 text-sm font-medium text-gray-900">No restaurants found</h3>
              <p className="mt-1 text-sm text-gray-500">
                {searchTerm ? "Try a different search term." : "Get started by adding a new restaurant."}
              </p>
            </div>
          ) : (
            // Table
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Restaurant
                    </th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Email
                    </th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Phone
                    </th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Start
                    </th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Expires
                    </th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Status
                    </th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Actions
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {filteredRestaurants.map((user) => (
                    <tr key={user.id} className="hover:bg-gray-50 transition-colors">
                      <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                        {user.restaurant}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {user.email}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {user.phone || "—"}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {formatDate(user.trialStart)}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {formatDate(user.trialEnds)}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <span
                          className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                            user.isActive
                              ? "bg-green-100 text-green-800"
                              : "bg-red-100 text-red-800"
                          }`}
                        >
                          {user.isActive ? "Active" : "Disabled"}
                        </span>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <button
                          onClick={() => toggleAccount(user)}
                          className={`inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded-md shadow-sm text-white transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 ${
                            user.isActive
                              ? "bg-red-600 hover:bg-red-700 focus:ring-red-500"
                              : "bg-green-600 hover:bg-green-700 focus:ring-green-500"
                          }`}
                        >
                          {user.isActive ? "Deactivate" : "Activate"}
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* Footer with count */}
        {!loading && filteredRestaurants.length > 0 && (
          <div className="mt-4 text-sm text-gray-500 text-right">
            Showing {filteredRestaurants.length} of {restaurants.length} restaurants
          </div>
        )}
      </div>
    </div>
  );
}