"use client"

import * as React from "react"
import { ChevronDown, ChevronRight, Clock, Dumbbell } from "lucide-react"

import { cn } from "@/lib/utils"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import type { Database } from "@/lib/supabase"

type ProgramTabata = Database["public"]["Tables"]["program_tabatas"]["Row"]

interface TabataData {
  position: number
  exercise_1_name: string
  exercise_1_name_en: string
  exercise_1_tip: string
  exercise_1_tip_en: string
  exercise_1_modification: string
  exercise_1_modification_en: string
  exercise_1_progression: string
  exercise_1_progression_en: string
  exercise_2_name: string
  exercise_2_name_en: string
  exercise_2_tip: string
  exercise_2_tip_en: string
  exercise_2_modification: string
  exercise_2_modification_en: string
  exercise_2_progression: string
  exercise_2_progression_en: string
  rounds: number
  work_time: number
  rest_time: number
}

export type { TabataData }

interface TabataEditorProps {
  tabata: TabataData | null
  position: 1 | 2 | 3
  onChange: (data: TabataData) => void
}

function getDefaultTabata(position: number): TabataData {
  return {
    position,
    exercise_1_name: "",
    exercise_1_name_en: "",
    exercise_1_tip: "",
    exercise_1_tip_en: "",
    exercise_1_modification: "",
    exercise_1_modification_en: "",
    exercise_1_progression: "",
    exercise_1_progression_en: "",
    exercise_2_name: "",
    exercise_2_name_en: "",
    exercise_2_tip: "",
    exercise_2_tip_en: "",
    exercise_2_modification: "",
    exercise_2_modification_en: "",
    exercise_2_progression: "",
    exercise_2_progression_en: "",
    rounds: 8,
    work_time: 20,
    rest_time: 10,
  }
}

interface ExerciseSectionProps {
  label: string
  number: 1 | 2
  data: TabataData
  onChange: (field: string, value: string) => void
  errors: Record<string, string>
}

