import { useEffect, useState } from 'react'
import { apiClient } from '../services/apiClient.js'
import { EmptyState } from '../components/EmptyState.jsx'

function MetricCard({ title, value, subtitle }) {
  return (
    <div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
      <p className="text-sm font-medium text-slate-600">{title}</p>
      <p className="mt-3 text-3xl font-extrabold text-slate-900">{value ?? '—'}</p>
      {subtitle ? <p className="mt-1 text-xs text-slate-500">{subtitle}</p> : null}
    </div>
  )
}

export default function DashboardPage() {
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  const [stats, setStats] = useState({ totalSuppliers: 0, totalShipments: 0, totalDeliveries: 0 })

  useEffect(() => {
    let mounted = true
    async function run() {
      setLoading(true)
      try {
        // There is no explicit totals endpoint in backend README.
        // We'll infer by hitting report endpoints is not correct; so instead use reports controller monthly? not.
        // Fallback: call suppliers/shipments/deliveries list and compute lengths.
        const [suppliersRes, shipmentsRes, deliveriesRes] = await Promise.all([
          apiClient.get('/api/suppliers'),
          apiClient.get('/api/shipments'),
          apiClient.get('/api/deliveries'),
        ])

        if (!mounted) return
        const [suppliers, shipments, deliveries] = [
          Array.isArray(suppliersRes.data) ? suppliersRes.data : (suppliersRes.data?.data ?? []),
          Array.isArray(shipmentsRes.data) ? shipmentsRes.data : (shipmentsRes.data?.data ?? []),
          Array.isArray(deliveriesRes.data) ? deliveriesRes.data : (deliveriesRes.data?.data ?? []),
        ]
        setStats({
          totalSuppliers: suppliers.length,
          totalShipments: shipments.length,
          totalDeliveries: deliveries.length,
        })
      } catch (e) {
        if (!mounted) return
        setError(e?.message || 'Failed to load dashboard')
      } finally {
        if (mounted) setLoading(false)
      }
    }
    run()
    return () => {
      mounted = false
    }
  }, [])

  if (loading) {
    return (
      <div className="flex min-h-[40vh] items-center justify-center">
        <div className="h-10 w-10 animate-spin rounded-full border-2 border-slate-300 border-t-slate-900" />
      </div>
    )
  }

  if (error) {
    return (
      <EmptyState
        title="Could not load dashboard"
        description={error}
        actionLabel="Retry"
        onAction={() => window.location.reload()}
      />
    )
  }

  return (
    <div className="space-y-5">
      <div className="flex flex-col gap-2 md:flex-row md:items-end md:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Dashboard</h1>
          <p className="mt-1 text-sm text-slate-600">A quick overview of your supply chain operations.</p>
        </div>
      </div>

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        <MetricCard title="Total Suppliers" value={stats.totalSuppliers} />
        <MetricCard title="Total Shipments" value={stats.totalShipments} />
        <MetricCard title="Total Deliveries" value={stats.totalDeliveries} />
      </div>

      <div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
        <h2 className="text-base font-bold text-slate-900">Tip</h2>
        <p className="mt-2 text-sm text-slate-600">
          Use the Supplier, Shipment, and Delivery pages to create and manage records. Reports provide aggregated views over time.
        </p>
      </div>
    </div>
  )
}

