// MyProfile.tsx
import Modal from "../components/Modals";
import IconMail from "../components/Icon/IconMail";
import IconPhone from "../components/Icon/IconPhone";
import IconUser from "../components/Icon/IconUser";
import IconLock from "../components/Icon/IconLock";
import IconCamera from "../components/Icon/IconCamera";
import { useEffect, useRef, useState } from "react";
import userProfile from '../assets/images/auth/user.png';
import IconEyeOff from "../components/Icon/IconEyeOff";
import IconEye from "../components/Icon/IconEye";
import api from '../api/axios';
import { toast } from 'react-toastify';
import config from '../config';
import { useDispatch, useSelector } from 'react-redux';
import { updateUser } from '../store/authSlice'; // We'll create this action

interface Props {
    open: boolean;
    onClose: () => void;
    onUpdateSuccess?: (updatedUser: any) => void; // Add callback prop
}

const MyProfile = ({ open, onClose, onUpdateSuccess }: Props) => {
    const dispatch = useDispatch();
    const authUser = useSelector((state: any) => state.auth.user);
    const userData = authUser?.staff || authUser;

    const [showPassword, setShowPassword] = useState(false);
    const [showNewPassword, setShowNewPassword] = useState(false);
    const [image, setImage] = useState<string>(userProfile);
    const [imageFile, setImageFile] = useState<File | null>(null);
    const [password, setPassword] = useState('');
    const [newPassword, setNewPassword] = useState('');
    const [saving, setSaving] = useState(false);

    const fileInputRef = useRef<HTMLInputElement | null>(null);

    useEffect(() => {
        if (open && userData) {
            const userImage = userData.staff_pic
                ? `${config.storageUrl}/${userData.staff_pic}`
                : userProfile;
            setImage(userImage);
            // Reset password fields
            setPassword('');
            setNewPassword('');
        }
    }, [open, userData]);

    const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) {
            setImageFile(file);
            const preview = URL.createObjectURL(file);
            setImage(preview);
        }
    };

    // Single update function for both image and password
    const handleSaveChanges = async () => {
        // Check if anything to update
        if (!imageFile && !newPassword) {
            toast.warning('No changes to save');
            return;
        }

        setSaving(true);
        try {
            const formData = new FormData();

            // Append image if changed
            if (imageFile) {
                formData.append('staff_pic', imageFile);
            }

            // Append password data if changed
            if (newPassword) {
                if (!password) {
                    toast.warning('Please enter current password');
                    setSaving(false);
                    return;
                }
                if (newPassword.length < 6) {
                    toast.warning('New password must be at least 6 characters');
                    setSaving(false);
                    return;
                }
                formData.append('current_password', password);
                formData.append('new_password', newPassword);
            }

            const response = await api.post('/staff/user/profile/update', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            });

            if (response.data.status === true) {
                // Get updated user data from response
                const updatedUser = response.data.data;

                // Update Redux store with new user data
                dispatch(updateUser(updatedUser));

                // Also update localStorage
                const storedUser = localStorage.getItem('user');
                if (storedUser) {
                    const userObj = JSON.parse(storedUser);
                    const updatedUserObj = {
                        ...userObj,
                        staff: {
                            ...userObj.staff,
                            ...updatedUser
                        }
                    };
                    localStorage.setItem('user', JSON.stringify(updatedUserObj));
                }

                toast.success('Profile updated successfully');

                // Call the callback if provided
                if (onUpdateSuccess) {
                    onUpdateSuccess(updatedUser);
                }

                onClose();
            } else {
                toast.error(response.data.message || 'Failed to update profile');
            }
        } catch (error: any) {
            console.error('Error updating profile:', error);
            toast.error(error.response?.data?.message || 'Failed to update profile');
        } finally {
            setSaving(false);
        }
    };

    const getDisplayName = () => {
        return userData?.staff_name || authUser?.name || 'Super Admin';
    };

    const getDisplayRole = () => {
        return userData?.role_name || userData?.role || 'Admin';
    };

    const getDisplayEmail = () => {
        return userData?.staff_email || authUser?.email || 'superadmin@tesra.com';
    };

    const getDisplayPhone = () => {
        return userData?.staff_mobile || userData?.mobile || '+91 98745 62100';
    };

    const getDisplayUsername = () => {
        return userData?.username || authUser?.name || 'superadmin';
    };

    return (
        <Modal
            open={open}
            onClose={onClose}
            title="Profile Details"
            maxWidth="max-w-lg"
            footer={
                <>
                    <button
                        onClick={onClose}
                        className="btn btn-outline-danger"
                        type="button"
                        disabled={saving}
                    >
                        Cancel
                    </button>

                    <button
                        className="btn btn-primary"
                        type="button"
                        onClick={handleSaveChanges}
                        disabled={saving}
                    >
                        {saving ? 'Saving...' : 'Save Changes'}
                    </button>
                </>
            }
        >
            <div className="space-y-5">
                <div className="flex flex-col items-center text-center">
                    <div className="relative">
                        <img
                            src={image}
                            alt="profile"
                            className="w-20 h-20 rounded-full border-2 border-rose-100 shadow object-cover"
                        />
                        <input
                            type="file"
                            accept="image/*"
                            ref={fileInputRef}
                            onChange={handleImageChange}
                            className="hidden"
                        />

                        <button
                            type="button"
                            onClick={() => fileInputRef.current?.click()}
                            className="absolute bottom-0 right-0 bg-gray-800 text-white p-1 rounded-full border"
                        >
                            <IconCamera className="w-5 h-5 text-white" />
                        </button>
                    </div>

                    <h2 className="mt-3 font-semibold text-lg">{getDisplayName()}</h2>
                    <span className="text-xs bg-rose-200 px-3 py-1 rounded-full text-rose-600">
                        {getDisplayRole()}
                    </span>
                </div>
                <div className="grid grid-cols-2 gap-3">
                    <div className="border rounded-lg p-3">
                        <div className="flex items-center gap-2 text-gray-500 text-xs">
                            <IconUser /> Staff Name
                        </div>
                        <div className="text-sm font-medium mt-1">{getDisplayName()}</div>
                    </div>
                    <div className="border rounded-lg p-3">
                        <div className="flex items-center gap-2 text-gray-500 text-xs">
                            <IconMail /> Username
                        </div>
                        <div className="text-sm font-medium mt-1">{getDisplayUsername()}</div>
                    </div>
                    <div className="border rounded-lg p-3">
                        <div className="flex items-center gap-2 text-gray-500 text-xs">
                            <IconPhone /> Mobile Number
                        </div>
                        <div className="text-sm font-medium mt-1">{getDisplayPhone()}</div>
                    </div>
                    <div className="border rounded-lg p-3">
                        <div className="flex items-center gap-2 text-gray-500 text-xs">
                            <IconUser /> Email
                        </div>
                        <div className="text-sm font-medium mt-1">{getDisplayEmail()}</div>
                    </div>
                </div>
                <div className="border rounded-xl p-4">
                    <div className="flex items-center justify-between mb-3">
                        <div className="flex items-center gap-2 font-medium">
                            <IconLock /> Security
                        </div>
                    </div>
                    <div className='relative mb-3'>
                        <label className="block mb-1 font-medium text-black">Current Password</label>
                        <input
                            type={showPassword ? 'text' : 'password'}
                            placeholder="Enter current password"
                            value={userData?.password}
                            onChange={(e) => setPassword(e.target.value)}
                            className="form-input pe-10 rounded-lg bg-white border border-gray-300 focus:border-red-400"
                        />
                        <button
                            type="button"
                            onClick={() => setShowPassword(!showPassword)}
                            className="absolute right-3 bottom-0 -translate-y-1/2 text-gray-500"
                        >
                            {showPassword ? <IconEyeOff /> : <IconEye />}
                        </button>
                    </div>
                    <div className='relative'>
                        <label className="block mb-1 font-medium text-black">New Password</label>
                        <input
                            type={showNewPassword ? 'text' : 'password'}
                            placeholder="Enter new password"
                            value={newPassword}
                            onChange={(e) => setNewPassword(e.target.value)}
                            className="form-input pe-10 rounded-lg bg-white border border-gray-300 focus:border-red-400"
                        />
                        <button
                            type="button"
                            onClick={() => setShowNewPassword(!showNewPassword)}
                            className="absolute right-3 bottom-0 -translate-y-1/2 text-gray-500"
                        >
                            {showNewPassword ? <IconEyeOff /> : <IconEye />}
                        </button>
                    </div>
                </div>
            </div>
        </Modal>
    );
};

export default MyProfile;
