"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Eye, EyeOff, UserPlus } from "lucide-react";
import { useAuthStore } from "@/store/authStore";
import { Spinner } from "@/components/ui";
import toast from "react-hot-toast";

const schema = z.object({
  full_name: z.string().min(2, "Ad soyad en az 2 karakter olmalı."),
  username: z.string().min(3, "Kullanıcı adı en az 3 karakter.").max(50).regex(/^[a-z0-9_-]+$/, "Sadece küçük harf, rakam, _ ve - kullanılabilir."),
  email: z.string().email("Geçerli bir e-posta girin."),
  password: z.string().min(8, "Şifre en az 8 karakter olmalı."),
  confirm_password: z.string(),
}).refine((d) => d.password === d.confirm_password, {
  message: "Şifreler eşleşmiyor.",
  path: ["confirm_password"],
});

type FormData = z.infer<typeof schema>;

export default function KayitPage() {
  const router = useRouter();
  const { register: authRegister, isLoading } = useAuthStore();
  const [showPass, setShowPass] = useState(false);

  const { register, handleSubmit, formState: { errors } } = useForm<FormData>({
    resolver: zodResolver(schema),
  });

  const onSubmit = async (data: FormData) => {
    try {
      await authRegister({
        username: data.username,
        email: data.email,
        password: data.password,
        full_name: data.full_name,
      });
      toast.success("Hesabınız oluşturuldu! KaplanOS'a hoş geldiniz 🐯");
      router.push("/");
    } catch (err: any) {
      const msg = err?.response?.data?.detail || "Kayıt olurken bir hata oluştu.";
      toast.error(msg);
    }
  };

  return (
    <div className="kaplan-card">
      <h1 className="text-lg font-semibold text-surface-100 mb-1">Kayıt Ol</h1>
      <p className="text-sm text-surface-500 mb-6">Yeni bir KaplanOS hesabı oluşturun</p>

      <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className="form-label">Ad Soyad</label>
            <input {...register("full_name")} placeholder="Ali Yılmaz" className="kaplan-input" />
            {errors.full_name && <p className="text-xs text-red-400 mt-1">{errors.full_name.message}</p>}
          </div>
          <div>
            <label className="form-label">Kullanıcı Adı</label>
            <input {...register("username")} placeholder="ali_yilmaz" className="kaplan-input" />
            {errors.username && <p className="text-xs text-red-400 mt-1">{errors.username.message}</p>}
          </div>
        </div>

        <div>
          <label className="form-label">E-posta</label>
          <input {...register("email")} type="email" placeholder="ornek@email.com" className="kaplan-input" />
          {errors.email && <p className="text-xs text-red-400 mt-1">{errors.email.message}</p>}
        </div>

        <div>
          <label className="form-label">Şifre</label>
          <div className="relative">
            <input
              {...register("password")}
              type={showPass ? "text" : "password"}
              placeholder="En az 8 karakter"
              className="kaplan-input pr-10"
            />
            <button type="button" onClick={() => setShowPass(!showPass)} className="absolute right-3 top-1/2 -translate-y-1/2 text-surface-500">
              {showPass ? <EyeOff size={16} /> : <Eye size={16} />}
            </button>
          </div>
          {errors.password && <p className="text-xs text-red-400 mt-1">{errors.password.message}</p>}
        </div>

        <div>
          <label className="form-label">Şifre Tekrar</label>
          <input
            {...register("confirm_password")}
            type="password"
            placeholder="Şifrenizi tekrar girin"
            className="kaplan-input"
          />
          {errors.confirm_password && <p className="text-xs text-red-400 mt-1">{errors.confirm_password.message}</p>}
        </div>

        <button type="submit" disabled={isLoading} className="btn-primary w-full justify-center py-2.5">
          {isLoading ? <Spinner size={16} /> : <UserPlus size={16} />}
          Hesap Oluştur
        </button>
      </form>

      <p className="text-center text-sm text-surface-500 mt-6">
        Zaten hesabınız var mı?{" "}
        <Link href="/giris" className="text-brand-400 hover:text-brand-300 font-medium">
          Giriş Yap
        </Link>
      </p>
    </div>
  );
}
