'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';

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 [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)
    ? 'Le mot de passe doit contenir au moins 8 caracteres, une majuscule, une minuscule et un chiffre'
    : '';

  const confirmError = confirmPassword.length > 0 && password !== confirmPassword
    ? 'Les mots de passe ne correspondent pas'
    : '';

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

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

    if (!token) {
      setError('Token manquant. Veuillez utiliser le lien recu par email.');
      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 : "Une erreur s'est produite";
      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">
              Office Translator
            </span>
          </Link>
          <CardTitle className="text-2xl font-bold">Lien invalide</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">
              Ce lien de reinitialisation est invalide. Veuillez redemander un nouveau lien.
            </p>
          </div>
          <p className="text-center text-sm text-muted-foreground">
            <Link href="/auth/forgot-password" className="text-primary hover:underline font-medium">
              Redemander un lien
            </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">
            Office Translator
          </span>
        </Link>

        <CardTitle className="text-2xl font-bold">
          {success ? 'Mot de passe reinitialise' : 'Nouveau mot de passe'}
        </CardTitle>
        <CardDescription>
          {success
            ? 'Vous allez etre redirige vers la connexion'
            : 'Definissez votre nouveau mot de passe'}
        </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">
                Votre mot de passe a ete reinitialise avec succes. Vous allez etre redirige vers la page de connexion.
              </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">Nouveau mot de passe</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 ? 'Masquer' : 'Afficher'} le mot de passe
              </button>
            </div>

            <div className="space-y-2">
              <Label htmlFor="confirmPassword">Confirmer le mot de passe</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 ? 'Masquer' : 'Afficher'} le mot de passe
              </button>
            </div>

            <Button
              type="submit"
              variant="premium"
              size="lg"
              className="w-full"
              disabled={loading || !isFormValid}
              loading={loading}
            >
              {loading ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Reinitialisation...
                </>
              ) : (
                'Reinitialiser le mot de passe'
              )}
            </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" />
            Retour a la connexion
          </Link>
        </p>
      </CardContent>
    </Card>
  );
}

function LoadingFallback() {
  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">Chargement...</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>
  );
}
