import { useEffect, useState } from 'react';
import { Calendar, Package, FileText } from 'lucide-react';
import useReportStore from '../../store/reportStore';
import Button from '../../components/UI/Button';
import Input from '../../components/UI/Input';

const ReportsPage = () => {
  const { dailySales, monthlySales, productStock, customerPurchases, loading, fetchDailySales, fetchMonthlySales, fetchProductStock, fetchCustomerPurchases } = useReportStore();
  const [dateRange, setDateRange] = useState({ startDate: '', endDate: '' });
  const [selectedReport, setSelectedReport] = useState('daily');

  useEffect(() => {
    const today = new Date().toISOString().split('T')[0];
    fetchDailySales(today);
  }, []);

  const handleDailyReport = () => {
    const today = new Date().toISOString().split('T')[0];
    fetchDailySales(today);
  };

  const handleMonthlyReport = () => {
    if (dateRange.startDate && dateRange.endDate) {
      fetchMonthlySales(dateRange.startDate, dateRange.endDate);
    }
  };

  const handleStockReport = () => {
    fetchProductStock();
  };

  const renderReportContent = () => {
    switch (selectedReport) {
      case 'daily':
        return (
          <div className="space-y-4">
            <h3 className="text-lg font-semibold text-gray-800 dark:text-white">Daily Sales Report</h3>
            {dailySales.length > 0 ? (
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-gray-50 dark:bg-gray-700">
                    <tr>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Product</th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Quantity</th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Total</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                    {dailySales.map((sale, idx) => (
                      <tr key={idx} className="hover:bg-gray-50 dark:hover:bg-gray-700">
                        <td className="px-6 py-4 text-gray-800 dark:text-white">{sale.product_name}</td>
                        <td className="px-6 py-4 text-gray-500 dark:text-gray-400">{sale.total_quantity}</td>
                        <td className="px-6 py-4 text-gray-800 dark:text-white font-semibold">${(sale.total_sales || 0).toLocaleString()}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <p className="text-gray-500 dark:text-gray-400 text-center py-4">No sales data for today</p>
            )}
          </div>
        );
      case 'monthly':
        return (
          <div className="space-y-4">
            <h3 className="text-lg font-semibold text-gray-800 dark:text-white">Monthly Sales Report</h3>
            <div className="flex gap-4 mb-4">
              <Input label="Start Date" type="date" value={dateRange.startDate} onChange={(e) => setDateRange({ ...dateRange, startDate: e.target.value })} />
              <Input label="End Date" type="date" value={dateRange.endDate} onChange={(e) => setDateRange({ ...dateRange, endDate: e.target.value })} />
              <div className="flex items-end">
                <Button onClick={handleMonthlyReport} loading={loading}>Generate</Button>
              </div>
            </div>
            {monthlySales.length > 0 ? (
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-gray-50 dark:bg-gray-700">
                    <tr>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Date</th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Total Sales</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                    {monthlySales.map((sale, idx) => (
                      <tr key={idx} className="hover:bg-gray-50 dark:hover:bg-gray-700">
                        <td className="px-6 py-4 text-gray-800 dark:text-white">{new Date(sale.date).toLocaleDateString()}</td>
                        <td className="px-6 py-4 text-gray-800 dark:text-white font-semibold">${(sale.total_sales || 0).toLocaleString()}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <p className="text-gray-500 dark:text-gray-400 text-center py-4">Select date range and click Generate</p>
            )}
          </div>
        );
      case 'stock':
        return (
          <div className="space-y-4">
            <h3 className="text-lg font-semibold text-gray-800 dark:text-white">Product Stock Report</h3>
            {productStock.length > 0 ? (
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-gray-50 dark:bg-gray-700">
                    <tr>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Product</th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">SKU</th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Stock</th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Status</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                    {productStock.map((product) => (
                      <tr key={product.id} className="hover:bg-gray-50 dark:hover:bg-gray-700">
                        <td className="px-6 py-4 text-gray-800 dark:text-white">{product.name}</td>
                        <td className="px-6 py-4 text-gray-500 dark:text-gray-400">{product.sku}</td>
                        <td className="px-6 py-4 text-gray-800 dark:text-white">{product.stock}</td>
                        <td className="px-6 py-4">
                          <span className={`px-2 py-1 rounded text-sm ${product.stock < 10 ? 'bg-red-100 text-red-600 dark:bg-red-900 dark:text-red-400' : 'bg-green-100 text-green-600 dark:bg-green-900 dark:text-green-400'}`}>
                            {product.stock < 10 ? 'Low Stock' : 'In Stock'}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <p className="text-gray-500 dark:text-gray-400 text-center py-4">No stock data available</p>
            )}
          </div>
        );
      default:
        return null;
    }
  };

  return (
    <div className="space-y-6">
      <h2 className="text-2xl font-bold text-gray-800 dark:text-white">Reports</h2>
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <button
          onClick={() => { setSelectedReport('daily'); handleDailyReport(); }}
          className={`p-6 rounded-xl shadow transition-all ${selectedReport === 'daily' ? 'bg-blue-600 text-white' : 'bg-white dark:bg-gray-800 text-gray-800 dark:text-white hover:shadow-md'}`}
        >
          <Calendar className="w-8 h-8 mb-2" />
          <h3 className="font-semibold">Daily Sales</h3>
          <p className="text-sm opacity-75">View today's sales</p>
        </button>
        <button
          onClick={() => { setSelectedReport('monthly'); }}
          className={`p-6 rounded-xl shadow transition-all ${selectedReport === 'monthly' ? 'bg-blue-600 text-white' : 'bg-white dark:bg-gray-800 text-gray-800 dark:text-white hover:shadow-md'}`}
        >
          <FileText className="w-8 h-8 mb-2" />
          <h3 className="font-semibold">Monthly Report</h3>
          <p className="text-sm opacity-75">Custom date range</p>
        </button>
        <button
          onClick={() => { setSelectedReport('stock'); handleStockReport(); }}
          className={`p-6 rounded-xl shadow transition-all ${selectedReport === 'stock' ? 'bg-blue-600 text-white' : 'bg-white dark:bg-gray-800 text-gray-800 dark:text-white hover:shadow-md'}`}
        >
          <Package className="w-8 h-8 mb-2" />
          <h3 className="font-semibold">Stock Report</h3>
          <p className="text-sm opacity-75">Inventory status</p>
        </button>
      </div>
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow p-6">
        {renderReportContent()}
      </div>
    </div>
  );
};

export default ReportsPage;