import { useMemo, useState } from 'react'
import { reportsApi } from '../services/reportsApi.js'
import { Button } from '../components/Button.jsx'
import { Input } from '../components/Input.jsx'
import { Alert } from '../components/Alert.jsx'
import { EmptyState } from '../components/EmptyState.jsx'

function StatBlock({ label, value }) {
  return (
    <div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
      <p className="text-sm font-medium text-slate-600">{label}</p>
      <p className="mt-3 text-3xl font-extrabold text-slate-900">{value ?? '—'}</p>
    </div>
  )
}

function PieList({ title, data }) {
  if (!data || Object.keys(data).length === 0) {
    return <EmptyState title={title} description="No statistics available for this period." />
  }

  const entries = Object.entries(data).sort((a, b) => (b[1] ?? 0) - (a[1] ?? 0))

  return (
    <div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
      <h3 className="text-base font-bold text-slate-900">{title}</h3>
      <div className="mt-3 space-y-2">
        {entries.map(([k, v]) => (
          <div key={k} className="flex items-center justify-between gap-4 rounded-xl bg-slate-50 px-3 py-2">
            <span className="text-sm font-medium text-slate-700">{k}</span>
            <span className="text-sm font-bold text-slate-900">{v}</span>
          </div>
        ))}
      </div>
    </div>
  )
}

export default function ReportsPage() {
  const today = useMemo(() => {
    const d = new Date()
    const yyyy = d.getFullYear()
    const mm = String(d.getMonth() + 1).padStart(2, '0')
    const dd = String(d.getDate()).padStart(2, '0')
    return `${yyyy}-${mm}-${dd}`
  }, [])

  const [mode, setMode] = useState('daily')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(null)

  const [dailyDate, setDailyDate] = useState(today)
  const [weeklyStart, setWeeklyStart] = useState(today)
  const [monthYear, setMonthYear] = useState(String(new Date().getFullYear()))
  const [monthMonth, setMonthMonth] = useState(String(new Date().getMonth() + 1).padStart(2, '0'))

  const [report, setReport] = useState(null)

  const fetchReport = async () => {
    setLoading(true)
    setError(null)
    try {
      if (mode === 'daily') {
        const data = await reportsApi.daily(dailyDate)
        setReport(data)
      } else if (mode === 'weekly') {
        const data = await reportsApi.weekly(weeklyStart)
        setReport(data)
      } else {
        const data = await reportsApi.monthly(Number(monthYear), Number(monthMonth))
        setReport(data)
      }
    } catch (e) {
      setError(e?.message || 'Failed to load report')
      setReport(null)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="space-y-5">
      <div>
        <h1 className="text-2xl font-bold text-slate-900">Reports</h1>
        <p className="mt-1 text-sm text-slate-600">Generate daily, weekly, and monthly aggregated reports.</p>
      </div>

      {error ? <Alert type="error" message={error} /> : null}

      <div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
        <div className="flex flex-col gap-4 md:flex-row md:items-end md:justify-between">
          <div className="space-y-2">
            <p className="text-sm font-semibold text-slate-900">Report Type</p>
            <div className="flex flex-wrap gap-2">
              {[
                { id: 'daily', label: 'Daily Reports' },
                { id: 'weekly', label: 'Weekly Reports' },
                { id: 'monthly', label: 'Monthly Reports' },
              ].map((t) => (
                <button
                  key={t.id}
                  type="button"
                  onClick={() => setMode(t.id)}
                  className={`rounded-xl border px-3 py-2 text-sm font-semibold transition-colors ${
                    mode === t.id ? 'border-slate-900 bg-slate-900 text-white' : 'border-slate-200 bg-white text-slate-900 hover:bg-slate-50'
                  }`}
                >
                  {t.label}
                </button>
              ))}
            </div>
          </div>

          <div className="flex gap-3">
            <Button type="button" onClick={fetchReport} disabled={loading}>
              {loading ? (
                <span className="inline-flex items-center gap-2"><span className="h-4 w-4 animate-spin rounded-full border-2 border-white/60 border-t-white" /> Generating…</span>
              ) : (
                'Generate Report'
              )}
            </Button>
          </div>
        </div>

        <div className="mt-5 grid gap-4 md:grid-cols-3">
          {mode === 'daily' ? (
            <div className="md:col-span-1">
              <Input label="Date" value={dailyDate} onChange={setDailyDate} placeholder="YYYY-MM-DD" />
            </div>
          ) : mode === 'weekly' ? (
            <div className="md:col-span-1">
              <Input label="Week Start" value={weeklyStart} onChange={setWeeklyStart} placeholder="YYYY-MM-DD" />
            </div>
          ) : (
            <>
              <div>
                <Input label="Year" value={monthYear} onChange={setMonthYear} placeholder="YYYY" />
              </div>
              <div>
                <Input label="Month" value={monthMonth} onChange={setMonthMonth} placeholder="MM" />
              </div>
            </>
          )}
        </div>
      </div>

      {loading ? (
        <div className="flex min-h-[30vh] items-center justify-center">
          <div className="h-10 w-10 animate-spin rounded-full border-2 border-slate-300 border-t-slate-900" />
        </div>
      ) : report ? (
        <div className="space-y-5">
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            <StatBlock label="Total Suppliers" value={report.totalSuppliers ?? report.totalSuppliersCount ?? report.total_suppliers} />
            <StatBlock label="Total Shipments" value={report.totalShipments ?? report.totalShipmentsCount ?? report.total_shipments} />
            <StatBlock label="Total Deliveries" value={report.totalDeliveries ?? report.totalDeliveriesCount ?? report.total_deliveries} />
          </div>

          <div className="grid gap-4 lg:grid-cols-2">
            <PieList title="Delivery Status Statistics" data={report.deliveryStatusStats || report.deliveryStatusStatistics || report.deliveryStatus} />
            <PieList title="Shipment Status Statistics" data={report.shipmentStatusStats || report.shipmentStatusStatistics || report.shipmentStatus} />
          </div>
        </div>
      ) : (
        <EmptyState title="No report generated yet" description="Choose a report type and click Generate Report." />
      )}
    </div>
  )
}

