"use client"
import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import TaskCompletionModal from '@/components/TaskCompletionModal';
import { Calendar, BarChart2, Settings, CheckSquare, Loader2, Check, X } from 'lucide-react';
import { startOfWeek, addDays, format } from 'date-fns';

interface Block {
  dayOfWeek: string;
  startTime: string;
  endTime: string;
  activityName: string;
  blockType: string;
  color: string;
}

interface Completion {
  date: string;
  activityName: string;
  scheduledStart: string;
  completed: boolean;
}

export default function Home() {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [blocks, setBlocks] = useState<Block[]>([]);
  const [completions, setCompletions] = useState<Completion[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchCompletions = () => {
    const start = startOfWeek(new Date(), { weekStartsOn: 1 }); // week starts Monday
    const end = addDays(start, 6);
    fetch(`/api/completions?startDate=${format(start, 'yyyy-MM-dd')}&endDate=${format(end, 'yyyy-MM-dd')}`)
      .then(res => res.json())
      .then(data => {
        if (Array.isArray(data)) setCompletions(data);
      })
      .catch(console.error);
  };

  useEffect(() => {
    fetch('/api/schedule')
      .then(res => res.json())
      .then(data => {
        if (Array.isArray(data)) {
          setBlocks(data);
        }
        setLoading(false);
      })
      .catch(err => {
        console.error(err);
        setLoading(false);
      });

    fetchCompletions();
  }, []);

  const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
  const todayIndex = new Date().getDay();
  const currentDayName = days[todayIndex === 0 ? 6 : todayIndex - 1];

  const getBlocksForDay = (day: string) => blocks.filter(b => b.dayOfWeek === day);

  const getCompletion = (dayOfWeek: string, activityName: string, startTime: string) => {
    const dayIndex = days.indexOf(dayOfWeek);
    const start = startOfWeek(new Date(), { weekStartsOn: 1 });
    const taskDate = addDays(start, dayIndex);
    const dateStr = format(taskDate, 'yyyy-MM-dd');
    return completions.find(c => c.date === dateStr && c.activityName === activityName && c.scheduledStart === startTime);
  };

  const markTask = async (dayOfWeek: string, block: Block, completed: boolean) => {
    const dayIndex = days.indexOf(dayOfWeek);
    const start = startOfWeek(new Date(), { weekStartsOn: 1 });
    const taskDate = addDays(start, dayIndex);
    const dateStr = format(taskDate, 'yyyy-MM-dd');

    const payload = {
      date: dateStr,
      blockType: block.blockType,
      activityName: block.activityName,
      scheduledStart: block.startTime,
      scheduledEnd: block.endTime,
      completed: completed,
      completedAt: new Date().toISOString()
    };

    await fetch('/api/completions', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    });
    
    fetchCompletions();
  };

  return (
    <div className="max-w-7xl mx-auto pb-16">
      <header className="flex justify-between items-center mb-8">
        <div>
          <h1 className="text-3xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-blue-400 to-emerald-400">
            සතියේ සැලැස්ම (Weekly Plan)
          </h1>
          <p className="text-slate-400 mt-1">Manage your schedule and track your daily tasks.</p>
        </div>
        
        <nav className="flex space-x-4">
          <Link href="/" className="flex items-center space-x-2 px-4 py-2 bg-slate-800 rounded-lg text-blue-400 border border-blue-500/30">
            <Calendar size={18} />
            <span>සතිය (Week)</span>
          </Link>
          <Link href="/analytics" className="flex items-center space-x-2 px-4 py-2 hover:bg-slate-800 rounded-lg text-slate-300 transition-colors">
            <BarChart2 size={18} />
            <span>Analytics</span>
          </Link>
          <Link href="/settings" className="flex items-center space-x-2 px-4 py-2 hover:bg-slate-800 rounded-lg text-slate-300 transition-colors">
            <Settings size={18} />
          </Link>
        </nav>
      </header>

      {loading ? (
        <div className="flex justify-center items-center h-64">
          <Loader2 className="animate-spin text-blue-500" size={48} />
        </div>
      ) : (
        <div className="bg-slate-900 border border-slate-800 rounded-2xl p-6 shadow-xl overflow-x-auto">
          <div className="min-w-[1000px] grid grid-cols-7 gap-4">
            {days.map(day => (
              <div key={day} className="flex flex-col space-y-3">
                <div className="text-center font-semibold text-slate-300 pb-2 border-b border-slate-800">{day}</div>
                <div className="flex flex-col space-y-2">
                  {getBlocksForDay(day).map((block, idx) => {
                    const comp = getCompletion(day, block.activityName, block.startTime);
                    const isCompleted = comp?.completed === true;
                    const isFailed = comp?.completed === false;
                    const isToday = day === currentDayName;

                    return (
                      <div 
                        key={idx} 
                        className="p-3 rounded-lg text-sm border shadow-sm relative overflow-hidden transition-all hover:scale-105 flex flex-col justify-between"
                        style={{ 
                          backgroundColor: `${block.color}15`,
                          borderColor: isToday ? `${block.color}` : `${block.color}40`,
                          borderLeftWidth: '4px',
                          borderLeftColor: block.color,
                          opacity: isCompleted ? 0.6 : 1
                        }}
                      >
                        <div>
                          <div className="font-medium text-white mb-1 leading-tight">{block.activityName}</div>
                          <div className="text-xs text-slate-400 font-mono mb-3">
                            {block.startTime} - {block.endTime}
                          </div>
                        </div>

                        {/* Inline completion buttons ONLY for today */}
                        {isToday && (
                          <div className="flex space-x-2 justify-end mt-auto pt-2 border-t border-slate-700/50">
                            <button 
                              onClick={(e) => { e.stopPropagation(); markTask(day, block, true) }} 
                              className={`p-1.5 rounded-md transition-colors ${isCompleted ? 'bg-green-500 text-white' : 'bg-slate-800 text-slate-400 hover:bg-green-500/20 hover:text-green-400'}`}
                              title="Done"
                            >
                              <Check size={14} strokeWidth={3} />
                            </button>
                            <button 
                              onClick={(e) => { e.stopPropagation(); markTask(day, block, false) }} 
                              className={`p-1.5 rounded-md transition-colors ${isFailed ? 'bg-red-500 text-white' : 'bg-slate-800 text-slate-400 hover:bg-red-500/20 hover:text-red-400'}`}
                              title="Missed"
                            >
                              <X size={14} strokeWidth={3} />
                            </button>
                          </div>
                        )}
                      </div>
                    )
                  })}
                  {getBlocksForDay(day).length === 0 && (
                    <div className="text-center text-slate-600 text-sm py-4">No blocks</div>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Floating Action Button for Manual Check-in */}
      <button 
        onClick={() => setIsModalOpen(true)}
        className="fixed bottom-8 right-8 bg-blue-600 hover:bg-blue-700 text-white p-4 rounded-full shadow-lg shadow-blue-600/30 flex items-center justify-center transition-transform hover:scale-105 z-40"
        title="Check Today's Tasks"
      >
        <CheckSquare size={24} />
      </button>

      {/* The Daily Task Completion Modal */}
      <TaskCompletionModal 
        isOpen={isModalOpen} 
        onClose={() => {
          setIsModalOpen(false);
          fetchCompletions(); // Refresh in case modal saved anything
        }} 
        tasks={getBlocksForDay(days[new Date().getDay() === 0 ? 6 : new Date().getDay() - 1]).map(b => ({
          ...b,
          scheduledStart: b.startTime,
          scheduledEnd: b.endTime
        }))} 
      />
    </div>
  );
}
