import { useState } from 'react';
import API from '../api/axios';

const periods = [
  { id: 'daily', label: 'Daily Report' },
  { id: 'weekly', label: 'Weekly Report' },
  { id: 'monthly', label: 'Monthly Report' },
];

export default function Reports() {
  const [period, setPeriod] = useState('daily');
  const [report, setReport] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const generateReport = async (selectedPeriod) => {
    setPeriod(selectedPeriod);
    setLoading(true);
    setError('');

    try {
      const { data } = await API.get(`/reports/${selectedPeriod}`);
      setReport(data);
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to generate report.');
      setReport(null);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div className="mb-8">
        <h2 className="text-2xl font-bold text-ink-900">Inventory Reports</h2>
        <p className="text-ink-500 mt-1">Generate daily, weekly and monthly stock reports</p>
      </div>

      <div className="flex flex-wrap gap-3 mb-8">
        {periods.map((p) => (
          <button
            key={p.id}
            onClick={() => generateReport(p.id)}
            disabled={loading}
            className={`px-5 py-2.5 rounded-lg font-medium transition-colors ${
              period === p.id && report
                ? 'bg-primary-600 text-white shadow-sm shadow-primary-900/20'
                : 'bg-white/95 border border-ink-200 text-ink-700 hover:bg-ink-100'
            } disabled:opacity-50`}
          >
            {p.label}
          </button>
        ))}
      </div>

      {error && (
        <div className="mb-6 p-4 bg-rose-50 border border-rose-200 text-rose-700 rounded-lg text-sm">
          {error}
        </div>
      )}

      {loading && (
        <div className="flex justify-center py-12">
          <div className="animate-spin rounded-full h-10 w-10 border-4 border-primary-500 border-t-transparent" />
        </div>
      )}

      {report && !loading && (
        <div className="space-y-8">
          <div className="bg-white/95 rounded-xl shadow-sm shadow-ink-900/5 border border-ink-200 p-6">
            <h3 className="text-lg font-semibold capitalize mb-2">{report.period} Report Summary</h3>
            <p className="text-sm text-ink-500 mb-4">
              Period: {report.dateRange.startDate} to {report.dateRange.endDate}
            </p>
            <div className="grid sm:grid-cols-3 gap-4">
              <div className="bg-accent-50 rounded-lg p-4 border border-accent-100">
                <p className="text-sm text-accent-600 font-medium">Total Available Stock</p>
                <p className="text-2xl font-bold text-ink-900">{report.summary.totalAvailableStock} units</p>
              </div>
              <div className="bg-emerald-50 rounded-lg p-4 border border-emerald-100">
                <p className="text-sm text-emerald-600 font-medium">Total Stock IN</p>
                <p className="text-2xl font-bold text-emerald-800">{report.summary.totalStockIn} units</p>
              </div>
              <div className="bg-rose-50 rounded-lg p-4 border border-rose-100">
                <p className="text-sm text-rose-600 font-medium">Total Stock OUT</p>
                <p className="text-2xl font-bold text-rose-800">{report.summary.totalStockOut} units</p>
              </div>
            </div>
          </div>

          <ReportTable
            title="Available Stock"
            headers={['Code', 'Product', 'Category', 'Qty in Stock', 'Unit Price']}
            rows={report.availableStock.map((p) => [
              p.productCode,
              p.productName,
              p.category,
              p.quantityInStock,
              `${Number(p.unitPrice).toLocaleString()} RWF`,
            ])}
          />

          <ReportTable
            title="Stock IN Transactions"
            headers={['Date', 'Product', 'Warehouse', 'Quantity']}
            rows={report.stockIn.map((t) => [
              t.transactionDate?.split('T')[0] || t.transactionDate,
              t.productName,
              t.warehouseName,
              t.quantityMoved,
            ])}
            emptyMessage="No stock IN transactions in this period"
          />

          <ReportTable
            title="Stock OUT Transactions"
            headers={['Date', 'Product', 'Warehouse', 'Quantity']}
            rows={report.stockOut.map((t) => [
              t.transactionDate?.split('T')[0] || t.transactionDate,
              t.productName,
              t.warehouseName,
              t.quantityMoved,
            ])}
            emptyMessage="No stock OUT transactions in this period"
          />
        </div>
      )}

      {!report && !loading && !error && (
        <div className="text-center py-16 text-ink-500">
          Select a report period above to generate inventory reports
        </div>
      )}
    </div>
  );
}

function ReportTable({ title, headers, rows, emptyMessage = 'No data available' }) {
  return (
    <div className="bg-white/95 rounded-xl shadow-sm shadow-ink-900/5 border border-ink-200 p-6 overflow-hidden">
      <h3 className="text-lg font-semibold mb-4">{title}</h3>
      <div className="overflow-x-auto">
        <table className="min-w-full text-sm">
          <thead className="bg-ink-100">
            <tr>
              {headers.map((h) => (
                <th key={h} className="px-3 py-2 text-left font-medium text-ink-700">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-ink-100">
            {rows.map((row, i) => (
              <tr key={i} className="hover:bg-primary-50/60">
                {row.map((cell, j) => (
                  <td key={j} className="px-3 py-2">{cell}</td>
                ))}
              </tr>
            ))}
            {rows.length === 0 && (
              <tr>
                <td colSpan={headers.length} className="px-3 py-8 text-center text-ink-500">
                  {emptyMessage}
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
