'use client';

import Link from 'next/link';
import { FormEvent, useState } from 'react';
import { useRouter } from 'next/navigation';
import { ShieldCheck } from 'lucide-react';
import { BrandLogo } from '@/components/id/brand-logo';
import { useAuth } from '@/components/id/auth-provider';
import { useToast } from '@/components/id/toast-provider';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { PhoneInput, phoneCountries, toE164 } from '@/components/ui/phone-input';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';

export default function RegisterPage() {
  const router = useRouter();
  const { sendLoginOtp } = useAuth();
  const { showToast } = useToast();
  const [authTab, setAuthTab] = useState<'email' | 'phone'>('email');
  const [email, setEmail] = useState('');
  const [phoneNumber, setPhoneNumber] = useState('');
  const [country, setCountry] = useState(phoneCountries[0]);
  const [isSubmitting, setIsSubmitting] = useState(false);

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setIsSubmitting(true);
    try {
      const recipient = authTab === 'email' ? email.trim() : toE164(country, phoneNumber);
      await sendLoginOtp(recipient);
      showToast('Код отправлен. Подтвердите его на экране входа.');
      router.push('/auth/login');
    } catch (error) {
      showToast(error instanceof Error ? error.message : 'Не удалось отправить код');
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <main className="flex min-h-screen items-center justify-center bg-[radial-gradient(circle_at_center,#5d6578_0%,#2c2736_48%,#111016_100%)] px-5">
      <section className="w-full max-w-[430px] rounded-[34px] bg-[#1f2028] px-9 py-10 text-white shadow-2xl">
        <div className="flex flex-col items-center text-center">
          <BrandLogo size="lg" variant="light" />
          <h1 className="mt-8 text-xl font-bold">Создайте ID</h1>
          <p className="mt-2 text-sm text-[#b9bdc9]">Введите почту или телефон. Пароль не нужен.</p>
        </div>
        <form className="mt-8 space-y-3" onSubmit={handleSubmit}>
          <Tabs value={authTab} onValueChange={(value) => setAuthTab(value as 'email' | 'phone')} className="w-full">
            <TabsList className="grid w-full grid-cols-2">
              <TabsTrigger value="email">Почта</TabsTrigger>
              <TabsTrigger value="phone">Телефон</TabsTrigger>
            </TabsList>
            <TabsContent value="email">
              <Input
                className="h-[56px] border-[#555762] bg-transparent text-white placeholder:text-[#8f92a0]"
                placeholder="name@example.com"
                type="email"
                value={email}
                onChange={(event) => setEmail(event.target.value)}
                required={authTab === 'email'}
              />
            </TabsContent>
            <TabsContent value="phone">
              <PhoneInput country={country} value={phoneNumber} onCountryChange={setCountry} onValueChange={setPhoneNumber} />
            </TabsContent>
          </Tabs>
          <Button variant="white" size="lg" className="w-full rounded-[18px]" disabled={isSubmitting}>
            {isSubmitting ? 'Отправляем...' : 'Получить код'}
          </Button>
        </form>
        <Button asChild variant="ghost" className="mt-5 w-full text-white hover:bg-[#2a2c36]">
          <Link href="/auth/login">У меня уже есть ID</Link>
        </Button>
      </section>
    </main>
  );
}
