'use client';

import React, { useState, Suspense } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
import { Eye, EyeOff, Lock } from 'lucide-react';
import { getApiErrorMessage } from '@/lib/apiError';
import { useAppDispatch } from '@/state/hooks';
import { openModal } from '@/state/auth/authSlice';
import { resetPassword } from '@/state/auth/authService';
import routes from '@/app/routes';

// Same rules as the API's `password` validator and the signup form
const resetSchema = Yup.object().shape({
  password: Yup.string()
    .min(8, 'Password must be at least 8 characters')
    .matches(/^(?=.*[A-Za-z])(?=.*\d)/, 'Password must contain at least one letter and one number')
    .required('New password is required'),
  confirmPassword: Yup.string()
    .oneOf([Yup.ref('password')], 'Passwords must match')
    .required('Confirm password is required'),
});

const inputClass = (hasError: boolean) =>
  `w-full pl-9 pr-9 py-2.5 rounded-md border text-[13px] focus:outline-none focus:ring-2 transition-all ${
    hasError ? 'border-red-400 focus:ring-red-100' : 'border-gray-200 focus:ring-blue-100 focus:border-[#2954E8]'
  }`;

const PasswordField = ({ name, placeholder, hasError }: { name: string; placeholder: string; hasError: boolean }) => {
  const [visible, setVisible] = useState(false);
  return (
    <div className="relative">
      <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
      <Field
        name={name}
        type={visible ? 'text' : 'password'}
        placeholder={placeholder}
        autoComplete="new-password"
        className={inputClass(hasError)}
      />
      <button
        type="button"
        onClick={() => setVisible((v) => !v)}
        className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
        aria-label={visible ? 'Hide password' : 'Show password'}
      >
        {visible ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
      </button>
    </div>
  );
};

const ResetPasswordContent = () => {
  const searchParams = useSearchParams();
  const token = searchParams.get('token');
  const dispatch = useAppDispatch();
  const router = useRouter();

  const [status, setStatus] = useState<'form' | 'success'>('form');
  const [error, setError] = useState<string | null>(
    token ? null : 'This password reset link is incomplete. Please request a new one.',
  );

  const openAuthModal = (view: 'login' | 'forgot') => {
    dispatch(openModal(view));
    router.push(routes.home);
  };

  return (
    <div className="min-h-[70vh] flex items-center justify-center py-16 px-4 sm:px-6 lg:px-8">
      <div className="max-w-md w-full bg-white rounded-xl shadow-lg border border-gray-100 p-8">
        {status === 'success' ? (
          <div className="py-6 text-center">
            <div className="w-16 h-16 mx-auto mb-4 bg-green-100 text-green-600 rounded-full flex items-center justify-center">
              <svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7" />
              </svg>
            </div>
            <h2 className="text-2xl font-bold text-gray-900 mb-2">Password Reset!</h2>
            <p className="text-sm text-gray-600 mb-6">
              Your password has been changed. You can now log in with your new password.
            </p>
            <button
              onClick={() => openAuthModal('login')}
              className="w-full bg-[#2954E8] text-white font-semibold py-3 px-4 rounded-lg hover:bg-[#1f42c2] transition-colors shadow-sm"
            >
              Log In to Seller Account
            </button>
          </div>
        ) : (
          <>
            <h2 className="text-2xl font-bold text-gray-900 mb-2 text-center">Choose a New Password</h2>
            <p className="text-sm text-gray-500 mb-6 text-center">
              Enter a new password for your BroadcastAV seller account.
            </p>

            {error && (
              <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-md text-red-700 text-xs">
                {error}
                <button
                  type="button"
                  onClick={() => openAuthModal('forgot')}
                  className="block mt-2 font-semibold text-[#2954E8] hover:underline"
                >
                  Request a new reset link
                </button>
              </div>
            )}

            {token && (
              <Formik
                initialValues={{ password: '', confirmPassword: '' }}
                validationSchema={resetSchema}
                onSubmit={async (values) => {
                  setError(null);
                  try {
                    await resetPassword({ token, ...values });
                    setStatus('success');
                  } catch (err) {
                    setError(getApiErrorMessage(err, 'Failed to reset your password. Please try again.'));
                  }
                }}
              >
                {({ errors, touched, isSubmitting }) => (
                  <Form className="space-y-4">
                    <div className="space-y-1.5">
                      <label className="text-[12px] font-semibold text-[#0B0F19]">New Password</label>
                      <PasswordField
                        name="password"
                        placeholder="At least 8 characters, a letter and a number"
                        hasError={!!(errors.password && touched.password)}
                      />
                      <ErrorMessage name="password" component="div" className="text-red-500 text-[11px] font-medium" />
                    </div>

                    <div className="space-y-1.5">
                      <label className="text-[12px] font-semibold text-[#0B0F19]">Confirm New Password</label>
                      <PasswordField
                        name="confirmPassword"
                        placeholder="Re-enter your new password"
                        hasError={!!(errors.confirmPassword && touched.confirmPassword)}
                      />
                      <ErrorMessage
                        name="confirmPassword"
                        component="div"
                        className="text-red-500 text-[11px] font-medium"
                      />
                    </div>

                    <button
                      type="submit"
                      disabled={isSubmitting}
                      className="w-full bg-[#2954E8] text-white font-semibold text-[14px] py-2.5 rounded-md disabled:bg-gray-400 hover:bg-[#1f42c2] transition-colors"
                    >
                      {isSubmitting ? 'Saving...' : 'Reset Password'}
                    </button>
                  </Form>
                )}
              </Formik>
            )}

            <div className="mt-6 text-center">
              <Link href={routes.home} className="text-xs text-blue-600 hover:underline">
                Return to Home
              </Link>
            </div>
          </>
        )}
      </div>
    </div>
  );
};

export default function ResetPasswordPage() {
  return (
    <Suspense
      fallback={
        <div className="min-h-[70vh] flex items-center justify-center">
          <div className="w-12 h-12 border-4 border-blue-600 border-t-transparent rounded-full animate-spin" />
        </div>
      }
    >
      <ResetPasswordContent />
    </Suspense>
  );
}