function ExerciseSection({ label, number, data, onChange, errors }: ExerciseSectionProps) {
  const [isOpen, setIsOpen] = React.useState(true)
  const prefix = `exercise_${number}` as const

  const nameField = `${prefix}_name` as keyof TabataData
  const nameValue = data[nameField] as string

  return (
    <div className="rounded-lg border border-neutral-800 bg-neutral-950 overflow-hidden">
      <button
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center justify-between w-full px-4 py-3 text-sm font-medium text-white hover:bg-neutral-800/50 transition-colors"
      >
        <div className="flex items-center gap-2">
          {isOpen ? <ChevronDown className="h-4 w-4 text-neutral-500" /> : <ChevronRight className="h-4 w-4 text-neutral-500" />}
          <Dumbbell className="h-4 w-4 text-orange-500" />
          <span>{label}</span>
          {nameValue && (
            <span className="text-neutral-500 font-normal">- {nameValue}</span>
          )}
        </div>
      </button>

      {isOpen && (
        <div className="px-4 pb-4 space-y-3 border-t border-neutral-800">
          {/* Name fields */}
          <div className="grid grid-cols-2 gap-3 pt-3">
            <div className="space-y-1.5">
              <Label className="text-xs text-neutral-400">Name (FR) *</Label>
              <Input
                value={data[nameField] as string}
                onChange={(e) => onChange(`${prefix}_name`, e.target.value)}
                placeholder="e.g., Squats"
                className={cn("h-9 text-sm", errors[`${prefix}_name`] && "border-red-500")}
              />
              {errors[`${prefix}_name`] && <p className="text-xs text-red-500">{errors[`${prefix}_name`]}</p>}
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs text-neutral-400">Name (EN)</Label>
              <Input
                value={data[`${prefix}_name_en` as keyof TabataData] as string}
                onChange={(e) => onChange(`${prefix}_name_en`, e.target.value)}
                placeholder="e.g., Squats"
                className="h-9 text-sm"
              />
            </div>
          </div>

          {/* Tip fields */}
          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1.5">
              <Label className="text-xs text-neutral-400">Tip (FR)</Label>
              <Input
                value={data[`${prefix}_tip` as keyof TabataData] as string}
                onChange={(e) => onChange(`${prefix}_tip`, e.target.value)}
                placeholder="Conseil en français"
                className="h-9 text-sm"
              />
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs text-neutral-400">Tip (EN)</Label>
              <Input
                value={data[`${prefix}_tip_en` as keyof TabataData] as string}
                onChange={(e) => onChange(`${prefix}_tip_en`, e.target.value)}
                placeholder="Tip in English"
                className="h-9 text-sm"
              />
            </div>
          </div>

          {/* Modification fields */}
          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1.5">
              <Label className="text-xs text-neutral-400">Modification (FR)</Label>
              <Input
                value={data[`${prefix}_modification` as keyof TabataData] as string}
                onChange={(e) => onChange(`${prefix}_modification`, e.target.value)}
                placeholder="Version plus facile"
                className="h-9 text-sm"
              />
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs text-neutral-400">Modification (EN)</Label>
              <Input
                value={data[`${prefix}_modification_en` as keyof TabataData] as string}
                onChange={(e) => onChange(`${prefix}_modification_en`, e.target.value)}
                placeholder="Easier variation"
                className="h-9 text-sm"
              />
            </div>
          </div>

          {/* Progression fields */}
          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1.5">
              <Label className="text-xs text-neutral-400">Progression (FR)</Label>
              <Input
                value={data[`${prefix}_progression` as keyof TabataData] as string}
                onChange={(e) => onChange(`${prefix}_progression`, e.target.value)}
                placeholder="Version plus difficile"
                className="h-9 text-sm"
              />
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs text-neutral-400">Progression (EN)</Label>
              <Input
                value={data[`${prefix}_progression_en` as keyof TabataData] as string}
                onChange={(e) => onChange(`${prefix}_progression_en`, e.target.value)}
                placeholder="Harder variation"
                className="h-9 text-sm"
              />
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default function TabataEditor({ tabata, position, onChange }: TabataEditorProps) {
  const data = tabata || getDefaultTabata(position)
  const [errors, setErrors] = React.useState<Record<string, string>>({})

  const handleChange = (field: string, value: string) => {
    const updated = { ...data, [field]: value }
    onChange(updated)
  }

  const handleTimingChange = (field: "rounds" | "work_time" | "rest_time", value: string) => {
    const numValue = parseInt(value) || 0
    const updated = { ...data, [field]: numValue }
    onChange(updated)
  }

  return (
    <div className="rounded-lg border border-neutral-700 bg-neutral-900 overflow-hidden">
      {/* Header */}
      <div className="flex items-center gap-3 px-4 py-3 bg-neutral-800/50 border-b border-neutral-700">
        <div className="flex h-8 w-8 items-center justify-center rounded-full bg-orange-500/20 text-orange-500 font-bold text-sm">
          {position}
        </div>
        <div>
          <h3 className="text-white font-medium">Tabata {position}</h3>
          <p className="text-xs text-neutral-500">
            {data.exercise_1_name && data.exercise_2_name
              ? `${data.exercise_1_name} / ${data.exercise_2_name}`
              : "Configure exercises and timing"
            }
          </p>
        </div>
        <div className="ml-auto flex items-center gap-2 text-xs text-neutral-500">
          <Clock className="h-3.5 w-3.5" />
          <span>{data.rounds * (data.work_time + data.rest_time)}s total</span>
        </div>
      </div>

      {/* Content */}
      <div className="p-4 space-y-4">
        {/* Exercise sections */}
        <ExerciseSection
          label="Exercise 1"
          number={1}
          data={data}
          onChange={handleChange}
          errors={errors}
        />

        <ExerciseSection
          label="Exercise 2"
          number={2}
          data={data}
          onChange={handleChange}
          errors={errors}
        />

        {/* Timing */}
        <div className="rounded-lg border border-neutral-800 bg-neutral-950 p-4">
          <div className="flex items-center gap-2 mb-3">
            <Clock className="h-4 w-4 text-orange-500" />
            <span className="text-sm font-medium text-white">Timing</span>
          </div>
          <div className="grid grid-cols-3 gap-3">
            <div className="space-y-1.5">
              <Label className="text-xs text-neutral-400">Rounds</Label>
              <Input
                type="number"
                value={data.rounds}
                onChange={(e) => handleTimingChange("rounds", e.target.value)}
                min={1}
                max={20}
                className="h-9 text-sm"
              />
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs text-neutral-400">Work (sec)</Label>
              <Input
                type="number"
                value={data.work_time}
                onChange={(e) => handleTimingChange("work_time", e.target.value)}
                min={1}
                className="h-9 text-sm"
              />
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs text-neutral-400">Rest (sec)</Label>
              <Input
                type="number"
                value={data.rest_time}
                onChange={(e) => handleTimingChange("rest_time", e.target.value)}
                min={0}
                className="h-9 text-sm"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
