"use client";

import React, { useEffect, useState } from "react";
// Example chart library:
// import { LineChart, Line, XAxis, YAxis, Tooltip, CartesianGrid } from "recharts";

interface DailyDataPoint {
  date: string;
  count: number;
}

interface AnalyticsData {
  success?: boolean;
  orders?: {
    total: number;
    today: number;
    week: number;
    dailyOrders: DailyDataPoint[];
  };
  revenue?: {
    total: number;
    today: number;
    week: number;
    dailyRevenue: DailyDataPoint[];
  };
  vendors?: {
    total: number;
    newToday: number;
    newThisWeek: number;
    dailyVendors: DailyDataPoint[];
  };
  engagement?: {
    totalChats: number;
    activeChatsToday: number;
    dailyChats: DailyDataPoint[];
  };
  products?: {
    total: number;
  };
  message?: string;
}

export default function AdminDashboardPage() {
  const [analytics, setAnalytics] = useState<AnalyticsData | null>(null);
  const [loading, setLoading] = useState(true);

  const fetchAnalytics = async () => {
    try {
      setLoading(true);
      const response = await fetch(`/api/admin/analytics`, {
        headers: {
          'Authorization': `Bearer ${process.env.NEXT_PUBLIC_JWT_SECRET}`
        }
      });
      const data = await response.json();
      setAnalytics(data);
    } catch (error) {
      console.error("Error fetching analytics:", error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchAnalytics();
  }, []);

  if (loading) {
    return <div className="p-4">Loading Admin Dashboard...</div>;
  }

  if (!analytics?.success) {
    return (
      <div className="p-4">
        <h2>Error Fetching Analytics</h2>
        <p>{analytics?.message || "Unknown error occurred."}</p>
      </div>
    );
  }

  // Deconstruct the analytics data
  const {
    orders,
    revenue,
    vendors,
    engagement,
    products,
  } = analytics;

  return (
    <div className="p-4">
      <h1 className="text-2xl font-bold mb-4">Admin Dashboard</h1>

      {/* Quick stats row */}
      <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
        <div className="bg-white rounded shadow p-4">
          <h2 className="font-bold text-lg mb-2">Total Orders</h2>
          <p className="text-xl">{orders?.total || 0}</p>
          <p className="text-sm text-gray-600">
            Today: {orders?.today || 0} | This Week: {orders?.week || 0}
          </p>
        </div>

        <div className="bg-white rounded shadow p-4">
          <h2 className="font-bold text-lg mb-2">Revenue</h2>
          <p className="text-xl">£{revenue?.total?.toFixed(2) || 0}</p>
          <p className="text-sm text-gray-600">
            Today: £{revenue?.today?.toFixed(2) || 0} | This Week: £{revenue?.week?.toFixed(2) || 0}
          </p>
        </div>

        <div className="bg-white rounded shadow p-4">
          <h2 className="font-bold text-lg mb-2">Vendors</h2>
          <p className="text-xl">{vendors?.total || 0}</p>
          <p className="text-sm text-gray-600">
            New Today: {vendors?.newToday || 0} | This Week: {vendors?.newThisWeek || 0}
          </p>
        </div>

        <div className="bg-white rounded shadow p-4">
          <h2 className="font-bold text-lg mb-2">Chats</h2>
          <p className="text-xl">{engagement?.totalChats || 0}</p>
          <p className="text-sm text-gray-600">
            Active Today: {engagement?.activeChatsToday || 0}
          </p>
        </div>

        <div className="bg-white rounded shadow p-4">
          <h2 className="font-bold text-lg mb-2">Products</h2>
          <p className="text-xl">{products?.total || 0}</p>
        </div>
      </div>

      {/* Example chart section */}
      <div className="mt-8 bg-white p-4 rounded shadow">
        <h2 className="text-lg font-bold mb-4">Orders This Week</h2>

        {/* 
        Uncomment and customize if using a chart library like Recharts:

        <LineChart
          width={800}
          height={300}
          data={orders?.dailyOrders || []}
          margin={{ top: 5, right: 20, left: 10, bottom: 5 }}
        >
          <CartesianGrid stroke="#ccc" strokeDasharray="5 5" />
          <XAxis dataKey="date" />
          <YAxis />
          <Tooltip />
          <Line type="monotone" dataKey="count" stroke="#8884d8" />
        </LineChart>
        */}

        <pre className="text-sm bg-gray-100 p-2 rounded mt-2">
          {JSON.stringify(orders?.dailyOrders, null, 2)}
        </pre>
      </div>
    </div>
  );
} 