'use client';

import { useEffect, useState } from 'react';
import api from '@/lib/api';
import { CalendarIcon, CheckIcon, XIcon, ClockIcon } from '@/components/ui/Icons';

interface HistorySession {
  id: string;
  routine_id: string;
  status: string;
  created_at: string;
  completed_at?: string;
}

interface Routine {
  id: string;
  name: string;
  icon?: string;
}

export default function HistoryPage() {
  const [routines, setRoutines] = useState<Routine[]>([]);
  const [selectedRoutine, setSelectedRoutine] = useState<string>('all');
  const [history, setHistory] = useState<HistorySession[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [routinesData] = await Promise.all([
          api.routines.list(),
        ]);
        setRoutines(routinesData);
      } catch (err) {
        console.error('Failed to fetch data:', err);
      } finally {
        setIsLoading(false);
      }
    };
    fetchData();
  }, []);

  useEffect(() => {
    const fetchHistory = async () => {
      setIsLoading(true);
      try {
        if (selectedRoutine === 'all') {
          const allHistory: HistorySession[] = [];
          for (const routine of routines) {
            const sessions = await api.routines.getHistory(routine.id, 30).catch(() => []);
            allHistory.push(...sessions.map(s => ({ ...s, routine_name: routine.name, routine_icon: routine.icon })));
          }
          allHistory.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
          setHistory(allHistory.slice(0, 50));
        } else {
          const sessions = await api.routines.getHistory(selectedRoutine, 30);
          setHistory(sessions);
        }
      } catch (err) {
        console.error('Failed to fetch history:', err);
      } finally {
        setIsLoading(false);
      }
    };
    
    if (routines.length > 0) {
      fetchHistory();
    }
  }, [selectedRoutine, routines]);

  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr);
    return date.toLocaleDateString('en-US', { 
      weekday: 'short', 
      month: 'short', 
      day: 'numeric',
      hour: 'numeric',
      minute: '2-digit'
    });
  };

  const isToday = (dateStr: string) => {
    const date = new Date(dateStr);
    const today = new Date();
    return date.toDateString() === today.toDateString();
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[50vh]">
        <div className="w-8 h-8 border-4 border-indigo-500 border-t-transparent rounded-full animate-spin"></div>
      </div>
    );
  }

  return (
    <div className="p-4 space-y-4">
      <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">History</h1>

      {/* Filter */}
      <select
        value={selectedRoutine}
        onChange={(e) => setSelectedRoutine(e.target.value)}
        className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-xl bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"
      >
        <option value="all">All Routines</option>
        {routines.map((routine) => (
          <option key={routine.id} value={routine.id}>
            {routine.name}
          </option>
        ))}
      </select>

      {history.length === 0 ? (
        <div className="bg-white dark:bg-gray-800 rounded-xl p-8 shadow-sm text-center">
          <CalendarIcon className="text-gray-400 dark:text-gray-500 mx-auto mb-4" size={40} />
          <h3 className="font-semibold text-gray-900 dark:text-gray-100 mb-1">No history yet</h3>
          <p className="text-gray-500 dark:text-gray-400 text-sm">Complete a routine to see it here</p>
        </div>
      ) : (
        <div className="space-y-3">
          {history.map((session) => (
            <div
              key={session.id}
              className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm flex items-center gap-4"
            >
              <div className={`
                w-10 h-10 rounded-full flex items-center justify-center
                ${session.status === 'completed' ? 'bg-green-100 dark:bg-green-900/30' : 'bg-red-100 dark:bg-red-900/30'}
              `}>
                {session.status === 'completed' ? (
                  <CheckIcon className="text-green-600 dark:text-green-400" size={20} />
                ) : (
                  <XIcon className="text-red-600 dark:text-red-400" size={20} />
                )}
              </div>
              <div className="flex-1">
                <p className="font-medium text-gray-900 dark:text-gray-100">
                  {(session as any).routine_name || 'Routine'}
                </p>
                <p className="text-sm text-gray-500 dark:text-gray-400">
                  {formatDate(session.created_at)}
                </p>
              </div>
              <span className={`
                text-xs font-medium px-2 py-1 rounded-full
                ${session.status === 'completed' ? 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400' : 'bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400'}
              `}>
                {session.status}
              </span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
