'use client';

import { useState, useCallback } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useI18n } from '@/lib/i18n';
import {
  Eye,
  EyeOff,
  Mail,
  Lock,
  ArrowRight,
  Loader2,
  CheckCircle,
  AlertTriangle,
  UserPlus,
  Languages,
  User,
} from 'lucide-react';
import { GoogleLogin } from '@react-oauth/google';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { useNotification } from '@/components/ui/notification';
import { apiClient } from '@/lib/apiClient';
import { useRegister } from './useRegister';
import { cn } from '@/lib/utils';
import type { GoogleAuthResponse } from '../login/types';
import { useGoogleConfig } from '@/providers/ClientGoogleProvider';

function validateEmail(email: string) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

function validatePassword(password: string) {
  return password.length >= 8
    && /[A-Z]/.test(password)
    && /[a-z]/.test(password)
    && /[0-9]/.test(password);
}

function getPasswordStrength(password: string) {
  if (password.length === 0) return { score: 0, labelKey: '', color: '' };
  let score = 0;
  if (password.length >= 8) score++;
  if (password.length >= 12) score++;
  if (/[A-Z]/.test(password)) score++;
  if (/[a-z]/.test(password)) score++;
  if (/[0-9]/.test(password)) score++;
  if (/[^A-Za-z0-9]/.test(password)) score++;

  if (score <= 2) return { score, labelKey: 'register.password.strength.weak', color: 'bg-destructive' };
  if (score <= 4) return { score, labelKey: 'register.password.strength.medium', color: 'bg-yellow-500' };
  return { score, labelKey: 'register.password.strength.strong', color: 'bg-green-500' };
}

