import { useEffect, useState } from 'react';
import { useHistoryStore } from '../../stores/historyStore';
import { SessionDetail } from './SessionDetail';
import type { Session } from '../../types';
import { api } from '../../api/client';

export function SessionList() {
  const { sessions, loading, fetchSessions } = useHistoryStore();
  const [expandedId, setExpandedId] = useState<number | null>(null);
  const [expandedSession, setExpandedSession] = useState<Session | null>(null);

  useEffect(() => {
    fetchSessions(50);
  }, [fetchSessions]);

  const toggleSession = async (id: number) => {
    if (expandedId === id) {
      setExpandedId(null);
      setExpandedSession(null);
      return;
    }
    setExpandedId(id);
    try {
      const session = await api.sessions.get(id);
      setExpandedSession(session);
    } catch {
      setExpandedSession(null);
    }
  };

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleDateString('de-DE', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  const formatDuration = (start: string, end?: string) => {
    if (!end) return 'laufend';
    const ms = new Date(end).getTime() - new Date(start).getTime();
    const mins = Math.round(ms / 60000);
    if (mins < 60) return `${mins} Min.`;
    const h = Math.floor(mins / 60);
    const m = mins % 60;
    return `${h}h ${m}m`;
  };

  if (loading) {
    return <div className="text-center text-gray-500 py-8">Laden...</div>;
  }

  if (sessions.length === 0) {
    return (
      <div className="text-center text-gray-500 py-12">
        <p className="text-lg">Noch keine Trainings absolviert</p>
        <p className="text-sm mt-1">Starte dein erstes Training im Training-Tab.</p>
      </div>
    );
  }

  return (
    <div className="space-y-3">
      {sessions.map((session) => (
        <div
          key={session.id}
          className="bg-gray-900 border border-gray-800 rounded-xl overflow-hidden"
        >
          <button
            onClick={() => toggleSession(session.id)}
            className="w-full px-4 py-3 min-h-[44px] text-left hover:bg-gray-800/50"
          >
            <div className="flex items-center justify-between">
              <div>
                <div className="font-semibold text-gray-100">{session.set_name}</div>
                <div className="text-sm text-gray-400 mt-0.5">
                  {formatDate(session.started_at)}
                </div>
              </div>
              <div className="text-right">
                <div className="text-sm text-gray-400">
                  {formatDuration(session.started_at, session.ended_at)}
                </div>
                <svg
                  className={`w-5 h-5 text-gray-400 transition-transform ml-auto ${expandedId === session.id ? 'rotate-180' : ''}`}
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  strokeWidth={2}
                >
                  <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
                </svg>
              </div>
            </div>
          </button>
          {expandedId === session.id && expandedSession && (
            <div className="px-4 pb-4 border-t border-gray-800 pt-3">
              <SessionDetail logs={expandedSession.logs || []} />
            </div>
          )}
        </div>
      ))}
    </div>
  );
}
