import { useState } from 'react';
import { useActiveSessionStore } from '../../stores/activeSessionStore';
import { useConfirm } from '../../hooks/useConfirm';
import { ConfirmDialog } from '../layout/ConfirmDialog';
import { LogEntryForm } from './LogEntryForm';
import { RestTimer } from './RestTimer';
import type { Exercise, SessionLog } from '../../types';

interface ActiveSessionProps {
  onEnd: () => void;
}

export function ActiveSession({ onEnd }: ActiveSessionProps) {
  const { session, exercises, lastLogs, addLog, updateLog, deleteLog, endSession } =
    useActiveSessionStore();
  const [expandedExercise, setExpandedExercise] = useState<number | null>(null);
  const [editingLog, setEditingLog] = useState<SessionLog | null>(null);
  const { isOpen, title, message, confirm, handleConfirm, handleCancel } = useConfirm();

  if (!session) return null;

  const logs = session.logs || [];

  const getExerciseLogs = (exerciseId: number) =>
    logs
      .filter((l) => l.exercise_id === exerciseId)
      .sort((a, b) => a.set_number - b.set_number);

  const getNextSetNumber = (exerciseId: number) => {
    const exLogs = getExerciseLogs(exerciseId);
    return exLogs.length > 0 ? Math.max(...exLogs.map((l) => l.set_number)) + 1 : 1;
  };

  const handleAddLog = async (
    exercise: Exercise,
    weight: number,
    reps: number,
    note: string,
  ) => {
    await addLog({
      exercise_id: exercise.id,
      set_number: getNextSetNumber(exercise.id),
      weight_kg: weight,
      reps,
      note,
    });
  };

  const handleUpdateLog = async (
    log: SessionLog,
    weight: number,
    reps: number,
    note: string,
  ) => {
    await updateLog(log.id, { weight_kg: weight, reps, note });
    setEditingLog(null);
  };

  const handleDeleteLog = async (log: SessionLog) => {
    const ok = await confirm('Satz löschen', 'Möchtest du diesen Satz wirklich löschen?');
    if (ok) {
      await deleteLog(log.id);
    }
  };

  const handleEndSession = async () => {
    const ok = await confirm(
      'Training beenden',
      'Möchtest du das Training wirklich beenden?',
    );
    if (ok) {
      const success = await endSession();
      if (success) onEnd();
    }
  };

  const toggleExercise = (id: number) => {
    setExpandedExercise((prev) => (prev === id ? null : id));
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-bold text-gray-100">{session.set_name}</h2>
        <span className="text-sm text-gray-400">
          {new Date(session.started_at).toLocaleTimeString('de-DE', {
            hour: '2-digit',
            minute: '2-digit',
          })}
        </span>
      </div>

      <RestTimer />

      {/* Übungen als Accordion */}
      {exercises.map((exercise) => {
        const exLogs = getExerciseLogs(exercise.id);
        const isExpanded = expandedExercise === exercise.id;
        const lastLog = lastLogs.get(exercise.id);

        return (
          <div
            key={exercise.id}
            className="bg-gray-900 border border-gray-800 rounded-xl overflow-hidden"
          >
            {/* Header */}
            <button
              onClick={() => toggleExercise(exercise.id)}
              className="w-full flex items-center justify-between px-4 py-3 min-h-[44px] text-left hover:bg-gray-800/50"
            >
              <div>
                <span className="font-semibold text-gray-100">{exercise.name}</span>
                <span className="ml-2 text-sm text-gray-500">
                  ({exLogs.length} {exLogs.length === 1 ? 'Satz' : 'Sätze'})
                </span>
              </div>
              <svg
                className={`w-5 h-5 text-gray-400 transition-transform ${isExpanded ? '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>
            </button>

            {/* Expanded content */}
            {isExpanded && (
              <div className="px-4 pb-4 space-y-3">
                {/* Vorherige Werte */}
                {lastLog && (
                  <div className="text-sm text-gray-500 bg-gray-800 rounded-lg px-3 py-2">
                    Letztes Training: {lastLog.weight_kg} kg x {lastLog.reps} Wdh.
                  </div>
                )}

                {/* Bisherige Sätze */}
                {exLogs.map((log) => (
                  <div key={log.id}>
                    {editingLog?.id === log.id ? (
                      <LogEntryForm
                        exercise={exercise}
                        setNumber={log.set_number}
                        initialWeight={log.weight_kg}
                        initialReps={log.reps}
                        onSubmit={(w, r, n) => handleUpdateLog(log, w, r, n)}
                        submitLabel="Aktualisieren"
                      />
                    ) : (
                      <div className="flex items-center justify-between bg-gray-800 rounded-lg px-3 py-2">
                        <div>
                          <span className="text-gray-500 text-sm mr-2">
                            Satz {log.set_number}:
                          </span>
                          <span className="font-semibold text-gray-100">
                            {log.weight_kg} kg
                          </span>
                          <span className="text-gray-400 mx-1">x</span>
                          <span className="font-semibold text-gray-100">
                            {log.reps} Wdh.
                          </span>
                          {log.note && (
                            <span className="text-xs text-gray-500 ml-2">
                              ({log.note})
                            </span>
                          )}
                        </div>
                        <div className="flex gap-1">
                          <button
                            onClick={() => setEditingLog(log)}
                            className="min-h-[36px] min-w-[36px] flex items-center justify-center text-gray-400 hover:text-blue-400"
                          >
                            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                              <path strokeLinecap="round" strokeLinejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                            </svg>
                          </button>
                          <button
                            onClick={() => handleDeleteLog(log)}
                            className="min-h-[36px] min-w-[36px] flex items-center justify-center text-gray-400 hover:text-red-400"
                          >
                            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                              <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                            </svg>
                          </button>
                        </div>
                      </div>
                    )}
                  </div>
                ))}

                {/* Neuer Satz — Werte vom letzten Satz dieser Session, sonst vom letzten Training */}
                <LogEntryForm
                  key={`new-${exercise.id}-${exLogs.length}`}
                  exercise={exercise}
                  setNumber={getNextSetNumber(exercise.id)}
                  initialWeight={exLogs.length > 0 ? exLogs[exLogs.length - 1].weight_kg : (lastLog?.weight_kg ?? 0)}
                  initialReps={exLogs.length > 0 ? exLogs[exLogs.length - 1].reps : (lastLog?.reps ?? 0)}
                  onSubmit={(w, r, n) => handleAddLog(exercise, w, r, n)}
                />
              </div>
            )}
          </div>
        );
      })}

      {/* Training beenden */}
      <button
        onClick={handleEndSession}
        className="w-full bg-red-600 hover:bg-red-500 text-white font-semibold rounded-xl py-4 min-h-[44px]"
      >
        Training beenden
      </button>

      <ConfirmDialog
        isOpen={isOpen}
        title={title}
        message={message}
        onConfirm={handleConfirm}
        onCancel={handleCancel}
      />
    </div>
  );
}
