"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { createClient } from "@/lib/supabase/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardFooter } from "@/components/ui/card";
import { Loader2 } from "lucide-react";

export default function RegisterPage() {
  const router = useRouter();
  const supabase = createClient();
  const [form, setForm] = useState({ clinicName: "", fullName: "", email: "", password: "" });
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  function update(field: string, value: string) {
    setForm((prev) => ({ ...prev, [field]: value }));
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setLoading(true);

    const { data: authData, error: authError } = await supabase.auth.signUp({ email: form.email, password: form.password });
    if (authError || !authData.user) {
      setError(authError?.message || "Error al crear cuenta");
      setLoading(false);
      return;
    }

    const slug = form.clinicName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
    const { data: clinic, error: clinicError } = await supabase.from("clinics").insert({ name: form.clinicName, slug }).select().single();
    if (clinicError) {
      setError("Error al crear clinica: " + clinicError.message);
      setLoading(false);
      return;
    }

    const { error: userError } = await supabase.from("users").insert({
      id: authData.user.id,
      clinic_id: clinic.id,
      full_name: form.fullName,
      email: form.email,
      role: "owner",
    });

    if (userError) {
      setError("Error al crear perfil: " + userError.message);
      setLoading(false);
      return;
    }

    router.push("/dashboard");
  }

  return (
    <div className="space-y-6">
      <div className="space-y-2 text-center">
        <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-primary/10 lg:hidden">
          <svg xmlns="http://www.w3.org/2000/svg" className="h-7 w-7 text-primary" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 2a2 2 0 0 0-2 2v5H4a2 2 0 0 0-2 2v2c0 1.1.9 2 2 2h5v5c0 1.1.9 2 2 2h2a2 2 0 0 0 2-2v-5h5a2 2 0 0 0 2-2v-2a2 2 0 0 0-2-2h-5V4a2 2 0 0 0-2-2h-2z"/></svg>
        </div>
        <h1 className="text-2xl font-bold tracking-tight">Registra tu clinica</h1>
        <p className="text-sm text-muted-foreground">Prueba gratis por 14 dias. Sin tarjeta de credito.</p>
      </div>
      <Card className="border-0 shadow-lg lg:shadow-none">
        <form onSubmit={handleSubmit}>
          <CardContent className="space-y-4 pt-6">
            {error && (
              <div className="rounded-lg bg-destructive/10 p-3 text-sm text-destructive">{error}</div>
            )}
            <div className="space-y-2">
              <Label htmlFor="clinicName">Nombre de la clinica</Label>
              <Input id="clinicName" placeholder="Clinica San Jose" value={form.clinicName} onChange={(e) => update("clinicName", e.target.value)} required className="h-11" />
            </div>
            <div className="space-y-2">
              <Label htmlFor="fullName">Tu nombre completo</Label>
              <Input id="fullName" placeholder="Dr. Juan Perez" value={form.fullName} onChange={(e) => update("fullName", e.target.value)} required className="h-11" />
            </div>
            <div className="space-y-2">
              <Label htmlFor="email">Correo electronico</Label>
              <Input id="email" type="email" placeholder="doctor@clinica.com" value={form.email} onChange={(e) => update("email", e.target.value)} required className="h-11" />
            </div>
            <div className="space-y-2">
              <Label htmlFor="password">Contrasena</Label>
              <Input id="password" type="password" placeholder="Minimo 6 caracteres" value={form.password} onChange={(e) => update("password", e.target.value)} minLength={6} required className="h-11" />
            </div>
          </CardContent>
          <CardFooter className="flex flex-col gap-4 pb-6">
            <Button type="submit" className="h-11 w-full text-base" disabled={loading}>
              {loading ? <><Loader2 className="mr-2 h-4 w-4 animate-spin" /> Creando cuenta...</> : "Crear cuenta gratis"}
            </Button>
            <p className="text-center text-sm text-muted-foreground">
              Ya tienes cuenta?{" "}
              <Link href="/login" className="font-medium text-primary hover:underline">Inicia sesion</Link>
            </p>
          </CardFooter>
        </form>
      </Card>
    </div>
  );
}
