"use client";
import { useSearchParams } from 'next/navigation';
import { useEffect, useState, useRef  } from 'react';
import { databases, ID, Query } from "../../lib/appwrite"; // Added Query import
import { DATABASE_ID, COLLECTION_ID } from "../../lib/api";
import Header from '../../components/partials/header';
import Link from 'next/link';

export default function SingleBooked() {
  const searchParams = useSearchParams();
  const nameParam = searchParams.get('name');
  const dateParam = searchParams.get('date');

  const [appointmentDate] = useState(dateParam || new Date().toISOString().split('T')[0]);
  const [name] = useState(nameParam || '');
  const [token, setToken] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const bookingCreated = useRef(false);

  const generateTokenNumber = async (date) => {
    try {
      // Get the highest token number for the date
      const response = await databases.listDocuments(
        DATABASE_ID,
        COLLECTION_ID,
        [
          Query.equal('date', date),
          Query.orderDesc('tokenNumber'),
          Query.limit(1)
        ]
      );
      
      const lastToken = response.documents[0]?.tokenNumber || "000";
      return (parseInt(lastToken) + 1).toString().padStart(3, '0');
    } catch (error) {
      console.error("Token generation error:", error);
      return "001"; // Fallback token number
    }
  };

  const createBooking = async () => {
    if (bookingCreated.current) return; // Prevent duplicate calls
    
    try {
      bookingCreated.current = true; // Mark as created
      setLoading(true);
      setError(null);

      const generatedToken = await generateTokenNumber(appointmentDate);

      await databases.createDocument(
        DATABASE_ID,
        COLLECTION_ID,
        ID.unique(),
        {
          tokenNumber: generatedToken,
          date: appointmentDate,
          patientName: name,
          status: "booked",
          bookedBy: "staff",
          patientId: ID.unique(),
        }
      );

      setToken(generatedToken);
    } catch (error) {
      console.error("Booking error:", error);
      setError(error.message);
      bookingCreated.current = false; // Reset on error to allow retry
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (name && appointmentDate) {
      createBooking();
    }
  }, [name, appointmentDate]);

  return (
    <div className="flex h-screen overflow-hidden">
      <div className="relative flex flex-col flex-1 overflow-x-hidden overflow-y-auto">
        <div className="flex bg-white dark:bg-gray-800 shadow-sm sticky top-0 z-50 w-full">
          <Header />
        </div>

        <main>
          <div className="p-4 mx-auto max-w-[--breakpoint-2xl] md:p-6">
            {error && (
              <div className="mb-4 p-4 bg-red-100 text-red-700 rounded">
                {error}
              </div>
            )}

            <div className="text-center my-10">
              <h2 className="text-xl mb-2">Staff Booking</h2>
              <p className="text-2xl font-bold mb-4">{name || 'Staff Booking'}</p>

              <h2 className="text-xl mb-2">Token Number:</h2>
              <p className="text-6xl text-blue-700">
                {loading ? 'Generating...' : token || '---'}
              </p>
            </div>

            <div className="flex flex-col gap-4 md:flex-row w-full max-w-lg mx-auto">
              <Link href="/pages/StaffBooking" className="w-full">
                <button className="rounded-lg bg-blue-700 px-5 py-3.5 text-sm font-medium text-white hover:bg-blue-800 w-full">
                  Book Another
                </button>
              </Link>
              <Link href="/pages/entries" className="w-full">
                <button className="rounded-lg bg-white px-5 py-3.5 text-sm font-medium text-gray-700 border border-gray-300 hover:bg-gray-100 w-full">
                  View All Entries
                </button>
              </Link>
            </div>

            <p className="text-center mt-6 text-sm text-gray-600">
              Staff token booking system
            </p>
          </div>
        </main>
      </div>
    </div>
  );
}