"use client"

import { useState } from "react"
import { Play, Music, Video, FileText, ExternalLink } from "lucide-react"

export default function TaskCard({ task, isFirst }: { task: any, isFirst: boolean }) {
  const [isStarted, setIsStarted] = useState(false)

  const materials = task.activity?.materials || []

  // Helper to safely render youtube embeds
  const renderYouTube = (url: string) => {
    let videoId = ""
    if (url.includes("v=")) {
      videoId = url.split("v=")[1].split("&")[0]
    } else if (url.includes("youtu.be/")) {
      videoId = url.split("youtu.be/")[1].split("?")[0]
    }
    
    if (videoId) {
      return (
        <iframe 
          width="100%" 
          height="315" 
          src={`https://www.youtube.com/embed/${videoId}`} 
          title="YouTube video player" 
          frameBorder="0" 
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
          allowFullScreen
          style={{ borderRadius: "8px", marginTop: "1rem" }}
        ></iframe>
      )
    }
    return <a href={url} target="_blank" rel="noreferrer" className="btn" style={{ display: "inline-block", marginTop: "1rem" }}>Open Link <ExternalLink size={16} style={{ display: "inline", marginBottom: "-3px" }}/></a>
  }

  return (
    <div 
      style={{ 
        background: "var(--surface)", 
        padding: "1.5rem", 
        borderRadius: "var(--radius-xl)", 
        boxShadow: "var(--shadow-sm)", 
        display: "flex", 
        flexDirection: "column",
        gap: "1.5rem",
        borderLeft: "6px solid var(--primary)",
        transform: isFirst && !isStarted ? "scale(1.02)" : "scale(1)", 
        transition: "var(--transition)"
      }}
    >
      <div style={{ display: "flex", alignItems: "center", gap: "1.5rem" }}>
        <div style={{ flex: 1 }}>
          {task.startTime && <div style={{ fontSize: "1.1rem", fontWeight: "700", color: "var(--primary)", marginBottom: "0.25rem" }}>{task.startTime}</div>}
          <h3 style={{ fontSize: "1.6rem", fontWeight: "800", margin: 0, letterSpacing: "-0.02em" }}>{task.title}</h3>
          {task.activity && (
            <div style={{ marginTop: "0.5rem", color: "var(--primary-hover)", fontWeight: 600, fontSize: "1.05rem" }}>
              Activity: {task.activity.name}
            </div>
          )}
        </div>
        
        {!isStarted && (
          <div>
            <button 
              className="btn" 
              onClick={() => setIsStarted(true)}
              style={{ fontSize: "1.2rem", padding: "1rem 2rem", borderRadius: "100px", display: "flex", alignItems: "center", gap: "0.5rem", minHeight: "56px" }}
            >
              <Play size={24} fill="currentColor" /> Start
            </button>
          </div>
        )}
      </div>

      {isStarted && (
        <div style={{ borderTop: "1px solid var(--border)", paddingTop: "1.5rem", marginTop: "0.5rem" }}>
          {task.activity?.description && (
            <p style={{ fontSize: "1.1rem", marginBottom: "1.5rem", lineHeight: 1.6 }}>
              {task.activity.description}
            </p>
          )}

          {materials.length === 0 ? (
            <p style={{ opacity: 0.7 }}>No materials for this activity.</p>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: "2rem" }}>
              {materials.map((m: any) => (
                <div key={m.id} style={{ background: "var(--background)", padding: "1.5rem", borderRadius: "12px", border: "1px solid var(--border)" }}>
                  <h4 style={{ fontSize: "1.3rem", fontWeight: "bold", marginBottom: "1rem", color: "var(--primary)", display: "flex", alignItems: "center", gap: "0.5rem" }}>
                    {m.type === "link" && <Video size={24} />}
                    {m.type === "text" && <FileText size={24} />}
                    {m.type === "file" && <Music size={24} />}
                    {m.title}
                  </h4>
                  
                  {/* Render based on type */}
                  {m.type === "text" && (
                    <div style={{ whiteSpace: "pre-wrap", background: "white", padding: "1rem", borderRadius: "8px", border: "1px solid #e2e8f0", fontSize: "1.1rem", lineHeight: 1.6 }}>
                      {m.urlOrText}
                    </div>
                  )}

                  {m.type === "link" && renderYouTube(m.urlOrText)}

                  {m.type === "file" && (
                    <div style={{ marginTop: "1rem" }}>
                      {/* Check if audio or video */}
                      {m.urlOrText.match(/\.(mp3|wav|ogg|m4a)$/i) ? (
                        <audio controls style={{ width: "100%" }}>
                          <source src={m.urlOrText} />
                          Your browser does not support the audio element.
                        </audio>
                      ) : m.urlOrText.match(/\.(mp4|webm|mov)$/i) ? (
                        <video controls style={{ width: "100%", borderRadius: "8px" }}>
                          <source src={m.urlOrText} />
                          Your browser does not support the video tag.
                        </video>
                      ) : (
                        <a href={m.urlOrText} target="_blank" rel="noreferrer" className="btn">Download File</a>
                      )}
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}

          <div style={{ marginTop: "2rem", textAlign: "center", width: "100%" }}>
            <button 
              className="btn" 
              onClick={() => setIsStarted(false)}
              style={{ background: "var(--border)", color: "var(--foreground)", width: "100%", borderRadius: "100px", minHeight: "56px", fontSize: "1.1rem" }}
            >
              Close Activity
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
