"use client"

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

export default function Deployment() {
    const [dev, setDev] = useState("")
    const [prod, setProd] = useState("")
    const [ssl, setSsl] = useState(false)
    const [devSites, setDevSites] = useState<string[]>([])

    useEffect(() => {
        apiFetch("/sites/dev").then(res => res.json()).then(data => {
            if (Array.isArray(data)) {
                setDevSites(data as string[]);
            } else if (data && Array.isArray(data.sites)) {
                const sites = data.sites.slice(1); // remove first descriptive string
                const uniqueSites = [...new Set(sites.map((s: string) => s.replace(/-le-ssl$/, '')))] as string[];
                setDevSites(uniqueSites);
            } else {
                console.log('Unexpected data format:', data);
            }
        }).catch(err => console.error('API error:', err));
    }, [])

    async function deploy() {
        await apiFetch("/jobs/deploy-to-prod", {
            method: "POST",
            body: JSON.stringify({
                project: dev,
                domain: prod,
                ssl: ssl ? "letsencrypt" : false
            })
        })

        alert("Deployment started")
    }

    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">Deploy</h2>

            <div className="mb-3">
                <label className="block text-sm font-medium text-gray-700 mb-1">Sitio de desarrollo</label>
                <select 
                    onChange={e => setDev(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 sitio de desarrollo</option>
                    {Array.isArray(devSites) && devSites.map(p => (
                        <option key={p} value={p}>{p}</option>
                    ))}
                </select>
            </div>

            <div className="mb-3">
                <label className="block text-sm font-medium text-gray-700 mb-1">Dominio de producción</label>
                <div className="flex">
                    <span className="inline-flex items-center px-3 text-sm text-gray-900 bg-gray-200 border border-r-0 border-gray-300 rounded-l focus:ring-2 focus:ring-indigo-500">
                        https://
                    </span>
                    <input 
                        placeholder="example.es" 
                        onChange={e => setProd(e.target.value)} 
                        className="rounded-none rounded-r border border-gray-300 bg-white px-4 py-2.5 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none flex-1"
                    />
                </div>
            </div>

            <div className="mb-6">
                <label className="flex items-center">
                    <input 
                        type="checkbox"
                        id="ssl"
                        checked={ssl}
                        onChange={e => setSsl(e.target.checked)}
                        className="w-4 h-4 text-indigo-600 bg-gray-100 border-gray-300 rounded focus:ring-indigo-500 mr-2"
                    />
                    <span className="text-sm font-medium text-gray-900">Instalar SSL LetsEncrypt</span>
                </label>
            </div>

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