"use client";

import { useEffect, useState } from "react";
import { Bar } from "react-chartjs-2";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Tooltip,
  Legend,
} from "chart.js";

ChartJS.register(CategoryScale, LinearScale, BarElement, Tooltip, Legend);

type StatsResponse = {
  full_bins_total: number;
  dumped_bins_total: number;
  remaining_bins: number;
  bins_dumped_today: number;
  boxes_today: number;
  labels_boxes: string[];
  data_boxes: number[];
  labels_dump: string[];
  data_dump: number[];
  inv_labels: string[];
  inv_data: number[];
};

export default function Page() {
  const [stats, setStats] = useState<StatsResponse | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetch("http://localhost:8080/smproduce/api/dashboard_stats.php", {
      credentials: "include",
    })
      .then(async (res) => {
        if (!res.ok) {
          throw new Error(`HTTP ${res.status}`);
        }
        return res.json();
      })
      .then((data) => setStats(data))
      .catch((err) => {
        console.error(err);
        setError("Unable to load stats API. Check PHP app & CORS.");
      });
  }, []);

  if (error) {
    return (
      <main style={{ padding: "2rem" }}>
        <h1>SM Produce - Next.js Dashboard</h1>
        <p style={{ color: "#b00020" }}>{error}</p>
      </main>
    );
  }

  if (!stats) {
    return (
      <main style={{ padding: "2rem" }}>
        <h1>SM Produce - Next.js Dashboard</h1>
        <p>Loading data...</p>
      </main>
    );
  }

  const boxesData = {
    labels: stats.labels_boxes,
    datasets: [
      {
        label: "Boxes",
        data: stats.data_boxes,
      },
    ],
  };

  const dumpData = {
    labels: stats.labels_dump,
    datasets: [
      {
        label: "Bins dumped",
        data: stats.data_dump,
      },
    ],
  };

  const invData = {
    labels: stats.inv_labels,
    datasets: [
      {
        label: "Bins",
        data: stats.inv_data,
      },
    ],
  };

  return (
    <main style={{ padding: "2rem" }}>
      <h1 style={{ marginBottom: "1rem" }}>SM Produce - Next.js Dashboard</h1>

      <section style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: "1rem", marginBottom: "2rem" }}>
        <div style={{ padding: "1rem", borderRadius: "1rem", background: "#fff", boxShadow: "0 2px 8px rgba(0,0,0,0.05)" }}>
          <div style={{ fontSize: "0.75rem", letterSpacing: ".08em", textTransform: "uppercase", color: "#6c757d" }}>
            Full bins in inventory
          </div>
          <div style={{ fontSize: "2rem", fontWeight: 600 }}>{stats.full_bins_total}</div>
        </div>
        <div style={{ padding: "1rem", borderRadius: "1rem", background: "#fff", boxShadow: "0 2px 8px rgba(0,0,0,0.05)" }}>
          <div style={{ fontSize: "0.75rem", letterSpacing: ".08em", textTransform: "uppercase", color: "#6c757d" }}>
            Bins dumped today
          </div>
          <div style={{ fontSize: "2rem", fontWeight: 600 }}>{stats.bins_dumped_today}</div>
        </div>
        <div style={{ padding: "1rem", borderRadius: "1rem", background: "#fff", boxShadow: "0 2px 8px rgba(0,0,0,0.05)" }}>
          <div style={{ fontSize: "0.75rem", letterSpacing: ".08em", textTransform: "uppercase", color: "#6c757d" }}>
            Remaining bins
          </div>
          <div style={{ fontSize: "2rem", fontWeight: 600 }}>{stats.remaining_bins}</div>
        </div>
        <div style={{ padding: "1rem", borderRadius: "1rem", background: "#fff", boxShadow: "0 2px 8px rgba(0,0,0,0.05)" }}>
          <div style={{ fontSize: "0.75rem", letterSpacing: ".08em", textTransform: "uppercase", color: "#6c757d" }}>
            Boxes produced today
          </div>
          <div style={{ fontSize: "2rem", fontWeight: 600 }}>{stats.boxes_today}</div>
        </div>
      </section>

      <section style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(320px, 1fr))", gap: "1.5rem" }}>
        <div style={{ padding: "1rem", borderRadius: "1rem", background: "#fff", boxShadow: "0 2px 8px rgba(0,0,0,0.05)", height: 320 }}>
          <h3 style={{ fontSize: "1rem", marginBottom: ".5rem" }}>Boxes per hour (today)</h3>
          <Bar data={boxesData} options={{ responsive: true, maintainAspectRatio: false }} />
        </div>
        <div style={{ padding: "1rem", borderRadius: "1rem", background: "#fff", boxShadow: "0 2px 8px rgba(0,0,0,0.05)", height: 320 }}>
          <h3 style={{ fontSize: "1rem", marginBottom: ".5rem" }}>Bins dumped per hour (today)</h3>
          <Bar data={dumpData} options={{ responsive: true, maintainAspectRatio: false }} />
        </div>
        <div style={{ padding: "1rem", borderRadius: "1rem", background: "#fff", boxShadow: "0 2px 8px rgba(0,0,0,0.05)", height: 320 }}>
          <h3 style={{ fontSize: "1rem", marginBottom: ".5rem" }}>Inventory (received/dumped/remaining)</h3>
          <Bar data={invData} options={{ responsive: true, maintainAspectRatio: false }} />
        </div>
      </section>
    </main>
  );
}
