import { useEffect, useMemo, useState } from 'react';
import useProductStore from '../../store/productStore';
import useSalesStore from '../../store/saleStore';
import useCustomerStore from '../../store/customerStore';
import useReportStore from '../../store/reportStore';

const DashboardPage = () => {
  const { products, fetchProducts } = useProductStore();
  const { sales, fetchSales } = useSalesStore();
  const { customers, fetchCustomers } = useCustomerStore();

  const { dailySales, fetchDailySales, monthlySales, fetchMonthlySales, productStock, fetchProductStock, customerPurchases, fetchCustomerPurchases } = useReportStore();

  const [dailyDate, setDailyDate] = useState('');
  const [monthlyStartDate, setMonthlyStartDate] = useState('');
  const [monthlyEndDate, setMonthlyEndDate] = useState('');
  const [selectedCustomer, setSelectedCustomer] = useState('');

  useEffect(() => {
    fetchProducts();
    fetchSales();
    fetchCustomers();
    fetchProductStock();
  }, []);

  useEffect(() => {
    // set default customer once customers loaded
    if (!selectedCustomer && customers?.length) {
      setSelectedCustomer(customers[0].customer_name || customers[0].name || customers[0].customer_id);
    }
  }, [customers, selectedCustomer]);

  const totalRevenue = useMemo(
    () => sales.reduce((sum, sale) => sum + Number(sale.total_price || 0), 0),
    [sales]
  );

  return (
    <div className="p-6">
      <h1 className="text-2xl font-bold text-gray-800 mb-6">Dashboard</h1>

      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
        <div className="bg-blue-500 text-white p-4 rounded-lg">
          <p className="text-sm">Products</p>
          <p className="text-2xl font-bold">{products.length}</p>
        </div>
        <div className="bg-green-500 text-white p-4 rounded-lg">
          <p className="text-sm">Sales</p>
          <p className="text-2xl font-bold">{sales.length}</p>
        </div>
        <div className="bg-purple-500 text-white p-4 rounded-lg">
          <p className="text-sm">Customers</p>
          <p className="text-2xl font-bold">{customers.length}</p>
        </div>
        <div className="bg-yellow-500 text-white p-4 rounded-lg">
          <p className="text-sm">Revenue</p>
          <p className="text-2xl font-bold">${totalRevenue.toLocaleString()}</p>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div className="bg-white p-4 rounded-lg shadow md:col-span-2">
          <h3 className="text-lg font-semibold mb-4">Recent Sales</h3>
          {sales.length === 0 ? (
            <p className="text-gray-500">No sales yet</p>
          ) : (
            <ul className="space-y-2">
              {sales.slice(0, 5).map((sale) => (
                <li key={sale.sale_id} className="flex justify-between border-b pb-2">
                  <span>{sale.product_name}</span>
                  <span className="font-semibold">${Number(sale.total_price || 0).toLocaleString()}</span>
                </li>
              ))}
            </ul>
          )}
        </div>
      </div>

      <div className="mt-8 space-y-8">
        {/* A. DAILY SALES REPORT */}
        <div className="bg-white p-4 rounded-lg shadow">
          <h3 className="text-lg font-semibold mb-4">A. Daily Sales Report (filter by specific date)</h3>
          <div className="flex flex-col sm:flex-row gap-3 items-start sm:items-center mb-4">
            <input
              type="date"
              value={dailyDate}
              onChange={(e) => setDailyDate(e.target.value)}
              className="border rounded px-3 py-2"
            />
            <button
              onClick={() => dailyDate && fetchDailySales(dailyDate)}
              className="bg-blue-600 text-white px-4 py-2 rounded disabled:opacity-50"
              disabled={!dailyDate}
            >
              Generate Daily Report
            </button>
          </div>

          {dailySales?.length ? (
            <div className="overflow-x-auto">
              <table className="min-w-full text-sm">
                <thead>
                  <tr className="text-left border-b">
                    <th className="py-2">Product</th>
                    <th className="py-2">Customer</th>
                    <th className="py-2">Date</th>
                    <th className="py-2">Qty</th>
                    <th className="py-2">Total</th>
                  </tr>
                </thead>
                <tbody>
                  {dailySales.map((row) => (
                    <tr key={row.sale_id} className="border-b last:border-b-0">
                      <td className="py-2">{row.product_name}</td>
                      <td className="py-2">{row.customer_name}</td>
                      <td className="py-2">{row.sale_date}</td>
                      <td className="py-2">{row.quantity}</td>
                      <td className="py-2">${Number(row.total_price || 0).toLocaleString()}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            <p className="text-gray-500">{dailyDate ? 'No sales found for this date.' : 'Choose a date to generate report.'}</p>
          )}
        </div>

        {/* B. MONTHLY SALES REPORT */}
        <div className="bg-white p-4 rounded-lg shadow">
          <h3 className="text-lg font-semibold mb-4">B. Monthly Sales Report (filter by start_date & end_date)</h3>
          <div className="flex flex-col sm:flex-row gap-3 items-start sm:items-center mb-4">
            <input
              type="date"
              value={monthlyStartDate}
              onChange={(e) => setMonthlyStartDate(e.target.value)}
              className="border rounded px-3 py-2"
            />
            <input
              type="date"
              value={monthlyEndDate}
              onChange={(e) => setMonthlyEndDate(e.target.value)}
              className="border rounded px-3 py-2"
            />
            <button
              onClick={() => (monthlyStartDate && monthlyEndDate ? fetchMonthlySales(monthlyStartDate, monthlyEndDate) : null)}
              className="bg-blue-600 text-white px-4 py-2 rounded disabled:opacity-50"
              disabled={!monthlyStartDate || !monthlyEndDate}
            >
              Generate Monthly Report
            </button>
          </div>

          {monthlySales?.length ? (
            <div className="overflow-x-auto">
              <table className="min-w-full text-sm">
                <thead>
                  <tr className="text-left border-b">
                    <th className="py-2">Product</th>
                    <th className="py-2">Customer</th>
                    <th className="py-2">Date</th>
                    <th className="py-2">Qty</th>
                    <th className="py-2">Total</th>
                  </tr>
                </thead>
                <tbody>
                  {monthlySales.map((row) => (
                    <tr key={row.sale_id} className="border-b last:border-b-0">
                      <td className="py-2">{row.product_name}</td>
                      <td className="py-2">{row.customer_name}</td>
                      <td className="py-2">{row.sale_date}</td>
                      <td className="py-2">{row.quantity}</td>
                      <td className="py-2">${Number(row.total_price || 0).toLocaleString()}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            <p className="text-gray-500">Choose start/end dates to generate report.</p>
          )}
        </div>

        {/* C. PRODUCT STOCK REPORT */}
        <div className="bg-white p-4 rounded-lg shadow">
          <h3 className="text-lg font-semibold mb-4">C. Product Stock Report (available stock, sold stock)</h3>
          <button
            onClick={fetchProductStock}
            className="mb-4 bg-gray-800 text-white px-4 py-2 rounded"
          >
            Refresh Stock Report
          </button>

          {productStock?.length ? (
            <div className="overflow-x-auto">
              <table className="min-w-full text-sm">
                <thead>
                  <tr className="text-left border-b">
                    <th className="py-2">Product</th>
                    <th className="py-2">Category</th>
                    <th className="py-2">Available Stock</th>
                    <th className="py-2">Sold Stock</th>
                  </tr>
                </thead>
                <tbody>
                  {productStock.map((row) => (
                    <tr key={row.product_id} className="border-b last:border-b-0">
                      <td className="py-2">{row.product_name}</td>
                      <td className="py-2">{row.category}</td>
                      <td className="py-2 font-semibold">{row.available_stock}</td>
                      <td className="py-2">{row.sold_stock}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            <p className="text-gray-500">No stock data.</p>
          )}
        </div>

        {/* D. CUSTOMER PURCHASE REPORT */}
        <div className="bg-white p-4 rounded-lg shadow">
          <h3 className="text-lg font-semibold mb-4">D. Customer Purchase Report (all purchases by selected customer)</h3>
          <div className="flex flex-col sm:flex-row gap-3 items-start sm:items-center mb-4">
            <select
              value={selectedCustomer}
              onChange={(e) => setSelectedCustomer(e.target.value)}
              className="border rounded px-3 py-2 w-full sm:w-80"
            >
              {customers?.length ? (
                customers.map((c) => {
                  const value = c.customer_name || c.name || c.customer_id;
                  return (
                    <option key={c.customer_id || c.customer_name || c.name} value={value}>
                      {c.customer_name || c.name}
                    </option>
                  );
                })
              ) : (
                <option value="">No customers</option>
              )}
            </select>

            <button
              onClick={() => selectedCustomer && fetchCustomerPurchases(selectedCustomer)}
              className="bg-blue-600 text-white px-4 py-2 rounded disabled:opacity-50"
              disabled={!selectedCustomer}
            >
              Generate Customer Purchases
            </button>
          </div>

          {customerPurchases?.length ? (
            <div className="overflow-x-auto">
              <table className="min-w-full text-sm">
                <thead>
                  <tr className="text-left border-b">
                    <th className="py-2">Product</th>
                    <th className="py-2">Date</th>
                    <th className="py-2">Qty</th>
                    <th className="py-2">Total</th>
                  </tr>
                </thead>
                <tbody>
                  {customerPurchases.map((row) => (
                    <tr key={row.sale_id} className="border-b last:border-b-0">
                      <td className="py-2">{row.product_name}</td>
                      <td className="py-2">{row.sale_date}</td>
                      <td className="py-2">{row.quantity}</td>
                      <td className="py-2">${Number(row.total_price || 0).toLocaleString()}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            <p className="text-gray-500">Select a customer to view purchases.</p>
          )}
        </div>
      </div>
    </div>
  );
};

export default DashboardPage;
