import React, { useEffect, useRef, useState } from 'react';

interface HistoryItem {
  id: string;
  title: string;
  date: string;
  status: 'Completed' | 'Pending';
}

const TEST_DATA: HistoryItem[] = [
  { id: '1', title: 'General Well-being Check', date: '2025/02/01', status: 'Completed' },
  { id: '2', title: 'Symptom Severity Scale', date: '2025/02/05', status: 'Completed' },
  { id: '3', title: 'Daily Activity Log', date: '2025/02/06', status: 'Completed' },
  { id: '4', title: 'Pain Assessment', date: '2025/02/07', status: 'Pending' },
  { id: '5', title: 'Sleep Quality Survey', date: '2025/02/07', status: 'Pending' },
  { id: '6', title: 'Dietary Intake Record', date: '2025/02/08', status: 'Pending' },
  { id: '7', title: 'Mental Health Screening', date: '2025/02/10', status: 'Pending' },
  { id: '8', title: 'Medication Adherence', date: '2025/02/12', status: 'Pending' },
  { id: '9', title: 'Follow-up Consultation', date: '2025/02/15', status: 'Pending' },
  { id: '10', title: 'Monthly Health Summary', date: '2025/02/28', status: 'Pending' },
];

interface TestHistoryProps {
  testMode?: boolean;
}

const TestHistory: React.FC<TestHistoryProps> = ({ testMode = true }) => {
  const [items, setItems] = useState<HistoryItem[]>([]);
  const [showTopHint, setShowTopHint] = useState(false);
  const [showBottomHint, setShowBottomHint] = useState(true); // Default to true assuming content overflows
  
  const listRef = useRef<HTMLDivElement>(null);
  const topSentinelRef = useRef<HTMLDivElement>(null);
  const bottomSentinelRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (testMode) {
      setItems(TEST_DATA);
    } else {
      // Future: Fetch real PROMs data here
      setItems([]);
    }
  }, [testMode]);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.target === topSentinelRef.current) {
            // If top sentinel is visible, HIDE top hint (we are at the top)
            setShowTopHint(!entry.isIntersecting);
          }
          if (entry.target === bottomSentinelRef.current) {
            // If bottom sentinel is visible, HIDE bottom hint (we are at the bottom)
            setShowBottomHint(!entry.isIntersecting);
          }
        });
      },
      { 
        root: listRef.current,
        threshold: 0.1 // Trigger as soon as even a pixel is visible
      }
    );

    if (topSentinelRef.current) observer.observe(topSentinelRef.current);
    if (bottomSentinelRef.current) observer.observe(bottomSentinelRef.current);

    return () => observer.disconnect();
  }, [items]); // Re-run when items change

  return (
    <div className="flex justify-center items-center min-h-screen bg-[#fffbef] p-4 font-[Poppins]">
      {/* .wrapper translation */}
      <div className="w-full max-w-md bg-[#8ec0ac] text-[#fffbef] rounded-2xl shadow-xl flex flex-col items-center gap-4 p-8 relative">
        
        {/* Title */}
        <h1 className="text-2xl font-bold text-center">
          Your Health Journey
        </h1>

        {/* Description */}
        <p className="text-sm font-light text-center leading-relaxed opacity-90">
          A professional record of your care. These questionnaires help us tailor your treatment specifically for you.
        </p>

        {/* .list-wrapper */}
        <div className="relative w-full mt-4">
          
          {/* Top Gradient Hint */}
          <div 
            className={`absolute top-0 left-0 w-full h-8 bg-gradient-to-b from-[#8ec0ac] to-transparent z-10 transition-opacity duration-300 pointer-events-none
            ${showTopHint ? 'opacity-100' : 'opacity-0'}`}
          />

          {/* .list (Scrollable Area) */}
          <div 
            ref={listRef}
            className="flex flex-col gap-3 overflow-y-auto max-h-[60vh] pr-2 -mr-2 scrollbar-thin scrollbar-thumb-white/20 scrollbar-track-transparent"
          >
            {/* Top Sentinel for Observer */}
            <div ref={topSentinelRef} className="h-[1px] w-full shrink-0" />

            {items.map((item) => (
              <div 
                key={item.id}
                className="w-full p-4 bg-[#fffbef] text-[#8ec0ac] rounded-xl flex flex-col gap-1 shadow-sm transition-transform hover:scale-[1.02] cursor-pointer"
              >
                <div className="flex justify-between items-center">
                  <span className="font-semibold text-lg">{item.title}</span>
                  {item.status === 'Completed' && (
                     <span className="text-xs bg-[#8ec0ac]/20 text-[#8ec0ac] px-2 py-0.5 rounded-full font-bold">✓</span>
                  )}
                </div>
                <span className="text-xs font-light opacity-70 tracking-wide">
                  {item.date}
                </span>
              </div>
            ))}

             {/* Bottom Sentinel for Observer */}
             <div ref={bottomSentinelRef} className="h-[1px] w-full shrink-0" />
          </div>

          {/* Bottom Gradient Hint */}
          <div 
            className={`absolute bottom-0 left-0 w-full h-8 bg-gradient-to-t from-[#8ec0ac] to-transparent z-10 transition-opacity duration-300 pointer-events-none
            ${showBottomHint ? 'opacity-100' : 'opacity-0'}`}
          />
        </div>
        
        {!testMode && items.length === 0 && (
            <div className="text-center py-10 opacity-60 italic">
                No questionnaires pending.
            </div>
        )}

      </div>
    </div>
  );
};

export default TestHistory;