'use client';

import { useState } from 'react';
import Image from 'next/image';
import { TwoFactorSettings } from './TwoFactorSettings';
import api from '@/services/api';

interface PasswordSecurityFormProps {
  onSave?: (data: { currentPassword: string; newPassword: string }) => void;
}

export function PasswordSecurityForm({ onSave }: PasswordSecurityFormProps) {
  const [formData, setFormData] = useState({
    currentPassword: '',
    newPassword: '',
    confirmPassword: '',
  });

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

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  const handleChange = (field: string, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    // Clear messages when user starts typing
    if (error) setError('');
    if (success) setSuccess('');
  };

  const toggleShowPassword = (field: 'current' | 'new' | 'confirm') => {
    setShowPasswords((prev) => ({ ...prev, [field]: !prev[field] }));
  };

  const validatePassword = (password: string): boolean => {
    // Minimum 8 characters with at least one uppercase, lowercase, and number
    const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
    return regex.test(password);
  };

  const handleSave = async () => {
    setError('');
    setSuccess('');

    // Validate fields
    if (!formData.currentPassword) {
      setError('Current password is required');
      return;
    }

    if (!formData.newPassword) {
      setError('New password is required');
      return;
    }

    if (!validatePassword(formData.newPassword)) {
      setError('Password must be at least 8 characters with uppercase, lowercase, and number');
      return;
    }

    if (formData.newPassword !== formData.confirmPassword) {
      setError('Passwords do not match');
      return;
    }

    setLoading(true);

    try {
      await api.post('/auth/change-password', {
        currentPassword: formData.currentPassword,
        newPassword: formData.newPassword,
      });

      setSuccess('Password changed successfully');
      setFormData({
        currentPassword: '',
        newPassword: '',
        confirmPassword: '',
      });

      // Call onSave callback if provided
      if (onSave) {
        onSave({ currentPassword: formData.currentPassword, newPassword: formData.newPassword });
      }
    } catch (err: unknown) {
      const error = err as { response?: { data?: { message?: string | string[] } } };
      const message = error.response?.data?.message;
      if (Array.isArray(message)) {
        setError(message[0]);
      } else {
        setError(message || 'Failed to change password. Please try again.');
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      {/* Password Form */}
      <div className="border border-[#00293d]/10 rounded-[15px] bg-white p-6">
        <div className="mb-6">
          <h2 className="font-fractul font-bold text-[16px] text-[#00293D] mb-2">
            Change Password
          </h2>
          <p className="font-serif text-[12px] text-[#00293D]/60">
            Ensure your account is using a strong password to stay secure
          </p>
        </div>

        {/* Error Message */}
        {error && (
          <div className="mb-4 p-3 bg-red-50 border border-red-200 text-red-600 rounded-[10px] text-[13px] font-serif">
            {error}
          </div>
        )}

        {/* Success Message */}
        {success && (
          <div className="mb-4 p-3 bg-green-50 border border-green-200 text-green-600 rounded-[10px] text-[13px] font-serif">
            {success}
          </div>
        )}

        {/* Form Fields */}
        <div className="space-y-6 max-w-md">
          {/* Current Password */}
          <div>
            <label className="block text-[12px] font-medium text-[#00293D]/70 font-serif mb-2">
              Current Password
            </label>
            <div className="relative">
              <input
                type={showPasswords.current ? 'text' : 'password'}
                value={formData.currentPassword}
                onChange={(e) => handleChange('currentPassword', e.target.value)}
                placeholder="Enter current password"
                className="w-full h-[40px] px-4 pr-12 border border-[#00293D]/20 rounded-[15px] text-[14px] font-serif text-[#00293D] placeholder:text-[#00293D]/40 focus:outline-none focus:border-[#E58625]"
              />
              <button
                type="button"
                onClick={() => toggleShowPassword('current')}
                className="absolute right-4 top-1/2 -translate-y-1/2 text-[#00293D]/50 hover:text-[#00293D] cursor-pointer"
              >
                <Image
                  src={showPasswords.current ? '/assets/icons/eye-icon.svg' : '/assets/icons/eye-off-icon.svg'}
                  alt={showPasswords.current ? 'Hide password' : 'Show password'}
                  width={20}
                  height={20}
                />
              </button>
            </div>
          </div>

          {/* New Password */}
          <div>
            <label className="block text-[12px] font-medium text-[#00293D]/70 font-serif mb-2">
              New Password
            </label>
            <div className="relative">
              <input
                type={showPasswords.new ? 'text' : 'password'}
                value={formData.newPassword}
                onChange={(e) => handleChange('newPassword', e.target.value)}
                placeholder="Enter new password"
                className="w-full h-[40px] px-4 pr-12 border border-[#00293D]/20 rounded-[15px] text-[14px] font-serif text-[#00293D] placeholder:text-[#00293D]/40 focus:outline-none focus:border-[#E58625]"
              />
              <button
                type="button"
                onClick={() => toggleShowPassword('new')}
                className="absolute right-4 top-1/2 -translate-y-1/2 text-[#00293D]/50 hover:text-[#00293D] cursor-pointer"
              >
                <Image
                  src={showPasswords.new ? '/assets/icons/eye-icon.svg' : '/assets/icons/eye-off-icon.svg'}
                  alt={showPasswords.new ? 'Hide password' : 'Show password'}
                  width={20}
                  height={20}
                />
              </button>
            </div>
            <p className="text-[11px] text-[#00293D]/50 font-serif mt-1">
              Minimum 8 characters with at least one uppercase, lowercase, and number
            </p>
          </div>

          {/* Confirm Password */}
          <div>
            <label className="block text-[12px] font-medium text-[#00293D]/70 font-serif mb-2">
              Confirm New Password
            </label>
            <div className="relative">
              <input
                type={showPasswords.confirm ? 'text' : 'password'}
                value={formData.confirmPassword}
                onChange={(e) => handleChange('confirmPassword', e.target.value)}
                placeholder="Confirm new password"
                className="w-full h-[40px] px-4 pr-12 border border-[#00293D]/20 rounded-[15px] text-[14px] font-serif text-[#00293D] placeholder:text-[#00293D]/40 focus:outline-none focus:border-[#E58625]"
              />
              <button
                type="button"
                onClick={() => toggleShowPassword('confirm')}
                className="absolute right-4 top-1/2 -translate-y-1/2 text-[#00293D]/50 hover:text-[#00293D] cursor-pointer"
              >
                <Image
                  src={showPasswords.confirm ? '/assets/icons/eye-icon.svg' : '/assets/icons/eye-off-icon.svg'}
                  alt={showPasswords.confirm ? 'Hide password' : 'Show password'}
                  width={20}
                  height={20}
                />
              </button>
            </div>
          </div>
        </div>

        {/* Save Button */}
        <div className="mt-8">
          <button
            type="button"
            onClick={handleSave}
            disabled={loading}
            className="px-8 py-3 bg-[#e58625] text-white rounded-[15px] font-fractul font-medium text-[14px] hover:bg-[#d47920] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {loading ? 'Updating...' : 'Update Password'}
          </button>
        </div>
      </div>

      {/* Two-Factor Authentication Section */}
      <div className="mt-4">
        <TwoFactorSettings />
      </div>
    </>
  );
}
