
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Trash2, Music, Volume2, AlertCircle, Play, Pause, Bell, Settings2 } from 'lucide-react';
import { GoogleGenAI } from '@google/genai';
import { ScheduleItem, Quote } from './types';
import Clock from './components/Clock';
import ScheduleForm from './components/ScheduleForm';

const App: React.FC = () => {
  const [schedules, setSchedules] = useState<ScheduleItem[]>([]);
  const [isPlaying, setIsPlaying] = useState<string | null>(null); // ID of currently playing schedule
  const [systemActive, setSystemActive] = useState(false);
  const [quote, setQuote] = useState<Quote | null>(null);
  
  const audioRef = useRef<HTMLAudioElement | null>(null);
  const playedTodayRef = useRef<Set<string>>(new Set()); // Tracks IDs played today

  // Gemini to get a motivating quote for the school
  const fetchQuote = useCallback(async () => {
    try {
      const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
      const response = await ai.models.generateContent({
        model: 'gemini-3-flash-preview',
        contents: 'Give me one short motivational quote for school students and teachers in JSON format: { "text": "...", "author": "..." }',
        config: { responseMimeType: 'application/json' }
      });
      const data = JSON.parse(response.text || '{}');
      if (data.text) setQuote(data);
    } catch (error) {
      console.error("Failed to fetch quote", error);
      setQuote({ text: "Education is the passport to the future.", author: "Malcolm X" });
    }
  }, []);

  useEffect(() => {
    fetchQuote();
  }, [fetchQuote]);

  // Handle music playback
  const playSong = (item: ScheduleItem) => {
    if (!item.objectUrl) return;
    
    if (audioRef.current) {
      audioRef.current.pause();
    }
    
    const audio = new Audio(item.objectUrl);
    audioRef.current = audio;
    setIsPlaying(item.id);
    audio.play().catch(e => {
      console.error("Playback failed", e);
      alert("Error: Please make sure 'System Active' is enabled to allow autoplay.");
    });
    
    audio.onended = () => {
      setIsPlaying(null);
    };
  };

  // Main tick loop - checks every second
  useEffect(() => {
    if (!systemActive) return;

    const interval = setInterval(() => {
      const now = new Date();
      const currentHHmm = now.getHours().toString().padStart(2, '0') + ':' + 
                          now.getMinutes().toString().padStart(2, '0');
      const dayKey = now.toDateString();

      // Reset played set if new day
      if (!playedTodayRef.current.has(dayKey + '_marker')) {
        playedTodayRef.current.clear();
        playedTodayRef.current.add(dayKey + '_marker');
      }

      schedules.forEach(item => {
        const itemPlayedKey = `${dayKey}_${item.id}`;
        if (item.time === currentHHmm && !playedTodayRef.current.has(itemPlayedKey)) {
          console.log(`Triggering bell: ${item.songName} at ${item.time}`);
          playSong(item);
          playedTodayRef.current.add(itemPlayedKey);
        }
      });
    }, 1000);

    return () => clearInterval(interval);
  }, [systemActive, schedules]);

  const handleAddSchedule = (data: Omit<ScheduleItem, 'id' | 'isActive'>) => {
    const objectUrl = URL.createObjectURL(data.songFile!);
    const newItem: ScheduleItem = {
      ...data,
      id: Math.random().toString(36).substr(2, 9),
      isActive: true,
      objectUrl
    };
    setSchedules(prev => [...prev].sort((a, b) => a.time.localeCompare(b.time)));
    setSchedules(prev => [...prev, newItem].sort((a, b) => a.time.localeCompare(b.time)));
  };

  const removeSchedule = (id: string) => {
    setSchedules(prev => {
      const item = prev.find(i => i.id === id);
      if (item?.objectUrl) URL.revokeObjectURL(item.objectUrl);
      return prev.filter(i => i.id !== id);
    });
  };

  const toggleSystem = () => {
    setSystemActive(!systemActive);
    // User interaction required to unlock audio context in browsers
    if (!systemActive) {
      const audio = new Audio();
      audio.play().catch(() => {}); // silent play to unlock
    }
  };

  return (
    <div className="min-h-screen pb-20">
      {/* Header Section */}
      <header className="bg-indigo-600 text-white pt-10 pb-20 px-4 md:px-8">
        <div className="max-w-5xl mx-auto flex flex-col md:flex-row justify-between items-center gap-6">
          <div className="space-y-2 text-center md:text-left">
            <div className="flex items-center justify-center md:justify-start gap-3">
              <div className="p-2 bg-white/20 rounded-xl backdrop-blur-sm">
                <Bell className="w-8 h-8" />
              </div>
              <h1 className="text-3xl font-extrabold tracking-tight">School Bell Pro</h1>
            </div>
            <p className="text-indigo-100 max-w-md">Automate your class transition music effortlessly. Set it once, let it run every day.</p>
          </div>
          <Clock />
        </div>
      </header>

      {/* Main Content */}
      <main className="max-w-5xl mx-auto px-4 -mt-10 space-y-8">
        {/* System Status Bar */}
        <div className={`flex flex-col md:flex-row items-center justify-between p-4 rounded-2xl border transition-all ${
          systemActive ? 'bg-emerald-50 border-emerald-100' : 'bg-amber-50 border-amber-100'
        }`}>
          <div className="flex items-center gap-4 mb-4 md:mb-0">
            <div className={`p-3 rounded-full ${systemActive ? 'bg-emerald-500' : 'bg-amber-500'} text-white animate-pulse`}>
              <Settings2 className="w-6 h-6" />
            </div>
            <div>
              <p className={`font-bold ${systemActive ? 'text-emerald-800' : 'text-amber-800'}`}>
                {systemActive ? 'Automatic System Online' : 'System Paused'}
              </p>
              <p className="text-sm text-slate-500">
                {systemActive ? 'Bells will ring automatically at scheduled times.' : 'Enable system to allow automatic playback.'}
              </p>
            </div>
          </div>
          <button
            onClick={toggleSystem}
            className={`px-8 py-3 rounded-xl font-bold shadow-lg transition-all active:scale-95 ${
              systemActive 
                ? 'bg-white text-emerald-600 border border-emerald-200 hover:bg-emerald-100' 
                : 'bg-indigo-600 text-white hover:bg-indigo-700 shadow-indigo-200'
            }`}
          >
            {systemActive ? 'Pause System' : 'Activate System'}
          </button>
        </div>

        {/* Gemini Quote */}
        {quote && (
          <div className="bg-white p-6 rounded-2xl shadow-sm border border-slate-100 relative overflow-hidden group">
            <div className="absolute top-0 right-0 w-32 h-32 bg-indigo-50 -mr-16 -mt-16 rounded-full opacity-50 transition-transform group-hover:scale-110"></div>
            <div className="relative z-10 flex flex-col items-center text-center">
              <p className="text-xl font-medium text-slate-700 italic mb-3">"{quote.text}"</p>
              <p className="text-indigo-600 font-bold tracking-wider">— {quote.author}</p>
            </div>
          </div>
        )}

        {/* Action Panel */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          <div className="lg:col-span-1 space-y-6">
            <ScheduleForm onAdd={handleAddSchedule} />
            <div className="bg-blue-50 p-6 rounded-2xl border border-blue-100 space-y-3">
              <div className="flex items-center gap-2 text-blue-800 font-bold">
                <AlertCircle className="w-5 h-5" />
                <h3>Important Tips</h3>
              </div>
              <ul className="text-sm text-blue-700 space-y-2 list-disc ml-4">
                <li>Keep this browser tab open to ensure the music plays.</li>
                <li>Make sure your computer's volume is up.</li>
                <li>Ensure your computer doesn't go to sleep.</li>
                <li>"Activate System" must be clicked once after loading.</li>
              </ul>
            </div>
          </div>

          <div className="lg:col-span-2 space-y-4">
            <div className="flex items-center justify-between mb-2">
              <h2 className="text-xl font-bold text-slate-800 flex items-center gap-2">
                <Bell className="w-5 h-5 text-indigo-500" />
                Active Schedule ({schedules.length})
              </h2>
            </div>

            {schedules.length === 0 ? (
              <div className="bg-white border-2 border-dashed border-slate-200 rounded-2xl p-20 flex flex-col items-center justify-center text-slate-400">
                <Music className="w-12 h-12 mb-4 opacity-20" />
                <p className="font-medium">No bells scheduled yet.</p>
                <p className="text-sm">Add your first class end time using the form.</p>
              </div>
            ) : (
              <div className="space-y-3">
                {schedules.map((item) => (
                  <div 
                    key={item.id} 
                    className={`group bg-white p-4 rounded-2xl shadow-sm border transition-all flex items-center justify-between hover:border-indigo-200 ${
                      isPlaying === item.id ? 'border-indigo-500 ring-2 ring-indigo-50 shadow-md scale-[1.02]' : 'border-slate-100'
                    }`}
                  >
                    <div className="flex items-center gap-4">
                      <div className={`w-14 h-14 rounded-xl flex items-center justify-center font-bold text-lg transition-colors ${
                        isPlaying === item.id ? 'bg-indigo-600 text-white' : 'bg-slate-50 text-slate-600 group-hover:bg-indigo-50 group-hover:text-indigo-600'
                      }`}>
                        {item.time}
                      </div>
                      <div>
                        <h4 className="font-bold text-slate-800">{item.songName}</h4>
                        <div className="flex items-center gap-2 text-sm text-slate-500">
                          <Music className="w-3 h-3" />
                          <span className="truncate max-w-[150px]">{item.songFile?.name}</span>
                        </div>
                      </div>
                    </div>

                    <div className="flex items-center gap-2">
                      {isPlaying === item.id ? (
                        <div className="flex items-center gap-2 px-3 py-1 bg-indigo-50 text-indigo-600 rounded-full text-xs font-bold animate-pulse">
                          <Volume2 className="w-4 h-4" />
                          PLAYING
                        </div>
                      ) : (
                        <button 
                          onClick={() => playSong(item)}
                          className="p-2 text-slate-400 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg transition-all"
                          title="Test Sound"
                        >
                          <Play className="w-5 h-5" />
                        </button>
                      )}
                      <button 
                        onClick={() => removeSchedule(item.id)}
                        className="p-2 text-slate-400 hover:text-rose-600 hover:bg-rose-50 rounded-lg transition-all"
                        title="Delete Schedule"
                      >
                        <Trash2 className="w-5 h-5" />
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </main>

      {/* Footer Branding */}
      <footer className="mt-20 text-center text-slate-400 text-sm py-8 border-t border-slate-100">
        <p>© {new Date().getFullYear()} School Bell Pro • Automated Campus Solutions</p>
      </footer>
    </div>
  );
};

export default App;
