"use client";

import { useState } from "react";
import { Card } from "@/components/ui/Card";
import { Badge } from "@/components/ui/Badge";
import { ExerciseRow } from "@/components/workout/ExerciseRow";
import type { Superset } from "@/lib/types";

interface SupersetCardProps {
  superset: Superset;
  defaultOpen?: boolean;
}

function formatTime(seconds: number | null): string {
  if (!seconds) return "";
  const mins = Math.round(seconds / 60);
  return `${mins}m`;
}

export function SupersetCard({ superset, defaultOpen = false }: SupersetCardProps) {
  const [open, setOpen] = useState(defaultOpen);

  const sortedExercises = [...superset.exercises].sort(
    (a, b) => a.order - b.order
  );

  const displayName = superset.name || `Superset ${superset.order}`;

  return (
    <Card className="overflow-hidden">
      <button
        onClick={() => setOpen(!open)}
        className="w-full flex items-center justify-between p-4 text-left hover:bg-zinc-800/50 transition-colors duration-150"
      >
        <div className="flex items-center gap-3">
          <h3 className="text-sm font-semibold text-zinc-100">{displayName}</h3>
          <Badge variant="accent">{superset.rounds}x</Badge>
          {superset.estimated_time && (
            <span className="text-xs text-zinc-500">
              {formatTime(superset.estimated_time)}
            </span>
          )}
        </div>
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="20"
          height="20"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
          className={`text-zinc-500 transition-transform duration-200 ${
            open ? "rotate-180" : ""
          }`}
        >
          <polyline points="6 9 12 15 18 9" />
        </svg>
      </button>

      {open && (
        <div className="border-t border-zinc-700/50">
          {sortedExercises.map((exercise) => (
            <ExerciseRow key={exercise.id} exercise={exercise} />
          ))}
        </div>
      )}
    </Card>
  );
}
