import { useQuery } from '@tanstack/react-query'
import { dashboardApi } from '../../api'
import {
  ArchiveBoxIcon, UserGroupIcon, KeyIcon,
  CurrencyDollarIcon, ExclamationCircleIcon, ClockIcon,
} from '@heroicons/react/24/outline'
import { Link } from 'react-router-dom'
import { format } from 'date-fns'

function KpiCard({ label, value, sub, icon: Icon, color }: any) {
  return (
    <div className="card flex items-start justify-between">
      <div>
        <p className="text-slate-400 text-sm">{label}</p>
        <p className="text-3xl font-bold text-white mt-1">{value}</p>
        {sub && <p className="text-xs text-slate-400 mt-1">{sub}</p>}
      </div>
      <div className={`p-3 rounded-xl ${color}`}>
        <Icon className="w-6 h-6 text-white" />
      </div>
    </div>
  )
}

export default function DashboardPage() {
  const { data, isLoading } = useQuery({
    queryKey: ['dashboard'],
    queryFn: () => dashboardApi.getSummary().then((r) => r.data),
    refetchInterval: 60000,
  })

  if (isLoading) {
    return <div className="text-slate-400 text-center py-20">Loading dashboard…</div>
  }

  const d = data ?? {}

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-white">Dashboard</h1>
        <p className="text-slate-400 text-sm mt-1">{format(new Date(), 'EEEE, d MMMM yyyy')}</p>
      </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
        <KpiCard
          label="Locker Occupancy"
          value={`${d.lockers?.occupancy_rate ?? 0}%`}
          sub={`${d.lockers?.occupied ?? 0} occupied / ${d.lockers?.total ?? 0} total`}
          icon={ArchiveBoxIcon}
          color="bg-blue-600"
        />
        <KpiCard
          label="Active Clients"
          value={d.clients?.active ?? 0}
          sub={`+${d.clients?.new_this_month ?? 0} this month`}
          icon={UserGroupIcon}
          color="bg-green-600"
        />
        <KpiCard
          label="Active Rentals"
          value={d.rentals?.active ?? 0}
          sub={`${d.rentals?.expiring_in_7d ?? 0} expiring in 7 days`}
          icon={KeyIcon}
          color="bg-purple-600"
        />
        <KpiCard
          label="Revenue This Month"
          value={`৳${Number(d.revenue?.this_month ?? 0).toLocaleString()}`}
          sub={`৳${Number(d.revenue?.today ?? 0).toLocaleString()} today`}
          icon={CurrencyDollarIcon}
          color="bg-amber-600"
        />
      </div>

      {/* Alerts row */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        {d.rentals?.overdue > 0 && (
          <Link to="/rentals?status=overdue" className="card border-red-800 hover:border-red-600 transition-colors">
            <div className="flex items-center gap-3">
              <ExclamationCircleIcon className="w-8 h-8 text-red-400" />
              <div>
                <p className="font-semibold text-red-300">{d.rentals.overdue} Overdue Rentals</p>
                <p className="text-xs text-slate-400">Requires immediate attention</p>
              </div>
            </div>
          </Link>
        )}
        {d.rentals?.expiring_in_3d > 0 && (
          <Link to="/rentals?expiring=3" className="card border-yellow-800 hover:border-yellow-600 transition-colors">
            <div className="flex items-center gap-3">
              <ClockIcon className="w-8 h-8 text-yellow-400" />
              <div>
                <p className="font-semibold text-yellow-300">{d.rentals.expiring_in_3d} Expiring in 3 days</p>
                <p className="text-xs text-slate-400">Send reminders now</p>
              </div>
            </div>
          </Link>
        )}
        {d.lockers?.maintenance > 0 && (
          <Link to="/lockers?status=maintenance" className="card border-orange-800">
            <div className="flex items-center gap-3">
              <ArchiveBoxIcon className="w-8 h-8 text-orange-400" />
              <div>
                <p className="font-semibold text-orange-300">{d.lockers.maintenance} Under Maintenance</p>
                <p className="text-xs text-slate-400">Lockers unavailable</p>
              </div>
            </div>
          </Link>
        )}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Recent Rentals */}
        <div className="card">
          <div className="flex items-center justify-between mb-4">
            <h2 className="font-semibold text-white">Recent Rentals</h2>
            <Link to="/rentals" className="text-blue-400 text-sm hover:underline">View all</Link>
          </div>
          <div className="space-y-2">
            {(d.recent_rentals ?? []).map((r: any) => (
              <Link
                key={r.id}
                to={`/rentals/${r.id}`}
                className="flex items-center justify-between p-3 rounded-lg hover:bg-slate-700 transition-colors"
              >
                <div>
                  <p className="text-sm font-medium text-white">{r.client_name}</p>
                  <p className="text-xs text-slate-400">Locker {r.locker_number} · {r.rental_number}</p>
                </div>
                <span className={`badge-${r.status}`}>{r.status}</span>
              </Link>
            ))}
          </div>
        </div>

        {/* Expiring Soon */}
        <div className="card">
          <div className="flex items-center justify-between mb-4">
            <h2 className="font-semibold text-white">Expiring Soon (7 days)</h2>
            <Link to="/rentals?expiring=7" className="text-blue-400 text-sm hover:underline">View all</Link>
          </div>
          <div className="space-y-2">
            {(d.expiring_soon ?? []).length === 0 && (
              <p className="text-slate-400 text-sm text-center py-4">No rentals expiring soon.</p>
            )}
            {(d.expiring_soon ?? []).map((r: any) => (
              <Link
                key={r.id}
                to={`/rentals/${r.id}`}
                className="flex items-center justify-between p-3 rounded-lg hover:bg-slate-700 transition-colors"
              >
                <div>
                  <p className="text-sm font-medium text-white">{r.client_name}</p>
                  <p className="text-xs text-slate-400">Locker {r.locker_number} · expires {r.end_date}</p>
                </div>
                <span className={`text-xs font-medium ${r.days_remaining <= 1 ? 'text-red-400' : r.days_remaining <= 3 ? 'text-yellow-400' : 'text-green-400'}`}>
                  {r.days_remaining}d left
                </span>
              </Link>
            ))}
          </div>
        </div>
      </div>
    </div>
  )
}
