import { useState } from "react";
import toast from "react-hot-toast";
import {
    ArrowRight,
    BarChart3,
    Boxes,
    CheckCircle2,
    DoorOpen,
    Loader2,
    Sparkles,
    Table2,
    TrendingUp,
} from "lucide-react";
import { getEquipmentDemandReport, getRoomUtilizationReport } from "../api.js";

export default function ReportsPage() {
    const [roomReport, setRoomReport] = useState([]);
    const [equipmentReport, setEquipmentReport] = useState([]);
    const [activeReport, setActiveReport] = useState(null);
    const [loadingRoomReport, setLoadingRoomReport] = useState(false);
    const [loadingEquipmentReport, setLoadingEquipmentReport] = useState(false);

    async function loadRoomReport() {
        setLoadingRoomReport(true);

        try {
            const data = await getRoomUtilizationReport();
            setRoomReport(Array.isArray(data) ? data : []);
            setActiveReport("rooms");
            toast.success("Room utilization report loaded");
        } catch (err) {
            toast.error(err.message || "Room utilization report could not be loaded.");
        } finally {
            setLoadingRoomReport(false);
        }
    }

    async function loadEquipmentReport() {
        setLoadingEquipmentReport(true);

        try {
            const data = await getEquipmentDemandReport();
            setEquipmentReport(Array.isArray(data) ? data : []);
            setActiveReport("equipment");
            toast.success("Equipment demand report loaded");
        } catch (err) {
            toast.error(err.message || "Equipment demand report could not be loaded.");
        } finally {
            setLoadingEquipmentReport(false);
        }
    }

    return (
        <section className="reports-page-pro">
            <div className="reports-hero-pro">
                <div>
                    <div className="dashboard-eyebrow">
                        <BarChart3 size={16} />
                        Analytics center
                    </div>

                    <h1>Reports & Insights</h1>

                    <p>
                        Review room utilization, equipment demand and operational trends
                        using live data from the project database.
                    </p>
                </div>

                <div className="reports-hero-metrics">
                    <div>
                        <strong>2</strong>
                        <span>Advanced reports</span>
                    </div>

                    <div>
                        <strong>Live</strong>
                        <span>PostgreSQL data</span>
                    </div>

                    <div>
                        <strong>SQL</strong>
                        <span>Grouped analytics</span>
                    </div>
                </div>
            </div>

            <div className="reports-command-grid">
                <ReportCard
                    icon={DoorOpen}
                    tag="Quarterly analysis"
                    title="Room utilization"
                    description="Analyze how rooms are used across quarters, including reservation volume, approval status, approved hours and utilization ranking."
                    points={[
                        "Grouped by quarter, building and room",
                        "Approved, rejected, cancelled and pending counts",
                        "Room ranking by utilization level",
                    ]}
                    loading={loadingRoomReport}
                    onClick={loadRoomReport}
                />

                <ReportCard
                    icon={Boxes}
                    tag="Stock risk analysis"
                    title="Equipment demand"
                    description="Track requested equipment quantities and compare demand with registered stock and assigned room equipment."
                    points={[
                        "Demand by equipment type and quarter",
                        "Registered stock versus requested quantity",
                        "Demand ranking and stock risk level",
                    ]}
                    loading={loadingEquipmentReport}
                    onClick={loadEquipmentReport}
                />
            </div>

            {!activeReport && (
                <div className="reports-empty-panel">
                    <div className="reports-empty-icon">
                        <Table2 size={28} />
                    </div>

                    <div>
                        <h2>Select a report to view results</h2>
                        <p>
                            Choose one of the analytical reports above. Results will be loaded
                            from the live database and displayed in a structured table.
                        </p>
                    </div>
                </div>
            )}

            {activeReport === "rooms" && roomReport.length > 0 && (
                <PremiumTable
                    title="Room utilization report"
                    subtitle="Quarterly utilization grouped by building, room, reservation status and approved hours."
                    columns={[
                        "Quarter",
                        "Building",
                        "Room",
                        "Type",
                        "Total",
                        "Approved",
                        "Hours",
                        "Rank",
                        "Level",
                    ]}
                    rows={roomReport.map((row) => [
                        row.quarterStart,
                        row.buildingName,
                        row.roomCode,
                        row.type,
                        row.totalRoomReservations,
                        row.approvedReservations,
                        row.approvedHours,
                        row.utilizationRank,
                        row.utilizationLevel,
                    ])}
                />
            )}

            {activeReport === "equipment" && equipmentReport.length > 0 && (
                <PremiumTable
                    title="Equipment demand report"
                    subtitle="Demand, registered quantity, assigned equipment, stock risk and ranking by equipment type."
                    columns={[
                        "Quarter",
                        "Equipment",
                        "Stock",
                        "Assigned",
                        "Registered",
                        "Requested",
                        "Demand %",
                        "Rank",
                        "Level",
                    ]}
                    rows={equipmentReport.map((row) => [
                        row.quarterStart,
                        row.equipmentName,
                        row.stockQuantity,
                        row.assignedRoomQuantity,
                        row.totalRegisteredQuantity,
                        row.totalRequestedQuantity,
                        row.demandToRegisteredPercent,
                        row.demandRank,
                        row.demandLevel,
                    ])}
                />
            )}

            {activeReport === "rooms" && !loadingRoomReport && roomReport.length === 0 && (
                <EmptyResult title="No room utilization rows were returned." />
            )}

            {activeReport === "equipment" &&
                !loadingEquipmentReport &&
                equipmentReport.length === 0 && (
                    <EmptyResult title="No equipment demand rows were returned." />
                )}
        </section>
    );
}

