"use client";

import React, { useState } from "react";
import { createUserWithEmailAndPassword } from "firebase/auth";
import { ref, set } from "firebase/database";
import { auth, db } from "@/lib/firebase";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import Link from "next/link";

export default function RegisterPage() {
  const [formData, setFormData] = useState({
    ownerName: "",
    ownerPhone: "",
    establishmentName: "",
    email: "",
    establishmentPhone: "",
    password: "",
  });
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const router = useRouter();

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData({ ...formData, [e.target.id]: e.target.value });
  };

  const buildDocumentId = (email: string) => {
    return email.replace(/\./g, "_").replace(/@/g, "_at_");
  };

  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setLoading(true);

    // Validate inputs before attempting registration
    if (!formData.email || !formData.email.includes("@")) {
      setError("Por favor, insira um email válido.");
      setLoading(false);
      return;
    }
    if (formData.password.length < 6) {
      setError("A palavra-passe deve ter pelo menos 6 caracteres.");
      setLoading(false);
      return;
    }
    if (!formData.establishmentName.trim()) {
      setError("Por favor, insira o nome do restaurante.");
      setLoading(false);
      return;
    }

    try {
      // 1. Criar utilizador na Firebase Auth
      const userCredential = await createUserWithEmailAndPassword(auth, formData.email, formData.password);
      const user = userCredential.user;

      // 2. Preparar payload conforme a App Android
      const documentId = buildDocumentId(formData.email);
      const payload = {
        uid: user.uid,
        email: formData.email,
        displayName: formData.establishmentName,
        role: "ADMIN",
        accountType: "ESTABELECIMENTO",
        createdAt: Date.now(),
        ownerName: formData.ownerName,
        ownerEmail: formData.email,
        ownerPhone: formData.ownerPhone,
        establishmentName: formData.establishmentName,
        establishmentEmail: formData.email,
        establishmentPhone: formData.establishmentPhone,
      };

      // 3. Gravar na Realtime Database em /Restaurantes
      await set(ref(db, `Restaurantes/${documentId}`), payload);

      // 4. Success — redirect to dashboard
      router.push("/");
    } catch (err: any) {
      console.error("[Register Error]", err.code, err.message);
      
      // Map Firebase Auth error codes to user-friendly messages in Portuguese
      switch (err.code) {
        case "auth/email-already-in-use":
          setError("Este email já está registado. Tente fazer login.");
          break;
        case "auth/weak-password":
          setError("A palavra-passe deve ter pelo menos 6 caracteres.");
          break;
        case "auth/invalid-email":
          setError("Email inválido. Verifique o formato do email.");
          break;
        case "auth/operation-not-allowed":
          setError("Registo de contas está desactivado. Contacte o suporte.");
          break;
        case "auth/network-request-failed":
          setError("Erro de conexão. Verifique a sua ligação à internet.");
          break;
        case "auth/too-many-requests":
          setError("Demasiadas tentativas. Aguarde alguns minutos e tente novamente.");
          break;
        case "auth/invalid-credential":
          setError("Credenciais inválidas.");
          break;
        default:
          setError(`Erro ao criar conta: ${err.message || "Tente novamente."}`);
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card className="w-full max-w-lg mx-auto">
      <CardHeader className="space-y-1 text-center">
        <CardTitle className="text-3xl text-primary">Novo Restaurante</CardTitle>
        <CardDescription>
          Crie a sua conta de gestão no ReservaMesa
        </CardDescription>
      </CardHeader>
      <form onSubmit={handleRegister}>
        <CardContent className="space-y-4">
          {error && (
            <div className="bg-destructive/15 text-destructive text-sm p-3 rounded-md">
              {error}
            </div>
          )}
          
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="establishmentName">Nome do Restaurante</Label>
              <Input id="establishmentName" value={formData.establishmentName} onChange={handleChange} required />
            </div>
            <div className="space-y-2">
              <Label htmlFor="establishmentPhone">Telefone do Restaurante</Label>
              <Input id="establishmentPhone" type="tel" value={formData.establishmentPhone} onChange={handleChange} required />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="ownerName">Nome do Responsável</Label>
              <Input id="ownerName" value={formData.ownerName} onChange={handleChange} required />
            </div>
            <div className="space-y-2">
              <Label htmlFor="ownerPhone">Telemóvel Pessoal</Label>
              <Input id="ownerPhone" type="tel" value={formData.ownerPhone} onChange={handleChange} required />
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="email">Email Principal (Login)</Label>
            <Input id="email" type="email" value={formData.email} onChange={handleChange} required />
          </div>

          <div className="space-y-2">
            <Label htmlFor="password">Palavra-passe</Label>
            <Input id="password" type="password" value={formData.password} onChange={handleChange} required minLength={6} />
          </div>

        </CardContent>
        <CardFooter className="flex flex-col space-y-4">
          <Button type="submit" className="w-full" disabled={loading}>
            {loading ? "A registar..." : "Registar e Entrar"}
          </Button>
          <div className="text-center text-sm text-muted-foreground">
            Já tem conta?{" "}
            <Link href="/login" className="text-primary hover:underline">
              Iniciar sessão
            </Link>
          </div>
        </CardFooter>
      </form>
    </Card>
  );
}
