'use client';

import { useTranslations } from 'next-intl';
import { z } from 'zod';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter, usePathname } from 'next/navigation';
import Link from 'next/link';
import { api } from '@/lib/api';
import { useMutation } from '@tanstack/react-query';
import {
  Form, FormControl, FormField, FormItem, FormLabel, FormMessage
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { useAuthStore } from '@/store/authStore';
import { Eye, EyeOff, Lock, Mail, User } from 'lucide-react';
import { useEffect, useState } from 'react';

export default function RegisterPage() {
  const t = useTranslations('Auth');
  const router = useRouter();
  const pathname = usePathname();
  const locale = pathname.startsWith('/en') ? 'en' : 'vi';
  const setToken = useAuthStore((state) => state.setToken);
  const setUser = useAuthStore((state) => state.setUser);
  const [showPw, setShowPw] = useState(false);
  const [telegramChallenge, setTelegramChallenge] = useState<{ id: string; deepLink: string } | null>(null);
  const [telegramError, setTelegramError] = useState('');
  const [telegramLoading, setTelegramLoading] = useState(false);

  useEffect(() => {
    if (!telegramChallenge) return;
    let cancelled = false;
    const browserSessionId = window.sessionStorage.getItem('shopmmo.telegram.browser') || window.crypto.randomUUID();
    window.sessionStorage.setItem('shopmmo.telegram.browser', browserSessionId);
    const timer = window.setInterval(async () => {
      try {
        const status = await api.get(`/telegram/login/challenge/${telegramChallenge.id}`, { params: { browserSessionId } });
        if (cancelled || status.data.status !== 'APPROVED') return;
        const response = await api.post(`/telegram/login/challenge/${telegramChallenge.id}/consume`, { browserSessionId });
        if (cancelled) return;
        setToken(response.data.access_token);
        if (response.data.user) setUser(response.data.user);
        window.clearInterval(timer);
        router.push(`/${locale}`);
      } catch {
        if (!cancelled) setTelegramError(locale === 'vi' ? 'Không thể kiểm tra trạng thái Telegram.' : 'Unable to check Telegram login status.');
      }
    }, 2000);
    return () => { cancelled = true; window.clearInterval(timer); };
  }, [telegramChallenge, locale, router, setToken, setUser]);

  const startTelegramRegistration = async () => {
    setTelegramError('');
    setTelegramLoading(true);
    try {
      const browserSessionId = window.sessionStorage.getItem('shopmmo.telegram.browser') || window.crypto.randomUUID();
      window.sessionStorage.setItem('shopmmo.telegram.browser', browserSessionId);
      const response = await api.post('/telegram/login/challenge', { browserSessionId });
      setTelegramChallenge({ id: response.data.challengeId, deepLink: response.data.deepLink });
      window.open(response.data.deepLink, '_blank', 'noopener,noreferrer');
    } catch {
      setTelegramError(locale === 'vi' ? 'Không thể tạo yêu cầu Telegram.' : 'Unable to create Telegram request.');
    } finally {
      setTelegramLoading(false);
    }
  };

  const formSchema = z.object({
    name: z.string().min(2),
    email: z.string().email(),
    password: z.string().min(6),
  });

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: { name: '', email: '', password: '' },
  });

  const registerMutation = useMutation({
    mutationFn: async (values: z.infer<typeof formSchema>) => {
      const response = await api.post('/auth/register', values);
      return response.data;
    },
    onSuccess: (data) => {
      setToken(data.access_token);
      router.push(`/${locale}`);
    },
  });

  return (
    <div className="min-h-screen bg-[#0f1117] flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        <div className="text-center mb-8">
          <h1 className="text-3xl font-black">
            <span className="bg-gradient-to-r from-violet-500 to-cyan-400 bg-clip-text text-transparent">SHOP</span>
            <span className="text-white">MMO</span>
          </h1>
          <p className="text-gray-400 mt-2 text-sm">{locale === 'vi' ? 'Marketplace Sản phẩm Số' : 'Digital Product Marketplace'}</p>
        </div>

        <div className="rounded-2xl border border-white/10 bg-white/5 backdrop-blur p-8 shadow-2xl">
          <h2 className="text-xl font-bold text-white mb-6">{t('register')}</h2>

          {registerMutation.isError && (
            <div className="mb-4 rounded-lg bg-red-500/10 border border-red-500/20 p-3 text-sm text-red-400">
              {(registerMutation.error as any)?.response?.data?.message || 'Đăng ký thất bại'}
            </div>
          )}

          <Form {...form}>
            <form onSubmit={form.handleSubmit((v) => registerMutation.mutate(v))} className="space-y-4">
              <FormField control={form.control} name="name" render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-gray-300">{t('name')}</FormLabel>
                  <FormControl>
                    <div className="relative">
                      <User className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-500" />
                      <Input placeholder="Nguyễn Văn A" {...field} className="pl-9 bg-white/5 border-white/10 text-white placeholder:text-gray-600 focus:border-violet-500" />
                    </div>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )} />

              <FormField control={form.control} name="email" render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-gray-300">{t('email')}</FormLabel>
                  <FormControl>
                    <div className="relative">
                      <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-500" />
                      <Input placeholder="you@example.com" {...field} className="pl-9 bg-white/5 border-white/10 text-white placeholder:text-gray-600 focus:border-violet-500" />
                    </div>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )} />

              <FormField control={form.control} name="password" render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-gray-300">{t('password')}</FormLabel>
                  <FormControl>
                    <div className="relative">
                      <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-500" />
                      <Input type={showPw ? 'text' : 'password'} {...field} className="pl-9 pr-10 bg-white/5 border-white/10 text-white focus:border-violet-500" />
                      <button type="button" onClick={() => setShowPw(!showPw)} className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-300">
                        {showPw ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                      </button>
                    </div>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )} />

              <Button type="submit" className="w-full h-11 bg-gradient-to-r from-violet-600 to-cyan-600 hover:opacity-90 text-white font-semibold" disabled={registerMutation.isPending}>
                {registerMutation.isPending ? (locale === 'vi' ? 'Đang tạo tài khoản...' : 'Creating account...') : t('register')}
              </Button>
            </form>
          </Form>

          <div className="my-5 flex items-center gap-3 text-xs text-gray-600"><span className="h-px flex-1 bg-white/10" />{locale === 'vi' ? 'hoặc' : 'or'}<span className="h-px flex-1 bg-white/10" /></div>
          <Button type="button" variant="outline" className="h-11 w-full border-cyan-400/30 text-cyan-300 hover:bg-cyan-400/10" onClick={startTelegramRegistration} disabled={telegramLoading}>
            {telegramLoading ? (locale === 'vi' ? 'Đang tạo yêu cầu...' : 'Creating request...') : (locale === 'vi' ? 'Đăng ký bằng Telegram' : 'Register with Telegram')}
          </Button>
          {telegramChallenge && <div className="mt-3 space-y-2 rounded-lg border border-cyan-400/20 bg-cyan-400/5 p-3 text-xs text-cyan-200"><p>{locale === 'vi' ? 'Đã tạo yêu cầu. Hãy mở đúng liên kết bên dưới và bấm START BOT/Xác nhận.' : 'Request created. Open the link below and press START BOT/Confirm.'}</p><a href={telegramChallenge.deepLink} target="_blank" rel="noreferrer" className="block break-all text-cyan-300 underline">{telegramChallenge.deepLink}</a><p className="break-all text-cyan-100/80">{locale === 'vi' ? 'Nếu Telegram chỉ gửi /start, hãy gửi đúng lệnh:' : 'If Telegram only sends /start, send this exact command:'} <code>{telegramChallenge.deepLink.match(/[?&]start=([^&]+)/)?.[1] ? `/start ${telegramChallenge.deepLink.match(/[?&]start=([^&]+)/)?.[1]}` : ''}</code></p></div>}
          {telegramError && <p className="mt-3 text-xs text-red-300">{telegramError}</p>}

          <div className="mt-6 text-center text-sm text-gray-500">
            {t('hasAccount')}{' '}
            <Link href={`/${locale}/auth/login`} className="text-violet-400 hover:text-violet-300 font-medium">
              {t('login')}
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
