"use client"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { useState } from "react"
import { updateOrganizationIntegrations, IntegrationsData } from "../actions"
import { Loader2, Save, Eye, EyeOff } from "lucide-react"

export function OrgIntegrationsForm({ orgId, initialIntegrations }: { orgId: string, initialIntegrations: any }) {
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState<string | null>(null)
    const [success, setSuccess] = useState(false)

    const parsedIntegrations = typeof initialIntegrations === 'string' ? JSON.parse(initialIntegrations) : (initialIntegrations || {})

    // Odoo State
    const [odooBaseUrl, setOdooBaseUrl] = useState(parsedIntegrations?.odoo?.baseUrl || "")
    const [odooDb, setOdooDb] = useState(parsedIntegrations?.odoo?.db || "")
    const [odooUsername, setOdooUsername] = useState(parsedIntegrations?.odoo?.username || "")
    const [odooApiKey, setOdooApiKey] = useState(parsedIntegrations?.odoo?.apiKey || "")
    const [showApiKey, setShowApiKey] = useState(false)

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault()
        setLoading(true)
        setError(null)
        setSuccess(false)

        const payload: IntegrationsData = {
            odoo: {
                baseUrl: odooBaseUrl,
                db: odooDb,
                username: odooUsername,
                apiKey: odooApiKey
            }
        }

        const result = await updateOrganizationIntegrations(orgId, payload)

        if (result?.error) {
            setError(result.error)
        } else {
            setSuccess(true)
            setTimeout(() => setSuccess(false), 3000)
        }

        setLoading(false)
    }

    return (
        <form onSubmit={handleSubmit} className="space-y-8">
            {error && (
                <div className="bg-destructive/15 text-destructive text-sm p-3 rounded-md">
                    {error}
                </div>
            )}

            {/* Secção Odoo */}
            <div className="space-y-4">
                <h3 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground border-b pb-2">
                    Integração Odoo ERP
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-2">
                        <Label htmlFor="odooBaseUrl">URL do Servidor</Label>
                        <Input
                            id="odooBaseUrl"
                            type="url"
                            placeholder="https://meu-odoo.com"
                            value={odooBaseUrl}
                            onChange={(e) => setOdooBaseUrl(e.target.value)}
                        />
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="odooDb">Nome da Base de Dados</Label>
                        <Input
                            id="odooDb"
                            type="text"
                            value={odooDb}
                            onChange={(e) => setOdooDb(e.target.value)}
                        />
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="odooUsername">Utilizador (Email)</Label>
                        <Input
                            id="odooUsername"
                            type="text"
                            value={odooUsername}
                            onChange={(e) => setOdooUsername(e.target.value)}
                        />
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="odooApiKey">Password / API Key</Label>
                        <div className="relative">
                            <Input
                                id="odooApiKey"
                                type={showApiKey ? "text" : "password"}
                                placeholder="********"
                                value={odooApiKey}
                                onChange={(e) => setOdooApiKey(e.target.value)}
                                className="pr-10"
                            />
                            <button
                                type="button"
                                onClick={() => setShowApiKey(!showApiKey)}
                                className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
                            >
                                {showApiKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                            </button>
                        </div>
                    </div>
                </div>
            </div>



            <div className="pt-2 flex items-center justify-between">
                <div>
                    {success && <span className="text-sm text-green-600 font-medium">Configurações guardadas com sucesso!</span>}
                </div>
                <Button type="submit" disabled={loading}>
                    {loading ? (
                        <>
                            <Loader2 className="mr-2 h-4 w-4 animate-spin" /> Guardando...
                        </>
                    ) : (
                        <>
                            <Save className="mr-2 h-4 w-4" /> Guardar Integrações
                        </>
                    )}
                </Button>
            </div>
        </form>
    )
}
