import React, { useState } from 'react';
import Loginpic from '../../assets/image/loginpic.jpg';
import { FiLock } from 'react-icons/fi';
import { FaRegUser } from "react-icons/fa6";
import LogoDM from "../../assets/icons/LogoDM.svg";
import { useNavigate, Navigate } from 'react-router-dom';
import authService from '../../services/auth';
import { useDispatch } from 'react-redux';
import { setToken } from '../../redux/slices/authSlice';
import { setProfile } from '../../redux/slices/profileSlice';


const Login = () => {
    const [userName, setUserName] = useState('');
    const [password, setPassword] = useState('');
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');
    const navigate = useNavigate();
    const dispatch = useDispatch();


    const handleLogin = async (e) => {
        e.preventDefault();
        setError('');
        setLoading(true);

        const loginData = {
            userName: userName,
            password: password
        };

        try {
            const res = await authService.login(loginData);
            if (res.data.success && res.data.data && res.data.data.tokens.accessToken) {
                dispatch(setToken(res.data.data.tokens.accessToken));
                navigate('/dashboard');
                dispatch(setProfile(res.data.data.admin));
                console.log('login:', res.data.data.admin);
            }

            console.log('Response:', res);
        } catch (error) {
            setLoading(false);
            console.error('❌ Login error:', error);
            // if (error.response) {
            //     setError(error.response.data.message || error.response.data.en_message || 'نام کاربری یا رمز عبور اشتباه است');
            // } else if (error.request) {
            //     setError('خطا در برقراری ارتباط با سرور');
            // } else {
            //     console.error('Error setting up request');
            //     setError('خطای نامشخص رخ داده است');
            // }
        } finally {
            setLoading(false);
        }

    };

    return (
        <div className="relative h-screen" dir="rtl">
            <div className="absolute top-0 left-0 right-0 bg-white z-10 shadow-sm">
                <div className="flex items-center justify-between px-8 py-4">
                    <div className="flex items-center gap-4">
                        <div className="flex justify-center">
                            <img src={LogoDM} className="h-12 w-12" alt="Logo" />
                        </div>
                        <div className="relative">
                            <select className="appearance-none px-6 py-2 pr-4 pl-10 bg-white border-2 border-gray-300 rounded-xl text-sm focus:outline-none focus:border-[#7f4629] transition-colors cursor-pointer">
                                <option>شهر</option>
                                <option>تهران</option>
                                <option>اصفهان</option>
                                <option>شیراز</option>
                                <option>مشهد</option>
                            </select>
                            <svg
                                className="absolute left-4 top-5 -translate-y-1/2 w-6 h-10 text-gray-500 pointer-events-none"
                                fill="none"
                                stroke="currentColor"
                                viewBox="0 0 24 24"
                            >
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                            </svg>
                        </div>
                    </div>

                    <div className="flex items-center font-bold gap-16 text-[#402E32]">
                        <a href="#" className="hover:text-[#7f4629] transition-colors">
                            خانه
                        </a>
                        <a href="#" className="hover:text-[#7f4629] transition-colors">
                            دسته بندی
                        </a>
                        <a href="#" className="hover:text-[#7f4629] transition-colors">
                            تماس با ما
                        </a>
                        <a href="#" className="hover:text-[#7f4629] transition-colors">
                            درباره ما
                        </a>
                    </div>

                    <div className="flex items-center gap-4">
                        <button className="px-12 py-2 bg-[#7f4629] text-white rounded-full font-medium hover:bg-[#5f494f] transition-colors">
                            ثبت نام
                        </button>
                    </div>
                </div>
            </div>

            <div className="flex h-full pt-20">
                <div className="w-1/2 flex items-start justify-start bg-[#f5f0e8] px-24 pt-16">
                    <div className="w-full max-w-lg">
                        <div className="flex items-center gap-2 text-sm text-gray-500 mb-8">
                            <span>ورود</span>
                            <span className="font-bold text-2xl">&gt;</span>
                            <span>خانه</span>
                        </div>

                        <div className="mb-8">
                            <h2 className="text-2xl font-bold text-[#402E32] mb-2">
                                ورود ادمین
                            </h2>
                            <p className="text-gray-700 text-sm">
                                دسترسی ویژه برای مدیریت و گزارش‌ها
                            </p>
                        </div>

                        <form onSubmit={handleLogin} className="space-y-6">
                            {error && (
                                <div className="bg-red-50 border-2 border-red-300 text-red-700 px-4 py-3 rounded-xl text-sm">
                                    {error}
                                </div>
                            )}

                            <div className="relative">
                                <label className="absolute -top-2.5 right-4 bg-[#f5f0e8] px-2 text-sm text-gray-600 z-10">
                                    نام کاربری
                                </label>
                                <div className="relative">
                                    <input
                                        type="text"
                                        value={userName}
                                        onChange={(e) => setUserName(e.target.value)}
                                        placeholder="userName"
                                        className="w-full pl-14 pr-6 py-3 border-2 border-gray-300 rounded-xl focus:outline-none focus:border-[#7f4629] transition-colors"
                                        dir="ltr"
                                    />
                                    <FaRegUser className="absolute  left-5 top-1/2 -translate-y-1/2 text-gray-400 w-6 h-5" />
                                </div>
                            </div>

                            <div className="relative">
                                <label className="absolute -top-2.5 right-4 bg-[#f5f0e8] px-2 text-sm text-gray-600 z-10">
                                    رمز عبور
                                </label>
                                <div className="relative">
                                    <input
                                        type="password"
                                        value={password}
                                        onChange={(e) => setPassword(e.target.value)}
                                        placeholder="password"
                                        className="w-full pl-14 pr-6 py-3 border-2 border-gray-300 rounded-xl focus:outline-none focus:border-[#7f4629] transition-colors"
                                        dir="ltr"
                                    />
                                    <FiLock className="absolute left-5 top-1/2 -translate-y-1/2 text-gray-400 w-6 h-10" />
                                </div>
                            </div>

                            <div className="text-right">
                                <a
                                    href="#"
                                    className="text-sm text-gray-500 hover:text-[#7f4629] transition-colors"
                                >
                                    فراموشی رمز عبور
                                </a>
                            </div>

                            <button
                                type="submit"
                                disabled={loading || !userName || !password}
                                className="w-full bg-[#7f4629] text-white py-3 rounded-full font-bold hover:bg-[#5f494f] transition-all duration-300 shadow-lg hover:shadow-xl disabled:bg-gray-400 disabled:cursor-not-allowed"
                            >
                                {loading ? 'در حال ورود...' : 'ورود'}
                            </button>
                        </form>
                    </div>
                </div>

                <div className="w-1/2 relative overflow-hidden">
                    <img
                        src={Loginpic}
                        alt="Coffee workspace"
                        className="w-full h-full object-cover"
                    />
                </div>
            </div>
        </div>
    );
};



export default Login;