"use client"

import { useState } from "react"
import { createKid } from "@/app/actions"
import QRCode from "react-qr-code"

export default function KidManager({ kids }: { kids: any[] }) {
  const [newKidName, setNewKidName] = useState("")

  const handleAddKid = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!newKidName.trim()) return
    await createKid(newKidName)
    setNewKidName("")
  }

  const origin = typeof window !== "undefined" ? window.location.origin : ""

  return (
    <div style={{ width: "100%" }}>
      <h2 style={{ fontSize: "1.3rem", fontWeight: "600", marginBottom: "0.75rem", paddingLeft: "0.5rem" }}>Your Kids</h2>
      
      <div className="ios-list">
        {kids.map(kid => {
          const kidUrl = `${origin}/kid/${kid.loginToken}`
          return (
            <div key={kid.id} className="ios-list-item" style={{ flexDirection: "column", alignItems: "flex-start", padding: "1.25rem" }}>
              <div style={{ width: "100%", display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "1rem" }}>
                <h3 className="ios-list-item-title" style={{ fontSize: "1.2rem" }}>{kid.name}</h3>
                <a href={kidUrl} target="_blank" style={{ color: "var(--primary)", fontWeight: "500", fontSize: "0.95rem" }}>
                  Open directly
                </a>
              </div>
              
              <p className="ios-list-item-subtitle" style={{ marginBottom: "1rem" }}>
                Scan this QR code with {kid.name}'s iPad to log them in automatically.
              </p>
              
              <div style={{ background: "white", padding: "1rem", borderRadius: "12px", alignSelf: "center", boxShadow: "0 2px 8px rgba(0,0,0,0.05)" }}>
                <QRCode value={kidUrl} size={130} />
              </div>
            </div>
          )
        })}

        {kids.length === 0 && (
          <div className="ios-list-item" style={{ justifyContent: "center", color: "var(--foreground)", opacity: 0.6 }}>
            No kids added yet.
          </div>
        )}
      </div>

      <h2 style={{ fontSize: "1.3rem", fontWeight: "600", marginBottom: "0.75rem", paddingLeft: "0.5rem", marginTop: "1.5rem" }}>Add a Kid</h2>
      <div className="ios-list">
        <form onSubmit={handleAddKid} style={{ display: "flex", flexDirection: "column", padding: "1rem", gap: "1rem" }}>
          <input
            type="text"
            placeholder="Kid's Name"
            className="input"
            style={{ border: "none", background: "var(--background)" }}
            value={newKidName}
            onChange={e => setNewKidName(e.target.value)}
          />
          <button type="submit" className="btn" style={{ width: "100%" }}>Add Kid</button>
        </form>
      </div>
    </div>
  )
}
