'use client';

import React, { useState } from 'react';
import { useModal } from '@/hooks/useModal';
import { Modal } from '../common/modal';
import { ConfirmLogoutModal } from '../common/modal/ConfirmLogoutModal';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { changePassword, logoutUser } from '@/store/slices/authSlice';
import { toast } from 'react-toastify';
import { Eye, EyeOff, Bell, BellOff } from 'lucide-react';
import { useRouter } from 'next/navigation';

const UserSettingCard = () => {
    const { isOpen, openModal, closeModal } = useModal();
    const [isLogoutModalOpen, setIsLogoutModalOpen] = useState(false);
    const dispatch = useAppDispatch();
    const router = useRouter();
    const user = useAppSelector((state: any) => state.auth.user);
    const [isNotificationEnabled, setIsNotificationEnabled] = useState(user?.isNotificationEnabled ?? true);
    const [isToggling, setIsToggling] = useState(false);
    
    const [oldPassword, setOldPassword] = useState('');
    const [newPassword, setNewPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [isLoading, setIsLoading] = useState(false);

    const [showOldPassword, setShowOldPassword] = useState(false);
    const [showNewPassword, setShowNewPassword] = useState(false);
    const [showConfirmPassword, setShowConfirmPassword] = useState(false);
    const [errors, setErrors] = useState<{oldPassword?: string, newPassword?: string, confirmPassword?: string}>({});

    const handleSave = async (e: React.FormEvent) => {
        e.preventDefault();
        
        const newErrors: {oldPassword?: string, newPassword?: string, confirmPassword?: string} = {};
        
        if (!oldPassword) newErrors.oldPassword = "Old Password is required";
        if (!newPassword) newErrors.newPassword = "New Password is required";
        else if (newPassword.length < 6) newErrors.newPassword = "Password must be at least 6 characters";
        
        if (!confirmPassword) newErrors.confirmPassword = "Confirm Password is required";
        else if (newPassword !== confirmPassword) newErrors.confirmPassword = "Passwords do not match";

        if (Object.keys(newErrors).length > 0) {
            setErrors(newErrors);
            return;
        }

        setErrors({});
        setIsLoading(true);
        try {
            const resultAction = await dispatch(changePassword({ oldPassword, newPassword }));
            if (changePassword.fulfilled.match(resultAction)) {
                toast.success(resultAction.payload.message || 'Password updated successfully');
                setOldPassword('');
                setNewPassword('');
                setConfirmPassword('');
                setErrors({});
                closeModal();
            } else {
                toast.error(resultAction.payload as string || 'Failed to update password');
            }
        } catch (error) {
            toast.error('An unexpected error occurred');
        } finally {
            setIsLoading(false);
        }
    };

    const handleToggleNotification = async () => {
        setIsToggling(true);
        try {
            const token = localStorage.getItem("token") || sessionStorage.getItem("token");
            const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000'}/api/users/me/notification-toggle`, {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({ isEnabled: !isNotificationEnabled })
            });

            if (response.ok) {
                setIsNotificationEnabled(!isNotificationEnabled);
                toast.success(`Notifications ${!isNotificationEnabled ? 'enabled' : 'disabled'} successfully`);
            } else {
                toast.error('Failed to update notification preferences');
            }
        } catch (error) {
            toast.error('An error occurred while updating notifications');
        } finally {
            setIsToggling(false);
        }
    };

    const isProjectManagerOrTeamLeader = user?.roles?.some((r: any) => r.slug === 'project-manager' || r.slug === 'team-leader') || false;

    return (
        <>
            <h4 className="mb-4 lg:mb-6 text-lg font-medium text-brand-950 ">Settings</h4>
            <div>
                {isProjectManagerOrTeamLeader && (
                    <div className="flex flex-col justify-between gap-4 border-b border-gray-200 py-4 first:pt-0 last:border-b-0 last:pb-0 sm:flex-row sm:items-center">
                        <div>
                            <span className="block font-medium mb-1 text-base text-gray-800">Notifications</span>
                            <p className="text-sm text-gray-500">Enable or disable system notifications.</p>
                        </div>
                        <div>
                            <button 
                                onClick={handleToggleNotification}
                                disabled={isToggling}
                                className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none ${
                                    isNotificationEnabled ? 'bg-brand-500' : 'bg-gray-200'
                                }`}
                            >
                                <span
                                    className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                                        isNotificationEnabled ? 'translate-x-6' : 'translate-x-1'
                                    }`}
                                />
                            </button>
                        </div>
                    </div>
                )}

                <div className="flex flex-col justify-between gap-4 border-b border-gray-200 py-4 first:pt-0 last:border-b-0 last:pb-0 sm:flex-row sm:items-end">
                    <div>
                        <span className="block font-medium mb-1 text-base text-gray-800">Change Password</span>
                        <p className="text-sm text-gray-500">Receive real-time notifications and team alerts.</p>
                    </div>
                    <div>
                        <button 
                            onClick={openModal}
                            className="flex w-full items-center justify-center gap-2 rounded-lg border border-gray-300 bg-[#f7f8fa] px-4 py-2.5 text-sm font-medium text-gray-700 lg:inline-flex lg:w-auto"
                        >
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none">
                                <path d="M12.3861 5.08087L14.9182 7.61296M15.6437 3.5917L16.408 4.35603C16.8962 4.84419 16.8962 5.63564 16.408 6.1238L7.83547 14.6963C7.69039 14.8414 7.51182 14.9486 7.31554 15.0083L3.97461 16.0251L4.99141 12.6842C5.05115 12.4879 5.15829 12.3093 5.30337 12.1642L13.8759 3.5917C14.3641 3.10355 15.1555 3.10355 15.6437 3.5917Z" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"></path>
                            </svg>
                            Change Password
                        </button>
                    </div>
                </div>

                <div className="flex flex-col justify-between gap-4 border-b border-gray-200 py-4 first:pt-0 last:border-b-0 last:pb-0 sm:flex-row sm:items-end">
                    <div>
                        <span className="block text-base font-medium mb-1 text-gray-800">Logout</span>
                        <p className="text-sm text-gray-500">Sign out from every active session.</p>
                    </div>
                    <div>
                        <button 
                            onClick={() => setIsLogoutModalOpen(true)}
                            className="flex w-full items-center justify-center gap-2 rounded-lg border border-gray-300 bg-[#f7f8fa] px-4 py-2.5 text-sm font-medium text-gray-700 lg:inline-flex lg:w-auto"
                        >
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none">
                                <path d="M3.33325 10.0003L9.79159 10.0003M6.66599 6.66699L3.33488 10.0002L6.66599 13.3337M8.12492 4.16374V3.54199C8.12492 2.85164 8.68456 2.29199 9.37492 2.29199H14.3749C15.0653 2.29199 15.6249 2.85164 15.6249 3.54199V16.4587C15.6249 17.149 15.0653 17.7087 14.3749 17.7087H9.37492C8.68456 17.7087 8.12492 17.149 8.12492 16.4587V15.8337" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"></path>
                            </svg>
                            Logout
                        </button>
                    </div>
                </div>
            </div>

            <Modal isOpen={isOpen} onClose={closeModal} className="max-w-[700px] m-4">
                <div className="no-scrollbar relative w-full max-w-[700px] rounded-3xl bg-white p-4 lg:p-8">
                    <div className="px-2 pr-14">
                        <h4 className="mb-2 text-xl lg:text-2xl font-semibold text-brand-950">
                            Update Password
                        </h4>
                        <p className="mb-6 text-sm text-gray-500 lg:mb-7">
                            Update your password to keep your profile up-to-date.
                        </p>
                    </div>
                    <form className="flex flex-col space-y-5 px-2" onSubmit={handleSave}>
                        <div className="col-span-2 lg:col-span-1">
                            <label className="mb-1.5 block text-sm font-medium text-gray-700">Old Password</label>
                            <div className="relative">
                                <input 
                                    type={showOldPassword ? "text" : "password"} 
                                    value={oldPassword}
                                    onChange={(e) => {
                                        setOldPassword(e.target.value);
                                        if (errors.oldPassword) setErrors({...errors, oldPassword: undefined});
                                    }}
                                    className={`h-11 w-full rounded-lg border appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none pr-10 ${errors.oldPassword ? 'border-error-500' : 'border-gray-300'}`} 
                                />
                                <button
                                    type="button"
                                    className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
                                    onClick={() => setShowOldPassword(!showOldPassword)}
                                >
                                    {showOldPassword ? <Eye size={18} /> : <EyeOff size={18} />}
                                </button>
                            </div>
                            {errors.oldPassword && <p className="mt-1 text-xs text-error-500">{errors.oldPassword}</p>}
                        </div>
                        <div className="col-span-2 lg:col-span-1">
                            <label className="mb-1.5 block text-sm font-medium text-gray-700">New Password</label>
                            <div className="relative">
                                <input 
                                    type={showNewPassword ? "text" : "password"} 
                                    value={newPassword}
                                    onChange={(e) => {
                                        setNewPassword(e.target.value);
                                        if (errors.newPassword) setErrors({...errors, newPassword: undefined});
                                    }}
                                    className={`h-11 w-full rounded-lg border appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none pr-10 ${errors.newPassword ? 'border-error-500' : 'border-gray-300'}`} 
                                />
                                <button
                                    type="button"
                                    className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
                                    onClick={() => setShowNewPassword(!showNewPassword)}
                                >
                                    {showNewPassword ? <Eye size={18} /> : <EyeOff size={18} />}
                                </button>
                            </div>
                            {errors.newPassword && <p className="mt-1 text-xs text-error-500">{errors.newPassword}</p>}
                        </div>
                        <div className="col-span-2 lg:col-span-1">
                            <label className="mb-1.5 block text-sm font-medium text-gray-700">Confirm Password</label>
                            <div className="relative">
                                <input 
                                    type={showConfirmPassword ? "text" : "password"} 
                                    value={confirmPassword}
                                    onChange={(e) => {
                                        setConfirmPassword(e.target.value);
                                        if (errors.confirmPassword) setErrors({...errors, confirmPassword: undefined});
                                    }}
                                    className={`h-11 w-full rounded-lg border appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none pr-10 ${errors.confirmPassword ? 'border-error-500' : 'border-gray-300'}`} 
                                />
                                <button
                                    type="button"
                                    className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
                                    onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                                >
                                    {showConfirmPassword ? <Eye size={18} /> : <EyeOff size={18} />}
                                </button>
                            </div>
                            {errors.confirmPassword && <p className="mt-1 text-xs text-error-500">{errors.confirmPassword}</p>}
                        </div>
                        <div className="flex items-center gap-3 px-2 lg:justify-end">
                            <button type="button" className="flex items-center justify-center gap-2 rounded-lg border border-gray-300 bg-[#f7f8fa] px-4 py-3 text-sm font-medium text-gray-700" onClick={closeModal}>
                                Close
                            </button>
                            <button type="submit" disabled={isLoading} className="inline-flex items-center justify-center font-medium gap-2 rounded-lg transition px-4 py-3 text-sm bg-brand-950 text-white shadow-theme-xs hover:text-brand-950 hover:bg-yellow-500 disabled:bg-yellow-500 disabled:opacity-50">
                                {isLoading ? 'Updating...' : 'Update Password'}
                            </button>
                        </div>
                    </form>
                </div>
            </Modal>
            
            <ConfirmLogoutModal 
                isOpen={isLogoutModalOpen} 
                onClose={() => setIsLogoutModalOpen(false)} 
                onConfirm={async () => {
                  try {
                    const resultAction = await dispatch(logoutUser());
                    if (logoutUser.fulfilled.match(resultAction)) {
                      toast.success("Logout successful");
                      router.push("/login");
                    } else {
                      toast.error((resultAction.payload as string) || "Logout failed");
                    }
                  } catch (err) {
                    toast.error("An error occurred during logout");
                  }
                }} 
            />
        </>
    )
};

export default UserSettingCard;