function PasswordToggleIcon({ visible, onToggle, label }: { visible: boolean; onToggle: () => void; label: string }) {
  return (
    <button
      type="button"
      onClick={onToggle}
      className="text-muted-foreground hover:text-foreground transition-colors duration-200 pointer-events-auto"
      aria-label={label}
      aria-pressed={visible}
    >
      {visible ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
    </button>
  );
}

export function RegisterForm() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const [googleLoading, setGoogleLoading] = useState(false);
  const [touched, setTouched] = useState({ name: false, email: false, password: false, confirmPassword: false });

  const registerMutation = useRegister();
  const { notify } = useNotification();
  const { t } = useI18n();
  const router = useRouter();
  const searchParams = useSearchParams();
  const redirect = searchParams.get('redirect') || '/dashboard';

  const { clientId: googleClientId, enabled: googleEnabled } = useGoogleConfig();

  const nameError = touched.name && name.length > 0 && name.length < 2
    ? t('register.name.error')
    : undefined;

  const emailError = touched.email && email.length > 0 && !validateEmail(email)
    ? t('register.email.error')
    : undefined;

  const passwordError = touched.password && password.length > 0 && !validatePassword(password)
    ? t('register.password.error')
    : undefined;

  const confirmError = touched.confirmPassword && confirmPassword.length > 0 && password !== confirmPassword
    ? t('register.confirmPassword.error')
    : undefined;

  const passwordStrength = getPasswordStrength(password);

  const isFormValid =
    name.length >= 2 &&
    validateEmail(email) &&
    validatePassword(password) &&
    password === confirmPassword;

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setTouched({ name: true, email: true, password: true, confirmPassword: true });
    if (!isFormValid) return;
    registerMutation.mutate({ name, email, password });
  };

  const getConfirmRightIcon = () => {
    if (touched.confirmPassword && confirmPassword.length > 0 && password === confirmPassword) {
      return <CheckCircle className="h-4 w-4 text-green-500" />;
    }
    return (
      <PasswordToggleIcon
        visible={showConfirm}
        onToggle={() => setShowConfirm(!showConfirm)}
        label={showConfirm ? t('register.confirmPassword.hide') : t('register.confirmPassword.show')}
      />
    );
  };

  const handleGoogleSuccess = useCallback(async (credentialResponse: { credential?: string }) => {
    if (!credentialResponse.credential) return;
    setGoogleLoading(true);
    try {
      const response = await apiClient.post<{ data: GoogleAuthResponse }>(
        '/api/v1/auth/google',
        { credential: credentialResponse.credential },
      );
      const { access_token, refresh_token } = response.data;
      localStorage.setItem('token', access_token);
      localStorage.setItem('refresh_token', refresh_token);
      router.push(redirect);
    } catch {
      notify({
        title: t('login.google.errorGeneric'),
        description: t('login.google.errorFailed'),
        variant: 'destructive',
      });
    } finally {
      setGoogleLoading(false);
    }
  }, [redirect, router, notify, t]);

  const handleGoogleError = useCallback(() => {
    notify({
      title: t('login.google.errorGeneric'),
      description: t('login.google.errorFailed'),
      variant: 'destructive',
    });
  }, [notify, t]);

  return (
    <Card variant="elevated" className="w-full max-w-md mx-auto" hover={false}>
      <CardHeader className="text-center pb-6">
        <Link href="/" className="inline-flex items-center gap-3 mb-6 group">
          <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-primary text-primary-foreground shadow-lg group-hover:shadow-xl group-hover:shadow-primary/25 transition-all duration-300 group-hover:-translate-y-0.5">
            <Languages className="h-6 w-6" />
          </div>
          <span className="text-2xl font-semibold text-foreground group-hover:text-primary transition-colors duration-300">
            {t('auth.brandName')}
          </span>
        </Link>

        <CardTitle className="text-2xl font-bold">{t('register.title')}</CardTitle>
        <CardDescription>{t('register.subtitle')}</CardDescription>
      </CardHeader>

      <CardContent className="space-y-5">
        {googleEnabled && googleClientId && (
          <>
            <div className="flex justify-center">
              {googleLoading ? (
                <Button variant="outline" className="w-full" disabled>
                  <Loader2 className="me-2 h-4 w-4 animate-spin" />
                  {t('login.google.connecting')}
                </Button>
              ) : (
                <GoogleLogin
                  onSuccess={handleGoogleSuccess}
                  onError={handleGoogleError}
                  text="signup_with"
                  shape="rectangular"
                  size="large"
                  width={380}
                />
              )}
            </div>

            <div className="relative">
              <div className="absolute inset-0 flex items-center">
                <span className="w-full border-t" />
              </div>
              <div className="relative flex justify-center text-xs uppercase">
                <span className="bg-card px-2 text-muted-foreground">
                  {t('login.orContinueWith')}
                </span>
              </div>
            </div>
          </>
        )}

        {registerMutation.isError && (
          <div className="rounded-lg bg-destructive/10 border border-destructive/30 p-4">
            <div className="flex items-start gap-3">
              <AlertTriangle className="h-5 w-5 text-destructive flex-shrink-0 mt-0.5" />
              <p className="text-sm text-destructive">
                {registerMutation.error?.message || t('register.error.failed')}
              </p>
            </div>
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="name">{t('register.name.label')}</Label>
            <Input
              id="name"
              type="text"
              placeholder={t('register.name.placeholder')}
              value={name}
              onChange={(e) => setName(e.target.value)}
              onBlur={() => setTouched((t) => ({ ...t, name: true }))}
              leftIcon={<User className="h-4 w-4" />}
              rightIcon={
                touched.name && name.length > 0
                  ? name.length >= 2
                    ? <CheckCircle className="h-4 w-4 text-green-500" />
                    : <AlertTriangle className="h-4 w-4 text-destructive" />
                  : undefined
              }
              error={nameError}
              required
              autoComplete="name"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="email">{t('register.email.label')}</Label>
            <Input
              id="email"
              type="email"
              placeholder={t('register.email.placeholder')}
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              onBlur={() => setTouched((t) => ({ ...t, email: true }))}
              leftIcon={<Mail className="h-4 w-4" />}
              rightIcon={
                touched.email && email.length > 0
                  ? validateEmail(email)
                    ? <CheckCircle className="h-4 w-4 text-green-500" />
                    : <AlertTriangle className="h-4 w-4 text-destructive" />
                  : undefined
              }
              error={emailError}
              required
              autoComplete="email"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="password">{t('register.password.label')}</Label>
            <Input
              id="password"
              type={showPassword ? 'text' : 'password'}
              placeholder="••••••••"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              onBlur={() => setTouched((t) => ({ ...t, password: true }))}
              leftIcon={<Lock className="h-4 w-4" />}
              rightIcon={
                <PasswordToggleIcon
                  visible={showPassword}
                  onToggle={() => setShowPassword(!showPassword)}
                  label={showPassword ? t('register.password.hide') : t('register.password.show')}
                />
              }
              error={passwordError}
              required
              minLength={8}
              autoComplete="new-password"
            />
            {password.length > 0 && (
              <div className="space-y-1 pt-1">
                <div className="flex gap-1">
                  {[1, 2, 3, 4].map((level) => (
                    <div
                      key={level}
                      className={cn(
                        'h-1 flex-1 rounded-full transition-all duration-300',
                        level <= Math.ceil((passwordStrength.score / 6) * 4)
                          ? passwordStrength.color
                          : 'bg-border'
                      )}
                    />
                  ))}
                </div>
                <p className={cn('text-xs', passwordStrength.score <= 2 ? 'text-destructive' : passwordStrength.score <= 4 ? 'text-muted-foreground' : 'text-green-500')}>
                  {t('register.password.strengthLabel')} {passwordStrength.labelKey ? t(passwordStrength.labelKey) : ''}
                </p>
              </div>
            )}
          </div>

          <div className="space-y-2">
            <Label htmlFor="confirmPassword">{t('register.confirmPassword.label')}</Label>
            <Input
              id="confirmPassword"
              type={showConfirm ? 'text' : 'password'}
              placeholder="••••••••"
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
              onBlur={() => setTouched((t) => ({ ...t, confirmPassword: true }))}
              leftIcon={<Lock className="h-4 w-4" />}
              rightIcon={getConfirmRightIcon()}
              error={confirmError}
              required
              autoComplete="new-password"
            />
          </div>

          <Button
            type="submit"
            size="lg"
            className="w-full"
            disabled={registerMutation.isPending}
            loading={registerMutation.isPending}
          >
            {registerMutation.isPending ? (
              <>
                <Loader2 className="me-2 h-4 w-4 animate-spin" />
                {t('register.submit.creating')}
              </>
            ) : (
              <>
                <UserPlus className="me-2 h-4 w-4" />
                {t('register.submit.create')}
                <ArrowRight className="ms-2 h-4 w-4" />
              </>
            )}
          </Button>
        </form>

        <p className="text-center text-sm text-muted-foreground">
          {t('register.hasAccount')}{' '}
          <Link href="/auth/login" className="text-primary hover:underline font-medium">
            {t('register.login')}
          </Link>
        </p>

        <p className="text-center text-xs text-muted-foreground">
          {t('register.terms.prefix')}{' '}
          <span className="text-muted-foreground/80">
            {t('register.terms.link')}
          </span>
          .
        </p>
      </CardContent>
    </Card>
  );
}
