import React, { useState } from 'react';
import * as Yup from 'yup';
import { FaEye, FaEyeSlash } from 'react-icons/fa';
import { FormLabel, FormControl, Button } from 'react-bootstrap';
import { useForm, Controller } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { toChangeAdminPassword } from '@/services/public';
import { toast, ToastContainer } from 'react-toastify';

interface FormValues {
  currentPassword: string;
  newPassword: string;
  confirmPassword: string;
}

const validationSchema = Yup.object({
  currentPassword: Yup.string()
    .required('Please enter your current password'),
  newPassword: Yup.string()
    .required('Please enter a new password')
    .min(8, 'Password must be at least 8 characters long')
    .max(20, 'Password must not exceed 20 characters')
    .matches(/[A-Z]/, 'Password must include at least one uppercase letter')
    .matches(/[0-9]/, 'Password must include at least one number')
    .matches(/[!@#$%^&*(),.?":{}|<>]/, 'Password must include at least one special character'),
  confirmPassword: Yup.string()
    .required('Please enter a confirm password')
    .oneOf([Yup.ref('newPassword')], 'The new password and confirmation password do not match'),
});

const AdminChangesPassword: React.FC = () => {

  const { control, handleSubmit, formState: { errors }, reset } = useForm<FormValues>({
    resolver: yupResolver(validationSchema),
  });

  const [showPassword, setShowPassword] = useState({
    current: false,
    new: false,
    confirm: false,
  });

  const toggleVisibility = (key: keyof typeof showPassword) => {
    setShowPassword((prev) => ({ ...prev, [key]: !prev[key] }));
  };

  const onSubmit = async (data: FormValues) => {
    const makePayload = {
      new_password: data.newPassword,
      current_password: data.currentPassword,
      new_password_confirmation: data.confirmPassword,
    };

    try {
      let updateStatus = await toChangeAdminPassword(makePayload);
      if (updateStatus?.status === 'success') {
        toast.success(updateStatus.message, { position: toast.POSITION.TOP_CENTER });
        reset({
          currentPassword: '',
          newPassword: '',
          confirmPassword: ''
        });
      } else {
        toast.error(updateStatus.message, { position: toast.POSITION.TOP_CENTER });
      }
    } catch (error) {
      toast.error('Error updating password', { position: toast.POSITION.TOP_CENTER });
    }
  };

  const fields: { name: keyof FormValues; label: string; visibilityKey: keyof typeof showPassword }[] = [
    { name: 'currentPassword', label: 'Current Password', visibilityKey: 'current' },
    { name: 'newPassword', label: 'New Password', visibilityKey: 'new' },
    { name: 'confirmPassword', label: 'Confirm Password', visibilityKey: 'confirm' },
  ];

  return (
    <div className="admin-update-password-page">
      <ToastContainer />
      <div className="admin-update-password-container">
        <form onSubmit={handleSubmit(onSubmit)}>
          {fields.map(({ name, label, visibilityKey }) => (
            <div key={name} className="admin-update-password-input-div">
              <FormLabel htmlFor={name}>{label}</FormLabel>
              <div className="admin-update-password-input-field">
                <Controller
                  control={control}
                  name={name}
                  render={({ field }) => (
                    <FormControl
                      {...field}
                      type={showPassword[visibilityKey] ? 'text' : 'password'}
                      id={name}
                      className="admin-update-password-input"
                    />
                  )}
                />
                <span
                  onClick={() => toggleVisibility(visibilityKey)}
                  className="admin-update-password-icon"
                >
                  {showPassword[visibilityKey] ? <FaEye /> : <FaEyeSlash className="admin-update-password-icon-hide" />}
                </span>
              </div>
              {errors[name] && <div className="admin-update-password-page-error">{errors[name]?.message}</div>}
            </div>
          ))}
          <Button type="submit" variant="primary" className="admin-update-password-button">
            Submit
          </Button>
        </form>
      </div>
    </div>
  );
};

export default AdminChangesPassword;
