import { useState } from 'react';
import api from '../api/axios';
import PageHeader, { Alert, DataTable } from '../components/PageUI';

const periods = [
  { value: 'daily', label: 'Daily Report' },
  { value: 'weekly', label: 'Weekly Report' },
  { value: '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 () => {
    setLoading(true);
    setError('');
    try {
      const { data } = await api.get(`/reports/${period}`);
      setReport(data);
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to generate report');
      setReport(null);
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      <PageHeader description="Generate daily, weekly and monthly supply chain reports." />

      <div className="form-card mb-5 flex flex-col gap-3 sm:flex-row sm:items-end">
        <div className="flex-1">
          <label className="mb-1 block text-xs font-medium text-gray-600">Report Period</label>
          <select value={period} onChange={(e) => setPeriod(e.target.value)} className="input-field">
            {periods.map((p) => (
              <option key={p.value} value={p.value}>{p.label}</option>
            ))}
          </select>
        </div>
        <button onClick={generateReport} disabled={loading} className="btn-primary sm:mb-0.5">
          {loading ? 'Generating...' : 'Generate Report'}
        </button>
      </div>

      <Alert type="error" message={error} />

      {report && (
        <div className="space-y-5">
          <p className="text-xs text-gray-500">
            {formatDate(report.dateRange?.start)} - {formatDate(report.dateRange?.end)}
          </p>

          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
            {[
              { label: 'Suppliers', val: report.summary.totalSuppliers },
              { label: 'Shipments', val: report.summary.totalShipments },
              { label: 'Deliveries', val: report.summary.totalDeliveries },
              { label: 'Total Qty', val: report.summary.totalQuantityDelivered },
            ].map((s) => (
              <div key={s.label} className="form-card py-3 text-center">
                <p className="text-[10px] font-medium uppercase tracking-wide text-gray-500">{s.label}</p>
                <p className="text-2xl font-bold text-primary-700">{s.val}</p>
              </div>
            ))}
          </div>

          <DataTable title="Suppliers" count={report.suppliers?.length || 0} columns={[
            { key: 'supplierCode', label: 'Code', bold: true },
            { key: 'supplierName', label: 'Name' },
            { key: 'telephone', label: 'Phone' },
            { key: 'email', label: 'Email' },
          ]} data={report.suppliers || []} />

          <DataTable title="Shipments" count={report.shipments?.length || 0} columns={[
            { key: 'shipmentNumber', label: 'Number', bold: true },
            { key: 'shipmentDate', label: 'Date', format: formatDate },
            { key: 'shipmentStatus', label: 'Status' },
            { key: 'destination', label: 'Destination' },
          ]} data={report.shipments || []} />

          <DataTable title="Deliveries" count={report.deliveries?.length || 0} columns={[
            { key: 'deliveryCode', label: 'Code', bold: true },
            { key: 'deliveryDate', label: 'Date', format: formatDate },
            { key: 'quantityDelivered', label: 'Qty' },
            { key: 'deliveryStatus', label: 'Status' },
          ]} data={report.deliveries || []} />
        </div>
      )}
    </>
  );
}

function formatDate(value) {
  if (!value) return '-';
  const d = new Date(value);
  return Number.isNaN(d.getTime()) ? '-' : d.toLocaleDateString();
}
