'use client';

import { useState, Suspense } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { Lock, Loader2, Languages, Eye, EyeOff, CheckCircle, ArrowLeft } from 'lucide-react';
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 { apiClient } from '@/lib/apiClient';
import { useI18n } from '@/lib/i18n';

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

function ResetPasswordForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const token = searchParams.get('token');
  const { t } = useI18n();

  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);

  const passwordError = password.length > 0 && !validatePassword(password)
    ? t('resetPassword.passwordRequirements')
    : '';

  const confirmError = confirmPassword.length > 0 && password !== confirmPassword
    ? t('resetPassword.passwordMismatch')
    : '';

  const isFormValid = validatePassword(password) && password === confirmPassword;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    if (!token) {
      setError(t('resetPassword.tokenMissing'));
      return;
    }

    if (!isFormValid) return;

    setLoading(true);
    try {
      await apiClient.post('/api/v1/auth/reset-password', { token, password });
      setSuccess(true);
      setTimeout(() => {
        router.push('/auth/login');
      }, 3000);
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : t('resetPassword.error');
      setError(message);
    } finally {
      setLoading(false);
    }
  };

  if (!token) {
    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">
              <Languages className="h-6 w-6" />
            </div>
            <span className="text-2xl font-semibold text-foreground">
              {t('auth.brandName')}
            </span>
          </Link>
          <CardTitle className="text-2xl font-bold">{t('resetPassword.invalidLink')}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-5">
          <div className="rounded-lg bg-destructive/10 border border-destructive/30 p-4">
            <p className="text-sm text-destructive">
              {t('resetPassword.invalidLinkMessage')}
            </p>
          </div>
          <p className="text-center text-sm text-muted-foreground">
            <Link href="/auth/forgot-password" className="text-primary hover:underline font-medium">
              {t('resetPassword.requestNewLink')}
            </Link>
          </p>
        </CardContent>
      </Card>
    );
  }

  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">
          {success ? t('resetPassword.successTitle') : t('resetPassword.newPasswordTitle')}
        </CardTitle>
        <CardDescription>
          {success
            ? t('resetPassword.successSubtitle')
            : t('resetPassword.subtitle')}
        </CardDescription>
      </CardHeader>

      <CardContent className="space-y-5">
        {success ? (
          <div className="rounded-lg bg-green-50 border border-green-200 p-4 dark:bg-green-950/20 dark:border-green-900">
            <div className="flex items-start gap-3">
              <CheckCircle className="h-5 w-5 text-green-600 flex-shrink-0 mt-0.5" />
              <p className="text-sm text-green-800 dark:text-green-200">
                {t('resetPassword.successMessage')}
              </p>
            </div>
          </div>
        ) : (
          <form onSubmit={handleSubmit} className="space-y-4">
            {error && (
              <div className="rounded-lg bg-destructive/10 border border-destructive/30 p-4">
                <p className="text-sm text-destructive">{error}</p>
              </div>
            )}

            <div className="space-y-2">
              <Label htmlFor="password">{t('resetPassword.newPassword')}</Label>
              <div className="relative">
                <Input
                  id="password"
                  type={showPassword ? 'text' : 'password'}
                  placeholder="••••••••"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  leftIcon={<Lock className="h-4 w-4" />}
                  error={passwordError}
                  required
                  autoComplete="new-password"
                />
              </div>
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                className="text-xs text-muted-foreground hover:text-foreground"
              >
                {showPassword ? t('resetPassword.hidePassword') : t('resetPassword.showPassword')}
              </button>
            </div>

            <div className="space-y-2">
              <Label htmlFor="confirmPassword">{t('resetPassword.confirmPassword')}</Label>
              <div className="relative">
                <Input
                  id="confirmPassword"
                  type={showConfirm ? 'text' : 'password'}
                  placeholder="••••••••"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  leftIcon={<Lock className="h-4 w-4" />}
                  error={confirmError}
                  required
                  autoComplete="new-password"
                />
              </div>
              <button
                type="button"
                onClick={() => setShowConfirm(!showConfirm)}
                className="text-xs text-muted-foreground hover:text-foreground"
              >
                {showConfirm ? t('resetPassword.hidePassword') : t('resetPassword.showPassword')}
              </button>
            </div>

            <Button
              type="submit"
              variant="premium"
              size="lg"
              className="w-full"
              disabled={loading || !isFormValid}
              loading={loading}
            >
              {loading ? (
                <>
                  <Loader2 className="me-2 h-4 w-4 animate-spin" />
                  {t('resetPassword.resetting')}
                </>
              ) : (
                t('resetPassword.resetPassword')
              )}
            </Button>
          </form>
        )}

        <p className="text-center text-sm text-muted-foreground">
          <Link href="/auth/login" className="text-primary hover:underline font-medium inline-flex items-center gap-1">
            <ArrowLeft className="h-3 w-3" />
            {t('resetPassword.backToLogin')}
          </Link>
        </p>
      </CardContent>
    </Card>
  );
}

function LoadingFallback() {
  const { t } = useI18n();
  return (
    <div className="w-full max-w-md mx-auto">
      <div className="rounded-xl bg-card border border-border shadow-lg p-8">
        <div className="flex flex-col items-center justify-center py-8 space-y-4">
          <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-primary text-primary-foreground">
            <Languages className="h-6 w-6" />
          </div>
          <Loader2 className="h-8 w-8 animate-spin text-primary" />
          <p className="text-muted-foreground">{t('resetPassword.loading')}</p>
        </div>
      </div>
    </div>
  );
}

export default function ResetPasswordPage() {
  return (
    <div className="min-h-screen bg-gradient-to-br from-surface via-surface-elevated to-background flex items-center justify-center p-4 relative overflow-hidden">
      <div className="absolute inset-0">
        <div className="absolute inset-0 bg-gradient-to-br from-primary/5 via-transparent to-accent/5" />
        <div className="absolute inset-0 bg-[url('/grid.svg')] opacity-5" />
        <div className="absolute inset-0 bg-gradient-to-t from-background via-background/90 to-background/50" />
      </div>

      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className="absolute top-20 left-10 w-32 h-32 bg-primary/5 rounded-full blur-3xl animate-pulse" />
        <div className="absolute bottom-20 right-20 w-24 h-24 bg-accent/5 rounded-full blur-2xl animate-pulse" />
      </div>

      <Suspense fallback={<LoadingFallback />}>
        <ResetPasswordForm />
      </Suspense>
    </div>
  );
}
