"use client";
import React, { useState, useEffect } from "react";
import { useTheme } from "../../context/ThemeContext"; // Import the theme context

const Visits = () => {
    const { darkMode } = useTheme(); // Get dark mode state
    const [data, setData] = useState(null);
    const [deviceData, setDeviceData] = useState(null);
    const [browserData, setBrowserData] = useState(null);
    const [osData, setOsData] = useState(null);
    const [lastMonthData, setLastMonthData] = useState(null);
    const [lastTwoMonthsData, setLastTwoMonthsData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    // Fetch data from the API
    const fetchData = async (endpoint, setDataFunction) => {
        try {
            const response = await fetch(`/api/proxy?domain=meerafirms.in&endpoint=${endpoint}`);
            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.error || `HTTP Error: ${response.status}`);
            }
            const result = await response.json();
            setDataFunction(result);
        } catch (err) {
            console.error(`Error fetching ${endpoint}:`, err);
            setError(err.message);
        }
    };

    useEffect(() => {
        const fetchAllData = async () => {
            setLoading(true);
            await Promise.all([
                fetchData("visits/total-visits", setData),
                fetchData("visits/total-visits?fields=device", setDeviceData),
                fetchData("visits/total-visits?fields=device,browser,os", setBrowserData),
                fetchData("visits/last-month", setLastMonthData),
                fetchData("visits/last-2-months", setLastTwoMonthsData),
            ]);
            setLoading(false);
        };

        fetchAllData();
    }, []);

    // Card component for consistent styling
    const DataCard = ({ title, children }) => (
        <div className={`m-2 p-6 rounded-2xl border transition-colors duration-300 
            ${darkMode ? 'bg-gray-800 border-gray-700' : 'bg-white border-gray-200'}`}>
            <h2 className={`text-lg font-bold mb-4 ${darkMode ? 'text-white' : 'text-gray-800'}`}>
                {title}
            </h2>
            {children}
        </div>
    );

    // Data row component
    const DataRow = ({ label, value }) => (
        <div className="flex justify-between py-2 border-b border-gray-200 dark:border-gray-700 last:border-0">
            <span className={`font-medium ${darkMode ? 'text-gray-300' : 'text-gray-600'}`}>
                {label}
            </span>
            <span className={`font-semibold ${darkMode ? 'text-white' : 'text-gray-800'}`}>
                {value}
            </span>
        </div>
    );

    return (
        <div className={`min-h-screen p-4 transition-colors duration-300 ${darkMode ? 'bg-gray-900' : 'bg-gray-50'}`}>
            <h1 className={`text-2xl font-bold mb-6 ${darkMode ? 'text-white' : 'text-gray-800'}`}>
                Website Analytics
            </h1>

            {loading && (
                <div className="flex justify-center items-center h-64">
                    <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500"></div>
                </div>
            )}

            {error && (
                <DataCard title="Error">
                    <p className="text-red-500">{error}</p>
                </DataCard>
            )}

            {data && (
                <DataCard title="Website Visits">
                    <div className="space-y-3">
                        <DataRow label="Total Visits" value={data["Total Visits"]} />
                        <DataRow label="Total Views" value={data["Total Views"]} />
                    </div>
                </DataCard>
            )}

            {deviceData && (
                <DataCard title="Device Distribution">
                    <div className="space-y-3">
                        {Object.entries(deviceData.Devices || {}).map(([key, value]) => (
                            <DataRow key={key} label={key} value={value} />
                        ))}
                    </div>
                </DataCard>
            )}

            {browserData && (
                <>
                    <DataCard title="Browser Distribution">
                        <div className="space-y-3">
                            {Object.entries(browserData.Browsers || {}).map(([key, value]) => (
                                <DataRow key={key} label={key} value={value} />
                            ))}
                        </div>
                    </DataCard>

                    <DataCard title="Operating System Distribution">
                        <div className="space-y-3">
                            {Object.entries(browserData.OS || {}).map(([key, value]) => (
                                <DataRow key={key} label={key} value={value} />
                            ))}
                        </div>
                    </DataCard>
                </>
            )}

            {lastMonthData && (
                <DataCard title="Last Month Visits">
                    <div className="space-y-3">
                        {Object.entries(lastMonthData || {}).map(([key, value]) => (
                            <DataRow key={key} label={key} value={value} />
                        ))}
                    </div>
                </DataCard>
            )}

            {lastTwoMonthsData && (
                <DataCard title="Last 2 Months Visits">
                    <div className="space-y-3">
                        {Object.entries(lastTwoMonthsData || {}).map(([key, value]) => (
                            <DataRow key={key} label={key} value={value} />
                        ))}
                    </div>
                </DataCard>
            )}
        </div>
    );
};

export default Visits;