"use client"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { createOrganization } from "../../actions"
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"
import { ArrowLeft, Loader2 } from "lucide-react"
import Link from "next/link"
import { useState } from "react"

export default function NewOrganizationPage() {
    const [loading, setLoading] = useState(false)

    const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault()
        setLoading(true)
        const formData = new FormData(event.currentTarget)
        const result = await createOrganization(formData)

        if (result?.error) {
            setLoading(false)

            alert(JSON.stringify(result.error))
        }
    }

    return (
        <div className="max-w-2xl mx-auto space-y-6">
            <div className="flex items-center gap-4">
                <Link href="/super-admin/organizations">
                    <Button variant="ghost" size="icon">
                        <ArrowLeft className="h-4 w-4" />
                    </Button>
                </Link>
                <h1 className="text-2xl font-bold tracking-tight">Nova Organização</h1>
            </div>

            <Card>
                <CardHeader>
                    <CardTitle>Configuração da Nova Organização</CardTitle>
                    <CardDescription>
                        Crie um novo tenant e configure o acesso do administrador inicial.
                    </CardDescription>
                </CardHeader>
                <CardContent>
                    <form onSubmit={handleSubmit} className="space-y-8">
                        {}
                        <div className="space-y-4">
                            <h3 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground border-b pb-2">
                                1. Dados da Organização
                            </h3>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label htmlFor="name">Nome da Empresa</Label>
                                    <Input
                                        id="name"
                                        name="name"
                                        placeholder="Ex: WibiX Tecnologia"
                                        required
                                        onChange={(e) => {
                                            const slugInput = document.getElementById("slug") as HTMLInputElement
                                            if (slugInput && !slugInput.dataset.touched) {
                                                slugInput.value = e.target.value
                                                    .toLowerCase()
                                                    .normalize("NFD").replace(/[\u0300-\u036f]/g, "")
                                                    .replace(/[^a-z0-9]/g, "-")
                                                    .replace(/-+/g, "-")
                                                    .replace(/^-|-$/g, "")
                                            }
                                        }}
                                    />
                                </div>

                                <div className="space-y-2">
                                    <Label htmlFor="slug">Slug (Subdomínio)</Label>
                                    <Input
                                        id="slug"
                                        name="slug"
                                        placeholder="Ex: wibix"
                                        required
                                        onFocus={(e) => { e.target.dataset.touched = "true" }}
                                    />
                                </div>
                            </div>
                        </div>

                        {}
                        <div className="space-y-4">
                            <h3 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground border-b pb-2">
                                2. Administrador do Cliente
                            </h3>
                            <div className="space-y-4">
                                <div className="space-y-2">
                                    <Label htmlFor="adminName">Nome Completo</Label>
                                    <Input id="adminName" name="adminName" placeholder="Nome do responsável" required />
                                </div>
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div className="space-y-2">
                                        <Label htmlFor="adminEmail">E-mail de Acesso</Label>
                                        <Input id="adminEmail" name="adminEmail" type="email" placeholder="email@cliente.com" required />
                                    </div>
                                    <div className="space-y-2">
                                        <Label htmlFor="adminPassword">Senha Inicial</Label>
                                        <Input id="adminPassword" name="adminPassword" type="password" required />
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className="pt-6 flex justify-end gap-3 border-t">
                            <Link href="/super-admin/organizations">
                                <Button variant="outline" type="button">Cancelar</Button>
                            </Link>
                            <Button type="submit" disabled={loading} className="min-w-[150px]">
                                {loading ? (
                                    <span className="flex items-center gap-2">
                                        <Loader2 className="h-4 w-4 animate-spin" /> Processando...
                                    </span>
                                ) : "Criar Organização"}
                            </Button>
                        </div>
                    </form>
                </CardContent>
            </Card>
        </div>
    )
}