function ReportCard({
                        icon: Icon,
                        tag,
                        title,
                        description,
                        points,
                        loading,
                        onClick,
                    }) {
    return (
        <button
            className="report-command-card"
            type="button"
            onClick={onClick}
            disabled={loading}
        >
            <div className="report-command-top">
                <div className="report-command-icon">
                    <Icon size={25} />
                </div>

                <span>{tag}</span>
            </div>

            <h2>{title}</h2>

            <p>{description}</p>

            <div className="report-point-list">
                {points.map((point) => (
                    <div key={point}>
                        <CheckCircle2 size={17} />
                        {point}
                    </div>
                ))}
            </div>

            <div className="report-command-footer">
        <span>
          {loading ? (
              <>
                  Loading report
                  <Loader2 size={17} className="spin-icon" />
              </>
          ) : (
              <>
                  Open report
                  <ArrowRight size={17} />
              </>
          )}
        </span>

                <TrendingUp size={20} />
            </div>
        </button>
    );
}

function PremiumTable({ title, subtitle, columns, rows }) {
    return (
        <div className="panel table-panel report-output-panel">
            <div className="panel-header report-table-header">
                <div>
                    <div className="dashboard-eyebrow">
                        <Sparkles size={15} />
                        Report output
                    </div>

                    <h3>{title}</h3>
                    <p>{subtitle}</p>
                </div>

                <div className="report-row-count">
                    <strong>{rows.length}</strong>
                    <span>rows loaded</span>
                </div>
            </div>

            <div className="table-wrapper">
                <table>
                    <thead>
                    <tr>
                        {columns.map((column) => (
                            <th key={column}>{column}</th>
                        ))}
                    </tr>
                    </thead>

                    <tbody>
                    {rows.map((row, index) => (
                        <tr key={index}>
                            {row.map((cell, cellIndex) => (
                                <td key={cellIndex}>{String(cell ?? "")}</td>
                            ))}
                        </tr>
                    ))}
                    </tbody>
                </table>
            </div>
        </div>
    );
}

function EmptyResult({ title }) {
    return (
        <div className="reports-empty-panel">
            <div className="reports-empty-icon">
                <Table2 size={28} />
            </div>

            <div>
                <h2>{title}</h2>
                <p>
                    The query executed successfully, but there is no matching data for the
                    current dataset.
                </p>
            </div>
        </div>
    );
}