"use client";
import { useState, useEffect } from "react";
import { databases, Query } from "../lib/appwrite";
import { DATABASE_ID, COLLECTION_ID } from "../lib/api";
import { useTheme } from "../context/ThemeContext";

export default function TokenTable({ statusFilter }) {
  const { darkMode } = useTheme();
  const [entries, setEntries] = useState([]);
  const [filteredEntries, setFilteredEntries] = useState([]);
  const [searchQuery, setSearchQuery] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const entriesPerPage = 20;
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const getEntries = async () => {
    try {
      const today = new Date().toISOString().split('T')[0];
      const response = await databases.listDocuments(
        DATABASE_ID,
        COLLECTION_ID,
        [
          Query.equal('date', today),
          Query.orderAsc('tokenNumber')
        ],
        100
      );
      return response.documents;
    } catch (error) {
      console.error("Fetch error:", error);
      throw error;
    }
  };

  const updateStatus = async (entryId, newStatus) => {
    try {
      setLoading(true);
      await databases.updateDocument(
        DATABASE_ID,
        COLLECTION_ID,
        entryId,
        { status: newStatus }
      );
      const data = await getEntries();
      setEntries(data);
      applyFilters(data, searchQuery);
    } catch (error) {
      console.error("Update error:", error);
      setError(error.message);
    } finally {
      setLoading(false);
    }
  };

  const applyFilters = (data, search) => {
    let filtered = data.filter((entry) => {
      const matchesSearch = 
        entry.patientName.toLowerCase().includes(search.toLowerCase()) ||
        entry.tokenNumber.toString().includes(search);
      
      const matchesFilter = 
        statusFilter === "all" || 
        entry.status === statusFilter ||
        (statusFilter === "booked" && entry.status === "booked");
      
      return matchesSearch && matchesFilter;
    });
    setFilteredEntries(filtered);
  };

  useEffect(() => {
    const loadData = async () => {
      try {
        const data = await getEntries();
        setEntries(data);
        applyFilters(data, searchQuery);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };
    loadData();
  }, []);

  useEffect(() => {
    applyFilters(entries, searchQuery);
    setCurrentPage(1);
  }, [searchQuery, statusFilter, entries]);

  const indexOfLastEntry = currentPage * entriesPerPage;
  const indexOfFirstEntry = indexOfLastEntry - entriesPerPage;
  const currentEntries = filteredEntries.slice(indexOfFirstEntry, indexOfLastEntry);
  const totalPages = Math.ceil(filteredEntries.length / entriesPerPage);



// Handle theme loading state
if (darkMode === undefined) {
  return (
    <div className={`flex items-center justify-center min-h-[200px] ${darkMode ? 'bg-gray-900' : 'bg-white'}`}>
      <div className="text-center">
        <div className={`animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500 mx-auto ${
          darkMode === true ? 'border-gray-100' : 'border-gray-900'
        }`}></div>
        <p className={`mt-4 text-lg font-semibold ${
          darkMode === true ? 'text-gray-100' : 'text-gray-900'
        }`}>
          Loading...
        </p>
      </div>
    </div>
  );
}
if (loading) return (
  <div className={`text-center py-10 ${darkMode ? 'bg-gray-900' : 'bg-white'}`}>
    <div className={`animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 mx-auto ${
      darkMode ? 'border-gray-100' : 'border-gray-900'
    }`}></div>
    <p className={`mt-4 text-lg font-semibold ${
      darkMode ? 'text-gray-100' : 'text-gray-900'
    }`}>
      Loading...
    </p>
  </div>
);

if (error) return (
  <div className={`p-4 rounded ${darkMode ? 'bg-red-900 text-red-100' : 'bg-red-100 text-red-900'}`}>
    Error: {error}
  </div>
);

return (
  <div className={`transition-colors duration-300 ${darkMode ? 'text-gray-100' : 'text-gray-800'}`}>
    <input
      type="text"
      placeholder="Search by token or name"
      className={`mb-4 p-2 border rounded w-full max-w-sm transition-colors ${
        darkMode 
          ? 'bg-gray-800 border-gray-700 text-white placeholder-gray-400 focus:ring-blue-500 focus:border-blue-500' 
          : 'bg-white border-gray-300 placeholder-gray-500 focus:ring-blue-500 focus:border-blue-500'
      }`}
      value={searchQuery}
      onChange={(e) => setSearchQuery(e.target.value)}
    />

    {filteredEntries.length === 0 ? (
      <div className={`p-4 rounded ${darkMode ? 'bg-gray-800' : 'bg-gray-50'}`}>
        No entries found.
      </div>
    ) : (
      <>
        <div className="overflow-x-auto">
          <table className="w-full border-collapse">
            <thead className={darkMode ? "bg-gray-800" : "bg-gray-100"}>
              <tr>
                <th className={`p-3 text-left ${darkMode ? 'text-gray-200' : 'text-gray-700'}`}>Token</th>
                <th className={`p-3 text-left ${darkMode ? 'text-gray-200' : 'text-gray-700'}`}>Name</th>
                <th className={`p-3 text-left ${darkMode ? 'text-gray-200' : 'text-gray-700'}`}>Status</th>
                <th className={`p-3 text-left ${darkMode ? 'text-gray-200' : 'text-gray-700'}`}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {currentEntries.map((entry) => (
                <tr
                  key={entry.$id}
                  className={`${darkMode ? 'bg-gray-900 border-gray-700 hover:bg-gray-800' : 'bg-white border-gray-200 hover:bg-gray-50'}`}
                >
                  <td className="p-3 font-mono">{entry.tokenNumber}</td>
                  <td className="p-3">{entry.patientName}</td>
                  <td className="p-3">
                    <span
                      className={`px-2 py-1 rounded-full text-xs font-semibold ${
                        entry.status === "done"
                          ? darkMode 
                            ? "bg-green-900 text-green-100" 
                            : "bg-green-100 text-green-800"
                          : entry.status === "booked"
                            ? darkMode 
                              ? "bg-yellow-900 text-yellow-100" 
                              : "bg-yellow-100 text-yellow-800"
                            : darkMode 
                              ? "bg-red-900 text-red-100" 
                              : "bg-red-100 text-red-800"
                      }`}
                    >
                      {entry.status === "booked" ? "In-Queue" : entry.status}
                    </span>
                  </td>
                  <td className="p-3 flex gap-2">
                    {entry.status === "booked" && (
                      <>
                        <button
                          onClick={() => updateStatus(entry.$id, "done")}
                          className={`border rounded-full px-2 py-1 text-xs transition-colors ${
                            darkMode
                              ? 'border-green-400 text-green-400 hover:bg-green-900'
                              : 'border-green-600 text-green-600 hover:bg-green-50'
                          }`}
                        >
                          Done
                        </button>
                        <button
                          onClick={() => updateStatus(entry.$id, "missed")}
                          className={`border rounded-full px-2 py-1 text-xs transition-colors ${
                            darkMode
                              ? 'border-red-400 text-red-400 hover:bg-red-900'
                              : 'border-red-600 text-red-600 hover:bg-red-50'
                          }`}
                        >
                          Missed
                        </button>
                      </>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className={`flex justify-between items-center mt-4 p-2 rounded ${
          darkMode ? 'bg-gray-800' : 'bg-gray-100'
        }`}>
          <button
            disabled={currentPage === 1}
            onClick={() => setCurrentPage((prev) => prev - 1)}
            className={`px-3 py-1 border rounded disabled:opacity-50 transition-colors ${
              darkMode 
                ? 'border-gray-600 hover:bg-gray-700 disabled:hover:bg-transparent' 
                : 'border-gray-300 hover:bg-gray-200 disabled:hover:bg-transparent'
            }`}
          >
            Previous
          </button>
          <span className="text-sm">
            Page {currentPage} of {totalPages}
          </span>
          <button
            disabled={currentPage === totalPages}
            onClick={() => setCurrentPage((prev) => prev + 1)}
            className={`px-3 py-1 border rounded disabled:opacity-50 transition-colors ${
              darkMode 
                ? 'border-gray-600 hover:bg-gray-700 disabled:hover:bg-transparent' 
                : 'border-gray-300 hover:bg-gray-200 disabled:hover:bg-transparent'
            }`}
          >
            Next
          </button>
        </div>
      </>
    )}
  </div>
);
}