// import { useState, useRef } from "react"
// import { SVGS } from "../assets/svgs"

import { useState } from "react"
import { useRef } from "react"
import { SVGS } from "../assets/svgs"
import useStore from "../utils/store"

export interface Lesson {
  id: string
  uid: string
  title: string
  type: "READ" | "CODE" | "QUIZ"
  description: string
  duration?: number
}

const typeToEmoji: Record<string, string> = {
  read: "📖",
  code: "💻",
  quiz: "🧠",
}

interface LessonItemProps {
  lesson: Lesson
  isNew: boolean
  onChange: (uid: string, newTitle: string) => void
  onRemove: () => void
}

function cleanFloatString(input: string): string {
  const num = parseFloat(input)
  const isInteger = Number.isInteger(num)

  return isInteger
    ? Math.floor(num).toString().padStart(2, "0")
    : num.toString()
}

function hasDecimalPart(input: string): boolean {
  const num = parseFloat(input)
  if (Number.isNaN(num)) return false
  return num % 1 > 0
}

export const LessonItem: React.FC<LessonItemProps> = ({
  lesson,
  onChange,
  onRemove,
  isNew,
}) => {
  const mode = useStore((state) => state.mode)
  const inputRef = useRef<HTMLInputElement>(null)
  const [isEditing, setIsEditing] = useState(false)

  return (
    <div
      className={`flex items-center space-x-2 relative rounded-md p-3 ${
        isNew ? "border border-learnpack-blue appear" : "border border-gray-200"
      } ${hasDecimalPart(lesson.id.toString() || "0") ? "ml-6" : ""}`}
    >
      {isNew && <span className="red-ball"></span>}

      {mode === "teacher" && (
        <>
          <span className="index-circle">{cleanFloatString(lesson.id)}</span>
        </>
      )}

      <span className="text-gray-500 text-sm">
        {typeToEmoji[lesson.type.toLowerCase()]}
      </span>
      {isEditing ? (
        <input
          defaultValue={lesson.title}
          ref={inputRef}
          onBlur={() => {
            if (inputRef.current) {
              onChange(lesson.uid, inputRef.current.value)
            }
          }}
          autoFocus
          className="flex-1 bg-white border border-gray-300 rounded-md px-2 py-1 text-sm"
        />
      ) : (
        <span className="flex-1 text-sm text-gray-800">{lesson.title}</span>
      )}

      <span className="text-sm text-gray-600 bg-blue-100 px-2 py-1 rounded-full">
        {lesson.duration} min
      </span>

      {mode === "teacher" && (
        <>
          <button
            onClick={() => {
              setIsEditing(!isEditing)
              if (inputRef.current) {
                onChange(lesson.uid, inputRef.current.value)
              }
            }}
            className="text-gray-500 hover:text-blue-500 cursor-pointer "
          >
            {SVGS.pen}
          </button>
          <button
            onClick={() => onRemove()}
            className="text-red-500 hover:text-red-700 cursor-pointer"
          >
            {SVGS.trash}
          </button>
        </>
      )}
    </div>
  )
}
