import React, { useState, useEffect } from "react";
import LineChart from "../Charts/LineChart";
import { useProjects } from "../../hooks/useProjects";
import { useDashboard_ActivityData } from "../../hooks/useDashboard_Data";
import ApexChart from "../Charts/Circlechart";

const LOCAL_STORAGE_PROJECT_KEY = "selectedActivityProjectId";

const Activity = () => {
    const { projects } = useProjects();
    const today = new Date().toISOString().split("T")[0]; // Format: YYYY-MM-DD
    const [selectedDate, setSelectedDate] = useState(today);
    const storedProjectId = localStorage.getItem(LOCAL_STORAGE_PROJECT_KEY);
    const initialProjectId = storedProjectId || "all";
    const [selectedProjectId, setSelectedProjectId] = useState(initialProjectId);
    const [displayedProjectName, setDisplayedProjectName] = useState("Select Project");
    const [activeTab, setActiveTab] = useState("all");

    const { dashboard_Activitydata: ActivityData, isLoading, error: isError } =
        useDashboard_ActivityData(selectedDate, selectedProjectId);

    useEffect(() => {
        if (selectedProjectId === "all") {
            setDisplayedProjectName("All Projects");
        } else if (projects) {
            const foundProject = projects.find((p) => p.id === selectedProjectId);
            setDisplayedProjectName(foundProject ? foundProject.name : "Select Project");
        } else {
            setDisplayedProjectName("Select Project");
        }

        localStorage.setItem(LOCAL_STORAGE_PROJECT_KEY, selectedProjectId);
    }, [selectedProjectId, projects]);

    const handleProjectSelect = (projectId) => {
        setSelectedProjectId(projectId);
    };

    const handleDateChange = (e) => {
        setSelectedDate(e.target.value);
    };

    return (
        <div className="card h-100">
            <div className="card-header">
                <div className="d-flex flex-wrap justify-content-between align-items-center mb-0">
                    <div className="card-title mb-0 text-start">
                        <h5 className="mb-1">Activity</h5>
                        <p className="card-subtitle">Activity Progress Chart</p>
                    </div>

                    <div className="btn-group">
                        <button
                            className="btn btn-outline-primary btn-sm dropdown-toggle"
                            type="button"
                            data-bs-toggle="dropdown"
                            aria-expanded="false"
                        >
                            {displayedProjectName}
                        </button>
                        <ul className="dropdown-menu">
                            <li>
                                <button className="dropdown-item" onClick={() => handleProjectSelect("all")}>
                                    All Projects
                                </button>
                            </li>
                            {projects?.map((project) => (
                                <li key={project.id}>
                                    <button
                                        className="dropdown-item"
                                        onClick={() => handleProjectSelect(project.id)}
                                    >
                                        {project.name}
                                    </button>
                                </li>
                            ))}
                        </ul>
                    </div>
                </div>
            </div>

            {/* ✅ Date Picker Aligned Left with Padding */}
            <div className="d-flex justify-content-start ps-3 mb-3">
                <div style={{ width: "150px" }}>
                    <input
                        type="date"
                        className="form-control"
                        value={selectedDate}
                        onChange={handleDateChange}
                    />
                </div>
            </div>

            {/* Tabs */}
            <ul className="nav nav-tabs " role="tablist">
                <li className="nav-item">
                    <button
                        type="button"
                        className={`nav-link ${activeTab === "all" ? "active" : ""}`}
                        onClick={() => setActiveTab("all")}
                        data-bs-toggle="tab"
                    >
                        Summary
                    </button>
                </li>
                <li className="nav-item">
                    <button
                        type="button"
                        className={`nav-link ${activeTab === "logs" ? "active" : ""}`}
                        onClick={() => setActiveTab("logs")}
                        data-bs-toggle="tab"
                    >
                        Details
                    </button>
                </li>
            </ul>

            <div className="card-body">
                {activeTab === "all" && (
                    <div className="row justify-content-between">
                        <div className="col-md-6 d-flex flex-column align-items-center text-center mb-4">
                            {isLoading ? (
                                <p>Loading activity data...</p>
                            ) : isError ? (
                                <p>No data available.</p>
                            ) : (
                                ActivityData && (
                                    <>
                                        <h5 className="fw-bold mb-0 text-start w-80">
                                            <i className="bx bx-task text-info"></i> Allocated Task
                                        </h5>
                                        <h4 className="mb-0 fw-bold">
                                            {ActivityData.totalCompletedWork?.toLocaleString()}/
                                            {ActivityData.totalPlannedWork?.toLocaleString()}
                                        </h4>
                                        <small className="text-muted">Completed / Assigned</small>
                                        <div style={{ maxWidth: "180px" }}>
                                            <ApexChart />
                                        </div>
                                    </>
                                )
                            )}
                        </div>

                        <div className="col-md-6 d-flex flex-column align-items-center text-center mb-4">
                            {!isLoading && !isError && ActivityData && (
                                <>
                                    <h5 className="fw-bold mb-0 text-start w-110">
                                        <i className="bx bx-task text-info"></i> Activities
                                    </h5>
                                    <h4 className="mb-0 fw-bold">
                                        {ActivityData.totalCompletedWork?.toLocaleString()}/
                                        {ActivityData.totalPlannedWork?.toLocaleString()}
                                    </h4>
                                    <small className="text-muted ">Pending / Assigned</small>
                                    <div style={{ maxWidth: "180px" }}>
                                        <ApexChart />
                                    </div>
                                </>
                            )}
                        </div>
                    </div>
                )}

                {activeTab === "logs" && (
                    <div className="table-responsive">
                        <table className="table table-bordered table-hover">
                            <thead>
                                <tr>
                                    <th>Activity / Location</th>
                                    <th>Assigned / Completed</th>
                                </tr>
                            </thead>
                            <tbody>
                                {[{
                                    activity: "Code Review / Remote",
                                    assignedToday: 3,
                                    completed: 2
                                }].map((log, index) => (
                                    <tr key={index}>
                                        <td>{log.activity}</td>
                                        <td>{log.assignedToday} / {log.completed}</td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>
        </div>
    );
};

export default Activity;
