import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useLocation } from "wouter";
import { useRegister } from "@workspace/api-client-react";
import { useQueryClient } from "@tanstack/react-query";
import { getGetMeQueryKey } from "@workspace/api-client-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useToast } from "@/hooks/use-toast";
import { useAppName, useAppSettings } from "@/hooks/use-app-settings";
import { useEffect } from "react";
import i18n from "@/i18n";

export default function RegisterPage() {
  const { t } = useTranslation();
  const appName = useAppName();
  const { data: settings, isLoading: settingsLoading } = useAppSettings();
  const [, setLocation] = useLocation();

  useEffect(() => {
    if (settings && !settings.registrationOpen) {
      setLocation("/login");
    }
  }, [settings, setLocation]);
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [form, setForm] = useState({
    username: "",
    email: "",
    password: "",
    displayNameAr: "",
    displayNameEn: "",
  });

  const register = useRegister();

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    register.mutate(
      { data: { ...form, preferredLanguage: i18n.language } },
      {
        onSuccess: () => {
          queryClient.invalidateQueries({ queryKey: getGetMeQueryKey() });
          setLocation("/");
        },
        onError: () => {
          toast({
            title: t("common.error"),
            variant: "destructive",
          });
        },
      },
    );
  };

  if (settingsLoading || (settings && !settings.registrationOpen)) {
    return (
      <div className="min-h-screen os-bg flex items-center justify-center p-4">
        <div className="glass-panel rounded-3xl p-8 w-full max-w-sm text-center space-y-3">
          <div className="text-2xl font-bold text-primary">{appName}</div>
          <p className="text-sm text-muted-foreground">{t("auth.registrationClosed")}</p>
          <Button onClick={() => setLocation("/login")} className="w-full">
            {t("auth.loginButton")}
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen os-bg flex items-center justify-center p-4">
      <div className="glass-panel rounded-3xl p-8 w-full max-w-sm space-y-6">
        <div className="text-center space-y-1">
          <div className="text-4xl font-bold text-primary mb-2">{appName}</div>
          <h1 className="text-xl font-semibold text-foreground">{t("auth.createAccount")}</h1>
        </div>

        <form onSubmit={handleSubmit} className="space-y-3">
          <div className="space-y-1">
            <Label htmlFor="username">{t("auth.username")}</Label>
            <Input
              id="username"
              value={form.username}
              onChange={(e) => setForm((f) => ({ ...f, username: e.target.value }))}
              required
              className="bg-white/70 border-slate-200"
            />
          </div>

          <div className="space-y-1">
            <Label htmlFor="email">{t("auth.email")}</Label>
            <Input
              id="email"
              type="email"
              value={form.email}
              onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))}
              required
              className="bg-white/70 border-slate-200"
            />
          </div>

          <div className="space-y-1">
            <Label htmlFor="password">{t("auth.password")}</Label>
            <Input
              id="password"
              type="password"
              value={form.password}
              onChange={(e) => setForm((f) => ({ ...f, password: e.target.value }))}
              required
              className="bg-white/70 border-slate-200"
            />
          </div>

          <div className="space-y-1">
            <Label htmlFor="displayNameAr">{t("auth.displayNameAr")}</Label>
            <Input
              id="displayNameAr"
              value={form.displayNameAr}
              onChange={(e) => setForm((f) => ({ ...f, displayNameAr: e.target.value }))}
              className="bg-white/70 border-slate-200"
              dir="rtl"
            />
          </div>

          <div className="space-y-1">
            <Label htmlFor="displayNameEn">{t("auth.displayNameEn")}</Label>
            <Input
              id="displayNameEn"
              value={form.displayNameEn}
              onChange={(e) => setForm((f) => ({ ...f, displayNameEn: e.target.value }))}
              className="bg-white/70 border-slate-200"
              dir="ltr"
            />
          </div>

          <Button type="submit" className="w-full" disabled={register.isPending}>
            {register.isPending ? t("common.loading") : t("auth.registerButton")}
          </Button>
        </form>

        <div className="text-center">
          <button
            onClick={() => setLocation("/login")}
            className="text-sm text-primary hover:underline"
          >
            {t("auth.login")}
          </button>
        </div>
      </div>
    </div>
  );
}
