'use client';

import React, { useEffect, useState } from 'react';
import { Bar } from 'react-chartjs-2';
import { Loader, AlertTriangle, CheckCircle, RefreshCw } from 'lucide-react';
import * as Dialog from '@radix-ui/react-dialog';
import 'chart.js/auto';

const AdminDashboard: React.FC = () => {
  const [salesData, setSalesData] = useState<number[]>([]);
  const [lowStockItems, setLowStockItems] = useState<any[]>([]);
  const [orders, setOrders] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Fetch data from APIs
  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        const [salesRes, inventoryRes] = await Promise.all([
          fetch('/api/swag/admin/sales'),
          fetch('/api/swag/admin/inventory'),
        ]);

        if (!salesRes.ok || !inventoryRes.ok) {
          throw new Error('Failed to fetch data');
        }

        const sales = await salesRes.json();
        const inventory = await inventoryRes.json();

        setSalesData(sales.metrics);
        setLowStockItems(inventory.lowStock);
        setOrders(inventory.orders);
      } catch (err) {
        setError('Failed to load dashboard data.');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  // Sales chart configuration
  const salesChartData = {
    labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul'],
    datasets: [
      {
        label: 'Revenue',
        data: salesData,
        backgroundColor: 'rgba(6, 182, 212, 0.5)',
        borderColor: '#0EA5E9',
        borderWidth: 2,
      },
    ],
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen bg-brand-bg text-white">
        <Loader className="animate-spin" size={32} />
        <span className="ml-4">Loading dashboard...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-screen bg-brand-bg text-white">
        <AlertTriangle className="text-red-500" size={32} />
        <span className="ml-4">{error}</span>
      </div>
    );
  }

  return (
    <div className="bg-brand-bg text-white min-h-screen p-6 space-y-6">
      <header className="flex justify-between items-center">
        <h1 className="text-3xl font-bold">Admin Dashboard</h1>
        <button className="flex items-center px-4 py-2 bg-brand text-white rounded-lg hover:bg-brand-deep transition">
          <RefreshCw className="mr-2" size={20} />
          Refresh
        </button>
      </header>

      {/* Sales Metrics */}
      <section className="glass-card p-6">
        <h2 className="text-xl font-semibold mb-4">Sales Metrics</h2>
        <Bar data={salesChartData} />
      </section>

      {/* Low Stock Alerts */}
      <section className="glass-card p-6">
        <h2 className="text-xl font-semibold mb-4">Low Stock Alerts</h2>
        {lowStockItems.length > 0 ? (
          <ul className="space-y-2">
            {lowStockItems.map((item) => (
              <li
                key={item.id}
                className="flex justify-between items-center p-4 bg-white/5 rounded-lg"
              >
                <span>{item.name}</span>
                <span className="text-red-400">Stock: {item.stock}</span>
              </li>
            ))}
          </ul>
        ) : (
          <p className="text-green-400">All items are sufficiently stocked.</p>
        )}
      </section>

      {/* Order Management Table */}
      <section className="glass-card p-6">
        <h2 className="text-xl font-semibold mb-4">Order Management</h2>
        <table className="w-full text-left border-collapse">
          <thead>
            <tr className="bg-white/10">
              <th className="p-4">Order ID</th>
              <th className="p-4">Customer</th>
              <th className="p-4">Status</th>
              <th className="p-4">Total</th>
            </tr>
          </thead>
          <tbody>
            {orders.map((order, index) => (
              <tr
                key={order.id}
                className={`${
                  index % 2 === 0 ? 'bg-white/5' : 'bg-white/10'
                } hover:bg-white/20 transition`}
              >
                <td className="p-4">{order.id}</td>
                <td className="p-4">{order.customer}</td>
                <td className="p-4">
                  <span
                    className={`px-2 py-1 rounded-lg ${
                      order.status === 'completed'
                        ? 'bg-green-400'
                        : 'bg-yellow-400'
                    }`}
                  >
                    {order.status}
                  </span>
                </td>
                <td className="p-4">${order.total.toFixed(2)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </section>

      {/* ERP Sync Status */}
      <section className="glass-card p-6 flex items-center space-x-4">
        <CheckCircle className="text-green-400" size={32} />
        <span>ERP Sync is active and up-to-date.</span>
      </section>
    </div>
  );
};

export default AdminDashboard;