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

export default function EntriesTable() {
  const { userRole } = useAuth();
  const { darkMode } = useTheme();
  const [entries, setEntries] = useState([]);
  const [filteredEntries, setFilteredEntries] = useState([]);
  const [searchQuery, setSearchQuery] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [avgConsultTime, setAvgConsultTime] = useState(15); // Default 15 mins
  const entriesPerPage = 20;

  const [currentToken, setCurrentToken] = useState(null);
  const [previousToken, setPreviousToken] = useState(null);
  const [nextToken, setNextToken] = useState(null);
  const [missedTokens, setMissedTokens] = useState("");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // Calculate waiting time based on position in queue
  const calculateWaitTime = (tokenNumber) => {
    const bookedEntries = entries.filter(e => e.status === "booked");
    const position = bookedEntries.findIndex(e => e.tokenNumber === tokenNumber);
    return position >= 0 ? (position * avgConsultTime) : 0;
  };

  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 updateTokenInfo = (entries) => {
    if (entries.length === 0) {
      setCurrentToken(null);
      setPreviousToken(null);
      setNextToken(null);
      setMissedTokens("");
      return;
    }

    const currentIndex = entries.findIndex((entry) => entry.status === "booked");
    const current = currentIndex >= 0 ? entries[currentIndex] : null;

    setCurrentToken(current?.tokenNumber || null);
    setPreviousToken(currentIndex > 0 ? entries[currentIndex - 1]?.tokenNumber : null);
    setNextToken(currentIndex < entries.length - 1 ? entries[currentIndex + 1]?.tokenNumber : null);

    const missed = entries
      .filter((entry) => entry.status === "missed")
      .map((entry) => entry.tokenNumber)
      .join(", ");
    setMissedTokens(missed || "None");
  };

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

  useEffect(() => {
    if (userRole === "patient") return; // Don't load data if patient

    const loadData = async () => {
      try {
        const data = await getEntries();
        setEntries(data);
        setFilteredEntries(data);
        updateTokenInfo(data);

        // Load settings (avg consultation time)
        // const settings = await getSettings();
        // setAvgConsultTime(settings?.avgConsultationTime || 15);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };
    loadData();
  }, [userRole]);

  useEffect(() => {
    const filtered = entries.filter((entry) => {
      return (
        entry.patientName.toLowerCase().includes(searchQuery.toLowerCase()) ||
        entry.tokenNumber.toString().includes(searchQuery)
      );
    });
    setFilteredEntries(filtered);
    setCurrentPage(1);
  }, [searchQuery, entries]);

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

  if (loading) return <div className="text-center mt-50">
    <div className={`animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500 mx-auto`}></div>
    <p className={`mt-4 text-lg font-semibold`}>Loading...</p>
  </div>;

  if (error) return <div className="p-4 text-red-500">Error: {error}</div>;

  // Check user role and show permission message if patient
  if (userRole === "patient") {
    return (
      <div className={`min-h-screen w-full ${darkMode ? 'bg-gray-900 text-white' : 'bg-white text-black'}`}>
        <div className="flex items-center justify-center h-screen">
          <div className="text-center">
            <h1 className="text-2xl font-bold mb-4">Access Denied</h1>
            <p>You don&apos;t have permission to view this page.</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className={`min-h-screen w-full ${darkMode ? 'bg-gray-900 text-white' : 'bg-white text-black'}`}>
      <div className="sticky top-0 z-10 bg-white shadow-md mb-4">
        <Header
          currentToken={currentToken}
          previousToken={previousToken}
          nextToken={nextToken}
          missedTokens={missedTokens}
          entries={entries} // Pass the entries data
        />

      </div>
      <h1 className="text-2xl font-bold mb-4">Today&apos;s Entries</h1>
      <input
        type="text"
        placeholder="Search by token or name"
        className="mb-4 p-2 border rounded bg-white w-full max-w-sm"
        value={searchQuery}
        onChange={(e) => setSearchQuery(e.target.value)}
      />

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

          {/* Pagination */}
          <div className={`flex justify-between items-center mt-4 ${darkMode ? 'text-white' : 'text-gray-700'
            }`}>
            <button
              disabled={currentPage === 1}
              onClick={() => setCurrentPage((prev) => prev - 1)}
              className="px-3 py-1 border rounded disabled:opacity-50"
            >
              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"
            >
              Next
            </button>
          </div>
        </>
      )}
    </div>
  );
}