import { useEffect, useState ,useRef} from 'react';
import { useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { setPageTitle } from '../../store/themeConfigSlice';
import { setCredentials } from '../../store/authSlice';
import { setSettings } from '../../store/settingsSlice';
import { setPermissions } from '../../store/permissionsSlice';
import IconEye from '../../components/Icon/IconEye';
import IconEyeOff from '../../components/Icon/IconEyeOff';
import Button from '../../components/Buttons';
import Select from '../../components/Select';
import api from "../../api/axios";
import { toast } from 'react-toastify';

const Login = () => {
    const dispatch = useDispatch();
    const navigate = useNavigate();
    const [branches, setBranches] = useState<any[]>([]);
    const [branchId, setBranchId] = useState<number | null>(null);
    const [userName, setUserName] = useState('');
    const [password, setPassword] = useState('');
    const [showPassword, setShowPassword] = useState(false);
    const calledRef = useRef(false);
    const [errors, setErrors] = useState<any>({});
    const [loading, setLoading] = useState(false);
    useEffect(() => {
        dispatch(setPageTitle('Login'));
    }, [dispatch]);

    const submitForm = async (e: React.FormEvent) => {
        e.preventDefault();

        let newErrors: any = {};

        if (!branchId) newErrors.branch = "Branch is required";
        if (!userName) newErrors.userName = "Username is required";
        if (!password) newErrors.password = "Password is required";

        setErrors(newErrors);

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

        setLoading(true);
        try {
            const res = await login(branchId!, userName, password);

            const { user, token, permissions, settings } = res.data;

            if (user && token) {
                dispatch(setCredentials({ user, token }));
                dispatch(setSettings(settings));
                dispatch(setPermissions(permissions));

                localStorage.setItem('token', token);
                localStorage.setItem('user', JSON.stringify(user));
                localStorage.setItem('settings', JSON.stringify(settings));
                localStorage.setItem('permissions', JSON.stringify(permissions));

                toast.success('Login successful');
                navigate('/dashboard');
            } else {
                toast.error('Login failed: Invalid response structure');
            }

        } catch (err: any) {
            const response = err?.response?.data;

            let shown = false;

            if (response?.errors) {
                Object.values(response.errors).forEach((fieldErrors: any) => {
                    fieldErrors.forEach((msg: string) => {
                        toast.error(msg);
                        shown = true;
                    });
                });
            }

            if (!shown && response?.message) {
                toast.error(response.message);
                shown = true;
            }

            if (!shown) {
                toast.error("Login failed. Please try again.");
            }
        } finally {
            setLoading(false);
        }
    };

    const login = async (branch_id: number, user_name: string, password: string) => {
        const res = await api.post("/web_login", {
            branch_id,
            user_name,
            password,
        });

        return res.data;
    };

    // branchOptions

    useEffect(() => {
        const loadBranches = async () => {
            const res = await api.get("/branch_list");

            const options = res.data.data.map((b: any) => ({
                value: b.id,
                label: b.name,
            }));

            setBranches(options);
        };

       if (calledRef.current) return;

        calledRef.current = true;
        loadBranches();
    }, []);


    return (
        <div className="relative w-screen h-screen">
            {/*  FULL BACKGROUND IMAGE */}
            <div
                className="absolute inset-0 bg-cover bg-center bg-no-repeat"
                style={{
                    backgroundImage: "url('/assets/images/auth/login_bg_2.jpg')",
                }}
            />
            <div className="relative z-10 flex h-full items-center justify-start px-6 lg:px-20 lg:ms-28 ms-0 md:ms-10 pb-24">
                <div className="w-full max-w-[380px] p-6 bg-black/20 backdrop-blur-md rounded-md shadow-lg">
                    {/* LOGO */}
                    <div className="mb-8 text-center">
                        <img src="/assets/images/auth/logo.png" alt="logo" className="mx-auto h-36 w-36 mb-2" />
                    </div>

                    {/* FORM */}
                    <form className="space-y-5" onSubmit={submitForm}>
                        <div>
                            <label className="block mb-1 font-medium text-black">Choose Branch</label>
                            <Select
                                options={branches}
                                placeholder="Select Branch"
                                onChange={(val: any) => {
                                    setBranchId(val?.value);

                                    setErrors((prev: any) => ({
                                        ...prev,
                                        branch: ""
                                    }));
                                }}
                            />
                            {errors.branch && (
                                <p className="text-red-500 text-sm mt-1">{errors.branch}</p>
                            )}
                        </div>
                        <div>
                            <label className="block mb-1 font-medium text-black">Username</label>
                            <input
                                type="text"
                                placeholder="Username"
                                value={userName}
                                onChange={(e) => {
                                    setUserName(e.target.value);

                                    // clear only username error
                                    setErrors((prev: any) => ({
                                        ...prev,
                                        userName: ""
                                    }));
                                }}
                                className="form-input rounded-lg bg-white border"
                            />
                            {errors.userName && (
                                <p className="text-red-500 text-sm mt-1">{errors.userName}</p>
                            )}
                        </div>
                        <div className='relative'>
                            <label className="block mb-1 font-medium text-black">Password</label>

                            <input
                                type={showPassword ? 'text' : 'password'}
                                placeholder="Password"
                                value={password}
                                onChange={(e) => {
                                    setPassword(e.target.value);

                                    setErrors((prev: any) => ({
                                        ...prev,
                                        password: ""
                                    }));
                                }}
                                className="form-input pe-10 rounded-lg bg-white border"
                            />

                            <button
                                type="button"
                                onClick={() => setShowPassword(!showPassword)}
                                className="absolute right-3 bottom-0 -translate-y-1/2 text-gray-500"
                            >
                                {showPassword ? <IconEyeOff /> : <IconEye />}
                            </button>

                            {errors.password && (
                                <p className="text-red-500 text-sm mt-1">{errors.password}</p>
                            )}
                        </div>
                        <Button
                            type="submit"
                            variant="primary"
                            fullWidth
                            disabled={loading}
                        >
                            {loading ? "Signing in..." : "SIGN IN"}
                        </Button>
                    </form>
                </div>
            </div>
        </div>
    );
};

export default Login;
