'use client';

import { Suspense, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { toast } from 'sonner';
import { CheckCircle2, Circle } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

const passwordSchema = z
  .object({
    password: z
      .string()
      .min(12, 'Must be at least 12 characters')
      .regex(/[A-Z]/, 'Must contain an uppercase letter')
      .regex(/[a-z]/, 'Must contain a lowercase letter')
      .regex(/[0-9]/, 'Must contain a number')
      .regex(/[^A-Za-z0-9]/, 'Must contain a special character'),
    confirmPassword: z.string().min(1, 'Please confirm your password'),
  })
  .refine((data) => data.password === data.confirmPassword, {
    message: 'Passwords do not match',
    path: ['confirmPassword'],
  });

type SetPasswordFormData = z.infer<typeof passwordSchema>;

type Requirement = {
  label: string;
  test: (value: string) => boolean;
};

const requirements: Requirement[] = [
  { label: 'At least 12 characters', test: (v) => v.length >= 12 },
  { label: 'Uppercase letter', test: (v) => /[A-Z]/.test(v) },
  { label: 'Lowercase letter', test: (v) => /[a-z]/.test(v) },
  { label: 'Number', test: (v) => /[0-9]/.test(v) },
  { label: 'Special character', test: (v) => /[^A-Za-z0-9]/.test(v) },
];

function SetPasswordInner() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const token = searchParams.get('token');
  const [isLoading, setIsLoading] = useState(false);
  const [passwordValue, setPasswordValue] = useState('');

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<SetPasswordFormData>({
    resolver: zodResolver(passwordSchema),
  });

  async function onSubmit(data: SetPasswordFormData) {
    if (!token) {
      toast.error('Invalid or missing reset token. Please request a new password reset link.');
      return;
    }

    setIsLoading(true);
    try {
      const response = await fetch('/api/auth/set-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token, password: data.password }),
      });

      if (!response.ok) {
        const body = await response.json().catch(() => ({}));
        toast.error(body.message ?? 'Failed to set password. Please try again.');
        return;
      }

      toast.success('Password set successfully. You can now sign in.');
      router.push('/login');
    } catch {
      toast.error('Something went wrong. Please try again.');
    } finally {
      setIsLoading(false);
    }
  }

  return (
    <div
      className="min-h-screen flex items-center justify-center px-4"
      style={{ backgroundColor: '#1e2844' }}
    >
      <Card className="w-full max-w-md">
        <CardHeader className="space-y-1 text-center pb-6">
          <h1 className="text-2xl font-bold tracking-tight text-foreground">Port Nimara</h1>
          <p className="text-sm text-muted-foreground">Set your password</p>
        </CardHeader>
        <CardContent>
          {!token ? (
            <p className="text-center text-sm text-destructive">
              Invalid or missing token. Please request a new password reset link.
            </p>
          ) : (
            <form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate>
              <div className="space-y-2">
                <Label htmlFor="password">New Password</Label>
                <Input
                  id="password"
                  type="password"
                  autoComplete="new-password"
                  disabled={isLoading}
                  className={cn(
                    errors.password && 'border-destructive focus-visible:ring-destructive',
                  )}
                  {...register('password', {
                    onChange: (e) => setPasswordValue(e.target.value),
                  })}
                />
                {errors.password && (
                  <p className="text-sm text-destructive">{errors.password.message}</p>
                )}

                <ul className="space-y-1 pt-1">
                  {requirements.map((req) => {
                    const met = req.test(passwordValue);
                    return (
                      <li
                        key={req.label}
                        className={cn(
                          'flex items-center gap-2 text-xs',
                          met ? 'text-green-600 dark:text-green-400' : 'text-muted-foreground',
                        )}
                      >
                        {met ? (
                          <CheckCircle2 className="h-3.5 w-3.5 shrink-0" />
                        ) : (
                          <Circle className="h-3.5 w-3.5 shrink-0" />
                        )}
                        {req.label}
                      </li>
                    );
                  })}
                </ul>
              </div>

              <div className="space-y-2">
                <Label htmlFor="confirmPassword">Confirm Password</Label>
                <Input
                  id="confirmPassword"
                  type="password"
                  autoComplete="new-password"
                  disabled={isLoading}
                  className={cn(
                    errors.confirmPassword && 'border-destructive focus-visible:ring-destructive',
                  )}
                  {...register('confirmPassword')}
                />
                {errors.confirmPassword && (
                  <p className="text-sm text-destructive">{errors.confirmPassword.message}</p>
                )}
              </div>

              <Button type="submit" className="w-full" disabled={isLoading}>
                {isLoading ? 'Setting password…' : 'Set password'}
              </Button>
            </form>
          )}
        </CardContent>
      </Card>
    </div>
  );
}

export default function SetPasswordPage() {
  return (
    <Suspense
      fallback={
        <div
          className="min-h-screen flex items-center justify-center px-4"
          style={{ backgroundColor: '#1e2844' }}
        />
      }
    >
      <SetPasswordInner />
    </Suspense>
  );
}
