'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;
            }

            const formData = new FormData();
            formData.append('currentPassword', currentPassword);
            formData.append('newPassword', newPassword);

            const res = await axios.post<ChangePasswordResponse>(
                `https://ebay.backend.data4autos.com/api/auth/change-password`,
                formData,
                {
                    headers: {
                        Authorization: `Bearer ${token}`,
                    },
                }
            );

            setSuccess(res.data.message || 'Password updated successfully!');
            localStorage.removeItem('token');
            router.push('/login');
        } catch (err: any) {
            const msg = err.response?.data?.error || err.message;
            setError(msg);
        } finally {
            setLoading(false);
        }
    };

    return (
        <form onSubmit={submitForm} className="dark:text-white">

            {/* Alerts */}
            {error && (
                <div className="mb-4 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
                    {error}
                </div>
            )}
            {success && (
                <div className="mb-4 rounded-md border border-green-200 bg-green-50 px-3 py-2 text-sm text-green-700">
                    {success}
                </div>
            )}

            <div className="space-y-4">

                {/* Current Password */}
                <div className="relative">
                    <label
                        htmlFor="currentPassword"
                        className="block mb-1 text-sm text-gray-300"
                    >
                        Current Password
                    </label>

                    <input
                        id="currentPassword"
                        type="password"
                        placeholder="Current Password"
                        value={currentPassword}
                        onChange={(e) => setCurrentPassword(e.target.value)}
                        required
                        className="w-full ps-10 py-3
                          bg-[rgba(7,13,30,0.7)]
                          border border-white/15 rounded-lg
                          text-white placeholder:text-gray-400
                          focus:outline-none focus:border-white/30"
                    />

                    <span className="absolute start-4 top-[42px] -translate-y-1/2 text-white">
                        <IconLockDots fill />
                    </span>
                </div>

                {/* New Password */}
                <div className="relative">
                    <label
                        htmlFor="newPassword"
                        className="block mb-1 text-sm text-gray-300"
                    >
                        New Password
                    </label>

                    <input
                        id="newPassword"
                        type="password"
                        placeholder="New Password"
                        value={newPassword}
                        onChange={(e) => setNewPassword(e.target.value)}
                        required
                        className="w-full ps-10 py-3
                          bg-[rgba(7,13,30,0.7)]
                          border border-white/15 rounded-lg
                          text-white placeholder:text-gray-400
                          focus:outline-none focus:border-white/30"
                    />

                    <span className="absolute start-4 top-[42px] -translate-y-1/2 text-white">
                        <IconLockDots fill />
                    </span>
                </div>

                {/* Submit */}
                <button
                    type="submit"
                    disabled={loading}
                    className="w-full py-3 rounded-xl text-lg font-semibold text-white
                      bg-gradient-to-r from-blue-600 to-pink-500
                      shadow-lg transition-all hover:opacity-90 hover:scale-[1.02]
                      disabled:opacity-60"
                >
                    {loading ? 'UPDATING…' : 'CHANGE PASSWORD'}
                </button>

            </div>
        </form>
    );
};

export default ComponentsAuthChangePasswordForm;
