'use client';

import IconLockDots from '@/components/icon/icon-lock-dots';
import { useRouter } from 'next/navigation';
import React, { useState } from 'react';
import axios from 'axios';

interface ChangePasswordResponse {
    message?: string;
    error?: string;
}

const ComponentsAuthChangePasswordForm = () => {
    const router = useRouter();

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

    const submitForm = async (e: React.FormEvent) => {
        e.preventDefault();
        setError('');
        setSuccess('');
        setLoading(true);

        try {
            const token = localStorage.getItem('token');
            if (!token) {
                setError('You are not logged in.');
                setLoading(false);
                return;
            }

            // ✅ Create FormData and append fields
            const formData = new FormData();
            formData.append('currentPassword', currentPassword);
            formData.append('newPassword', newPassword);

            // ✅ Axios call with generic type
            const res = await axios.post<ChangePasswordResponse>(
                `https://ebay.backend.data4autos.com/api/auth/change-password`,
                formData,
                {
                    headers: {
                        Authorization: `Bearer ${token}`,
                        // If you're sending FormData, remove JSON content-type
                        // Axios will automatically set multipart/form-data
                    },
                }
            );

            setSuccess(res.data.message || 'Password updated successfully!');

            // Optional: force re-login after password change
            localStorage.removeItem('token');
            router.push('/login');
        } catch (err: any) {
            const msg = err.response?.data?.error || err.message;
            setError(msg);
        } finally {
            setLoading(false);
        }
    };

    return (
        <form className="space-y-5" onSubmit={submitForm}>
            {/* Current password */}
            <div>
                <label htmlFor="currentPassword" className="dark:text-white">
                    Current Password
                </label>
                <div className="relative text-white-dark">
                    <input
                        id="currentPassword"
                        type="password"
                        placeholder="Enter Current Password"
                        className="form-input ps-10 placeholder:text-white-dark"
                        value={currentPassword}
                        onChange={(e) => setCurrentPassword(e.target.value)}
                        required
                    />
                    <span className="absolute start-4 top-1/2 -translate-y-1/2">
                        <IconLockDots fill={true} />
                    </span>
                </div>
            </div>

            {/* New password */}
            <div>
                <label htmlFor="newPassword" className="dark:text-white">
                    New Password
                </label>
                <div className="relative text-white-dark">
                    <input
                        id="newPassword"
                        type="password"
                        placeholder="Enter New Password"
                        className="form-input ps-10 placeholder:text-white-dark"
                        value={newPassword}
                        onChange={(e) => setNewPassword(e.target.value)}
                        required
                    />
                    <span className="absolute start-4 top-1/2 -translate-y-1/2">
                        <IconLockDots fill={true} />
                    </span>
                </div>
            </div>

            {error && <p className="text-red-500 text-sm">{error}</p>}
            {success && <p className="text-green-500 text-sm">{success}</p>}

            <button
                type="submit"
                disabled={loading}
                className="btn w-full border-0 uppercase shadow-[0_10px_20px_-10px_rgba(67,97,238,0.44)] disabled:cursor-not-allowed disabled:opacity-70 !mt-6 bg-[linear-gradient(135deg,#1E3A8A_0%,#2563EB_50%,#00C6FF_100%)] text-white hover:bg-[linear-gradient(135deg,#00C6FF_0%,#2563EB_50%,#1E3A8A_100%)]"
            >
                {loading ? 'UPDATING…' : 'CHANGE PASSWORD'}
            </button>
        </form>
    );
};

export default ComponentsAuthChangePasswordForm;
