"use client"

import { useEffect, useState } from "react"
import { apiFetch } from "../lib/api"

export default function Templates() {
    const [templates, setTemplates] = useState<string[]>([])
    const [project, setProject] = useState("")
    const [template, setTemplate] = useState("")

    useEffect(() => {
        const templatesList = "plantilla1,plantilla2,plantilla3,plantilla4,plantilla5,plantilla6,plantilla7a,plantilla8,plantilla9a,plantilla10";
        setTemplates(templatesList.split(','));
    }, [])

    async function create() {
        await apiFetch("/jobs/duplicate-template", {
            method: "POST",
            body: JSON.stringify({ template, project, db: project })
        })

        alert("Job created")
    }

    return (
        <div className="bg-white p-6 rounded-xl shadow-lg border border-gray-100 max-w-2xl mx-auto">
            <h2 className="text-xl font-bold text-gray-900 mb-6">Duplicate template</h2>

            <div className="mb-3">
                <label className="block text-sm font-medium text-gray-700 mb-1">Nombre del proyecto</label>
                <input 
                    placeholder="Nombre del nuevo proyecto" 
                    onChange={e => setProject(e.target.value)} 
                    className="w-full p-2.5 border border-gray-200 rounded focus:outline-none focus:ring-2 focus:ring-indigo-500"
                />
            </div>

            <div className="mb-6">
                <label className="block text-sm font-medium text-gray-700 mb-1">Plantilla</label>
                <select 
                    onChange={e => setTemplate(e.target.value)}
                    className="w-full p-2.5 border border-gray-200 rounded focus:outline-none focus:ring-2 focus:ring-indigo-500"
                >
                    <option value="">Seleccionar plantilla</option>
                    {Array.isArray(templates) && templates.map(t => (
                        <option key={t} value={t}>{t}</option>
                    ))}
                </select>
            </div>

            <button 
                onClick={create}
                className="bg-gray-900 text-white px-4 py-2 rounded font-semibold hover:bg-gray-800 transition-colors cursor-pointer"
            >
                Create
            </button>
        </div>
    )
}
