import { useState, useEffect } from 'react';
import Header from '../components/Header';
import { useStore } from '../hooks/useStore';
import { requestChangePassword } from '../config/UserRequest';
import { requestGetMyLogs } from '../config/logResponse';
import { toast } from 'react-toastify';
import { User, Mail, Calendar, CreditCard, Lock, Clock, MapPin, Search } from 'lucide-react';
import Footer from '../components/Footer';

import { Helmet } from 'react-helmet';
import { useNavigate } from 'react-router-dom';

function InfoUser() {
    const { dataUser, dataWebsite } = useStore();
    const [loading, setLoading] = useState(false);
    const [logs, setLogs] = useState([]);

    useEffect(() => {
        const fetchLogs = async () => {
            try {
                const res = await requestGetMyLogs();
                setLogs(res.metadata || []);
            } catch (error) {
                console.error('Failed to fetch logs', error);
            }
        };
        fetchLogs();
    }, []);

    // Change Password State
    const [passwordData, setPasswordData] = useState({
        currentPassword: '',
        newPassword: '',
        confirmPassword: '',
    });

    const navigate = useNavigate();

    useEffect(() => {
        if (!dataUser._id) {
            navigate('/login');
        }
    }, []);

    const handleChangePass = (e) => {
        setPasswordData({
            ...passwordData,
            [e.target.name]: e.target.value,
        });
    };

    const handleSubmitPassword = async (e) => {
        e.preventDefault();

        if (!passwordData.currentPassword || !passwordData.newPassword || !passwordData.confirmPassword) {
            toast.error('Vui lòng nhập đầy đủ thông tin!');
            return;
        }

        if (passwordData.newPassword !== passwordData.confirmPassword) {
            toast.error('Mật khẩu mới không khớp!');
            return;
        }

        if (passwordData.newPassword.length < 6) {
            toast.error('Mật khẩu mới phải có ít nhất 6 ký tự!');
            return;
        }

        setLoading(true);
        try {
            await requestChangePassword({
                currentPassword: passwordData.currentPassword,
                newPassword: passwordData.newPassword,
            });
            toast.success('Đổi mật khẩu thành công!');
            setPasswordData({
                currentPassword: '',
                newPassword: '',
                confirmPassword: '',
            });
        } catch (error) {
            toast.error(error.response?.data?.message || 'Đổi mật khẩu thất bại!');
        } finally {
            setLoading(false);
        }
    };

    // Format Date
    const formatDate = (dateString) => {
        if (!dateString) return 'Chưa cập nhật';
        return new Date(dateString).toLocaleString('vi-VN');
    };

    // Format Currency
    const formatCurrency = (amount) => {
        return (amount || 0).toLocaleString('vi-VN') + ' đ';
    };

    return (
        <div className="min-h-screen bg-gray-50">
            <Helmet>
                <title>Thông tin tài khoản | {dataWebsite?.nameWebsite || 'Website'}</title>
            </Helmet>
            <header className="pb-16">
                <Header />
            </header>

            <main className="container mx-auto px-4 py-8">
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
                    {/* Account Info Section */}
                    <div className="bg-white rounded-lg shadow p-6">
                        <h2 className="text-xl font-bold mb-6 text-gray-800 border-b pb-2">Thông Tin Tài Khoản</h2>
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div className="space-y-1">
                                <label className="text-sm font-semibold text-gray-600">Tên Đăng Nhập</label>
                                <div className="bg-gray-50 border border-gray-200 rounded px-3 py-2 text-gray-800 font-medium">
                                    {dataUser.fullName || dataUser.username}
                                </div>
                            </div>
                            <div className="space-y-1">
                                <label className="text-sm font-semibold text-gray-600">Địa Chỉ E-Mail</label>
                                <div className="bg-gray-50 border border-gray-200 rounded px-3 py-2 text-gray-800 font-medium">
                                    {dataUser.email}
                                </div>
                            </div>
                            <div className="space-y-1">
                                <label className="text-sm font-semibold text-gray-600">Ngày Đăng Ký</label>
                                <div className="bg-gray-50 border border-gray-200 rounded px-3 py-2 text-gray-800 font-medium">
                                    {formatDate(dataUser.createdAt)}
                                </div>
                            </div>
                            <div className="space-y-1">
                                <label className="text-sm font-semibold text-gray-600">Ngày Cập Nhật</label>
                                <div className="bg-gray-50 border border-gray-200 rounded px-3 py-2 text-gray-800 font-medium">
                                    {formatDate(dataUser.updatedAt)}
                                </div>
                            </div>
                            <div className="space-y-1">
                                <label className="text-sm font-semibold text-gray-600">Số Tiền Hiện Có</label>
                                <div className="bg-gray-50 border border-gray-200 rounded px-3 py-2 text-gray-800 font-medium">
                                    {formatCurrency(dataUser.balance)}
                                </div>
                            </div>
                            <div className="space-y-1">
                                <label className="text-sm font-semibold text-gray-600">Tổng Tiền Đã Nạp</label>
                                <div className="bg-gray-50 border border-gray-200 rounded px-3 py-2 text-gray-800 font-medium">
                                    {formatCurrency(dataUser.balanceHistory)}
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Change Password Section */}
                    <div className="bg-white rounded-lg shadow p-6">
                        <h2 className="text-xl font-bold mb-6 text-gray-800 border-b pb-2">Thay Đổi Mật Khẩu</h2>
                        <form onSubmit={handleSubmitPassword} className="space-y-4">
                            <div className="space-y-1">
                                <label className="text-sm font-semibold text-gray-600">Mật Khẩu Cũ</label>
                                <input
                                    type="password"
                                    name="currentPassword"
                                    value={passwordData.currentPassword}
                                    onChange={handleChangePass}
                                    placeholder="Nhập mật khẩu cũ"
                                    className="w-full border border-gray-300 rounded px-3 py-2 focus:outline-none focus:border-orange-500"
                                />
                            </div>
                            <div className="space-y-1">
                                <label className="text-sm font-semibold text-gray-600">Mật Khẩu Mới</label>
                                <input
                                    type="password"
                                    name="newPassword"
                                    value={passwordData.newPassword}
                                    onChange={handleChangePass}
                                    placeholder="Nhập mật khẩu mới"
                                    className="w-full border border-gray-300 rounded px-3 py-2 focus:outline-none focus:border-orange-500"
                                />
                            </div>
                            <div className="space-y-1">
                                <label className="text-sm font-semibold text-gray-600">Xác Nhận Mật Khẩu</label>
                                <input
                                    type="password"
                                    name="confirmPassword"
                                    value={passwordData.confirmPassword}
                                    onChange={handleChangePass}
                                    placeholder="Nhập lại mật khẩu mới"
                                    className="w-full border border-gray-300 rounded px-3 py-2 focus:outline-none focus:border-orange-500"
                                />
                            </div>
                            <button
                                type="submit"
                                disabled={loading}
                                className="w-full bg-orange-500 hover:bg-orange-600 text-white font-bold py-2 rounded transition-colors mt-4"
                            >
                                {loading ? 'Đang xử lý...' : 'Đổi Mật Khẩu'}
                            </button>
                        </form>
                    </div>
                </div>

                {/* Activity Log Section */}
                <div className="bg-white rounded-lg shadow p-6">
                    <div className="flex justify-between items-center mb-6 border-b pb-2">
                        <h2 className="text-xl font-bold text-gray-800">Nhật Ký Hoạt Động</h2>
                        {/* Search Input for Activity Log */}
                        <div className="flex items-center space-x-2">
                            <input
                                type="text"
                                placeholder="Search..."
                                className="border border-gray-300 rounded px-3 py-1 text-sm focus:outline-none focus:border-orange-500"
                            />
                            <button className="bg-orange-500 text-white p-1.5 rounded hover:bg-orange-600">
                                <Search size={16} />
                            </button>
                        </div>
                    </div>

                    <div className="overflow-x-auto">
                        <table className="w-full text-sm text-left">
                            <thead className="bg-gray-50 text-gray-700 font-semibold border-b">
                                <tr>
                                    <th className="px-4 py-3">Hoạt Động</th>
                                    <th className="px-4 py-3">Nội Dung</th>
                                    <th className="px-4 py-3">Địa Chỉ IP</th>
                                    <th className="px-4 py-3 whitespace-nowrap">Thời Gian</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-100">
                                {logs.length > 0 ? (
                                    logs.map((log) => (
                                        <tr key={log._id} className="hover:bg-gray-50">
                                            <td className="px-4 py-3 font-medium text-orange-600">
                                                {log.action === 'LOGIN'
                                                    ? 'Đăng Nhập'
                                                    : log.action === 'REGISTER'
                                                      ? 'Đăng Ký'
                                                      : log.action}
                                            </td>
                                            <td className="px-4 py-3">{log.content}</td>
                                            <td className="px-4 py-3">{log.ipAddress}</td>
                                            <td className="px-4 py-3 whitespace-nowrap">{formatDate(log.createdAt)}</td>
                                        </tr>
                                    ))
                                ) : (
                                    <tr>
                                        <td colSpan="4" className="text-center py-4 text-gray-500 italic">
                                            Chưa có hoạt động nào được ghi lại.
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>
            </main>
            <footer>
                <Footer />
            </footer>
        </div>
    );
}

export default InfoUser;
