"use client";

import { useEffect, useState } from "react";

import Link from "next/link";
import { useRouter } from "next/navigation";

import {
  ArrowLeft,
  Building2,
  CheckCircle2,
  ClipboardList,
  Command,
  Eye,
  EyeOff,
  Globe,
  Lock,
  Mail,
  Phone,
  User,
} from "lucide-react";

import { AuthLayout } from "@/components/silisuite/auth-layout";
import { GlassCard } from "@/components/silisuite/glass-card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { APP_CONFIG } from "@/config/app-config";
import { type RegisterData, register } from "@/lib/auth";

const FEATURES = [
  { icon: ClipboardList, text: "Full SiliSuite client portal on signup" },
  { icon: CheckCircle2, text: "SiliTalk, chatbots, integrations, and AI Director" },
  { icon: Building2, text: "Starter plan with scalable feature tiers" },
  { icon: Globe, text: "English or French preferred language" },
  { icon: Lock, text: "Secure client portal access" },
];

export default function RegisterPage() {
  const router = useRouter();

  const [form, setForm] = useState<RegisterData>({
    name: "",
    email: "",
    phone: "",
    language: "EN",
    password: "",
  });
  const [confirm, setConfirm] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [mounted, setMounted] = useState(false);

  const set = (field: keyof RegisterData, value: string) => {
    setForm((prev) => ({ ...prev, [field]: value }));
    setError("");
  };

  const validate = (): string | null => {
    if (!form.name.trim()) return "Full name is required.";
    if (!form.email.includes("@")) return "Please enter a valid email address.";
    if (!form.phone.trim()) return "Phone number is required.";
    if (form.password.length < 6) return "Password must be at least 6 characters.";
    if (form.password !== confirm) return "Passwords do not match.";
    return null;
  };

  useEffect(() => {
    setMounted(true);
    document.getElementById("name")?.focus();
  }, []);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const validationError = validate();
    if (validationError) {
      setError(validationError);
      return;
    }

    setLoading(true);
    setTimeout(() => {
      const result = register(form);
      if ("error" in result) {
        setError(result.error);
        setLoading(false);
        return;
      }
      router.replace("/portal");
    }, 500);
  };

  return (
    <AuthLayout>
      <div className="flex min-h-screen">
        {mounted && (
        <aside className="relative hidden w-[42%] flex-col justify-between p-10 lg:flex">
          <div className="flex items-center gap-2.5">
            <Command className="size-6 shrink-0" />
            <span className="font-bold text-xl tracking-tight">{APP_CONFIG.name}</span>
          </div>

          <div className="space-y-8">
            <div>
              <h1 className="font-bold text-3xl leading-tight">
                Your secure client
                <br />
                portal awaits.
              </h1>
              <p className="mt-3 text-muted-foreground text-sm leading-relaxed">
                Create your SiliSuite client portal account and start managing your AI operations.
              </p>
            </div>
            <div className="space-y-3">
              {FEATURES.map(({ icon: Icon, text }) => (
                <div key={text} className="flex items-center gap-3">
                  <div className="ss-glass flex size-7 shrink-0 items-center justify-center rounded-md">
                    <Icon className="size-3.5 text-muted-foreground" />
                  </div>
                  <span className="text-muted-foreground text-sm">{text}</span>
                </div>
              ))}
            </div>
          </div>

          <p className="text-muted-foreground text-xs">{APP_CONFIG.copyright}</p>
        </aside>
        )}

        <div className="flex flex-1 items-start justify-center overflow-y-auto px-6 py-10">
          <GlassCard className="w-full max-w-md space-y-7 p-8">
            {/* Mobile logo */}
            <div className="flex items-center gap-2 lg:hidden">
              <Command className="size-5 shrink-0" />
              <span className="font-bold">{APP_CONFIG.name}</span>
            </div>

            <div>
              <h2 className="font-bold text-2xl">Create your account</h2>
              <p className="mt-1 text-muted-foreground text-sm">Register to access your secure client portal.</p>
            </div>

            <form onSubmit={handleSubmit} className="space-y-4">
              {/* Full Name */}
              <div className="space-y-1.5">
                <Label htmlFor="name">Full Name *</Label>
                <div className="relative">
                  <User className="absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
                  <Input
                    id="name"
                    placeholder="Jane Doe"
                    value={form.name}
                    onChange={(e) => set("name", e.target.value)}
                    className="pl-9"
                  />
                </div>
              </div>

              {/* Email */}
              <div className="space-y-1.5">
                <Label htmlFor="email">Email Address *</Label>
                <div className="relative">
                  <Mail className="absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
                  <Input
                    id="email"
                    type="email"
                    placeholder="jane@example.com"
                    value={form.email}
                    onChange={(e) => set("email", e.target.value)}
                    className="pl-9"
                    autoComplete="email"
                  />
                </div>
              </div>

              {/* Phone */}
              <div className="space-y-1.5">
                <Label htmlFor="phone">Phone Number *</Label>
                <div className="relative">
                  <Phone className="absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
                  <Input
                    id="phone"
                    type="tel"
                    placeholder="+1 514-555-0100"
                    value={form.phone}
                    onChange={(e) => set("phone", e.target.value)}
                    className="pl-9"
                  />
                </div>
              </div>

              {/* Language */}
              <div className="space-y-1.5">
                <Label>Preferred Language *</Label>
                <div className="grid grid-cols-2 gap-2">
                  {(["EN", "FR"] as const).map((lang) => (
                    <button
                      key={lang}
                      type="button"
                      onClick={() => set("language", lang)}
                      className={`flex items-center gap-2 rounded-lg border px-3 py-2.5 text-sm transition-colors duration-150 ease-out ${form.language === lang ? "border-[var(--ss-accent)] bg-[var(--ss-accent)]/15 font-medium text-[var(--ss-accent)]" : "border-white/10 bg-white/5 hover:border-white/20"}`}
                    >
                      <Globe className="size-4 shrink-0 text-muted-foreground" />
                      {lang === "EN" ? "English" : "Français"}
                      {form.language === lang && <CheckCircle2 className="ml-auto size-4 text-primary" />}
                    </button>
                  ))}
                </div>
              </div>

              <Separator />

              {/* Password */}
              <div className="space-y-1.5">
                <Label htmlFor="password">Password *</Label>
                <div className="relative">
                  <Lock className="absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
                  <Input
                    id="password"
                    type={showPassword ? "text" : "password"}
                    placeholder="At least 6 characters"
                    value={form.password}
                    onChange={(e) => set("password", e.target.value)}
                    className="px-9"
                    autoComplete="new-password"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute top-1/2 right-3 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                  >
                    {showPassword ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
                  </button>
                </div>
              </div>

              {/* Confirm password */}
              <div className="space-y-1.5">
                <Label htmlFor="confirm">Confirm Password *</Label>
                <div className="relative">
                  <Lock className="absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
                  <Input
                    id="confirm"
                    type={showConfirm ? "text" : "password"}
                    placeholder="Re-enter your password"
                    value={confirm}
                    onChange={(e) => {
                      setConfirm(e.target.value);
                      setError("");
                    }}
                    className="px-9"
                    autoComplete="new-password"
                  />
                  <button
                    type="button"
                    onClick={() => setShowConfirm(!showConfirm)}
                    className="absolute top-1/2 right-3 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                  >
                    {showConfirm ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
                  </button>
                </div>
              </div>

              {error && (
                <div className="rounded-lg bg-destructive/10 px-3 py-2.5 text-destructive text-sm">{error}</div>
              )}

              <Button
                type="submit"
                className="h-10 w-full"
                disabled={loading || !form.name || !form.email || !form.phone || !form.password || !confirm}
              >
                {loading ? "Creating account…" : "Create account"}
              </Button>
            </form>

            <div className="space-y-3 text-center text-sm">
              <p className="text-muted-foreground">
                Already have an account?{" "}
                <Link href="/login" className="font-medium text-primary hover:underline">
                  Sign in
                </Link>
              </p>
              <Link
                href="/login"
                className="flex items-center justify-center gap-1 text-muted-foreground text-xs hover:text-foreground"
              >
                <ArrowLeft className="size-3" /> Back to login
              </Link>
            </div>

          </GlassCard>
        </div>
      </div>
    </AuthLayout>
  );
}
