"use client"

import { useState } from "react"
import { usePortalHistoryQuery } from "@/services/portal"
import { format } from "date-fns"
import { de } from "date-fns/locale"
import { useTranslations } from "next-intl"
import { Lock } from "lucide-react"

import type { PortalDistribution } from "@/data/mock/portal"

import { mockPortalHistory } from "@/data/mock/portal"

import { Skeleton } from "@/components/ui/skeleton"
import { PortalFooter } from "@/components/portal/portal-footer"
import { PortalNavbar } from "@/components/portal/portal-navbar"

const ITEMS_PER_PAGE = 8

function TableSkeleton() {
  return (
    <div className="space-y-3">
      {Array.from({ length: 5 }).map((_, i) => (
        <Skeleton key={i} className="h-12 rounded-lg" />
      ))}
    </div>
  )
}

export default function PortalHistoryPage() {
  const t = useTranslations("portal")
  const [monthFilter, setMonthFilter] = useState<string>("all")
  const [page, setPage] = useState(1)

  // React Query hook
  const { data: historyData, isLoading } = usePortalHistoryQuery({
    page: page - 1,
    size: ITEMS_PER_PAGE,
    month: monthFilter === "all" ? undefined : monthFilter,
  })

  // Map API data to local format, fall back to mock
  const allHistory: PortalDistribution[] = historyData
    ? historyData.content.map((entry) => ({
        id: entry.id,
        date: entry.recordedAt,
        strain: entry.strainName,
        amountGrams: entry.amountGrams,
        recordedBy: "Staff",
      }))
    : mockPortalHistory

  // Get unique months from history for filter
  const months = Array.from(
    new Set(
      (historyData ? allHistory : mockPortalHistory).map((d) =>
        format(new Date(d.date), "yyyy-MM")
      )
    )
  ).sort((a, b) => b.localeCompare(a))

  // If using mock data, do client-side filtering/pagination
  const useClientPagination = !historyData

  const filtered: PortalDistribution[] = useClientPagination
    ? monthFilter === "all"
      ? mockPortalHistory
      : mockPortalHistory.filter(
          (d) => format(new Date(d.date), "yyyy-MM") === monthFilter
        )
    : allHistory

  // Paginate (client-side for mock, server-side for real)
  const totalPages = useClientPagination
    ? Math.ceil(filtered.length / ITEMS_PER_PAGE)
    : (historyData?.totalPages ?? 1)

  const paginated = useClientPagination
    ? filtered.slice((page - 1) * ITEMS_PER_PAGE, page * ITEMS_PER_PAGE)
    : filtered

  return (
    <>
      <PortalNavbar />
      <main className="flex-1 w-full">
        <div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8 py-6 space-y-6">
          {/* Header + Filter */}
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <h1 className="text-xl font-bold sm:text-2xl">{t("history")}</h1>
            <select
              value={monthFilter}
              onChange={(e) => {
                setMonthFilter(e.target.value)
                setPage(1)
              }}
              className="h-9 rounded-md border border-input bg-background px-3 text-sm"
              aria-label={t("allMonths")}
            >
              <option value="all">{t("allMonths")}</option>
              {months.map((m) => (
                <option key={m} value={m}>
                  {format(new Date(m + "-01"), "MMMM yyyy", { locale: de })}
                </option>
              ))}
            </select>
          </div>

          {/* Loading state */}
          {isLoading && <TableSkeleton />}

          {/* Desktop Table */}
          {!isLoading && (
            <div className="hidden sm:block rounded-xl border bg-card shadow-sm overflow-hidden">
              <table className="w-full text-sm">
                <thead className="bg-muted/50">
                  <tr>
                    <th className="px-4 py-3 text-left font-medium">
                      {t("date")}
                    </th>
                    <th className="px-4 py-3 text-left font-medium">
                      {t("strain")}
                    </th>
                    <th className="px-4 py-3 text-right font-medium">
                      {t("amount")}
                    </th>
                    <th className="px-4 py-3 text-left font-medium">
                      {t("recordedBy")}
                    </th>
                    <th
                      className="px-4 py-3 text-center font-medium"
                      aria-label="Status"
                    >
                      <Lock className="h-3.5 w-3.5 mx-auto text-muted-foreground" />
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {paginated.map((dist) => (
                    <tr key={dist.id} className="hover:bg-muted/30">
                      <td className="px-4 py-3">
                        {format(new Date(dist.date), "dd.MM.yyyy, HH:mm", {
                          locale: de,
                        })}
                      </td>
                      <td className="px-4 py-3">{dist.strain}</td>
                      <td className="px-4 py-3 text-right font-medium">
                        {dist.amountGrams}
                        {t("grams")}
                      </td>
                      <td className="px-4 py-3 text-muted-foreground">
                        {dist.recordedBy}
                      </td>
                      <td className="px-4 py-3 text-center">
                        <Lock className="h-3.5 w-3.5 mx-auto text-muted-foreground/50" />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          {/* Mobile Card Layout */}
          {!isLoading && (
            <div className="sm:hidden space-y-3">
              {paginated.map((dist) => (
                <div
                  key={dist.id}
                  className="rounded-lg border bg-card p-4 shadow-sm space-y-2"
                >
                  <div className="flex items-center justify-between">
                    <span className="font-medium">{dist.strain}</span>
                    <span className="font-bold text-primary">
                      {dist.amountGrams}
                      {t("grams")}
                    </span>
                  </div>
                  <div className="flex items-center justify-between text-xs text-muted-foreground">
                    <span>
                      {format(new Date(dist.date), "dd.MM.yyyy, HH:mm", {
                        locale: de,
                      })}
                    </span>
                    <div className="flex items-center gap-1">
                      <Lock className="h-3 w-3" />
                      <span>{dist.recordedBy}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Empty state */}
          {!isLoading && filtered.length === 0 && (
            <div className="text-center py-12 text-muted-foreground">
              {t("noHistory")}
            </div>
          )}

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-between text-sm">
              <span className="text-muted-foreground">
                {t("pagination", {
                  from: String((page - 1) * ITEMS_PER_PAGE + 1),
                  to: String(
                    Math.min(
                      page * ITEMS_PER_PAGE,
                      useClientPagination
                        ? filtered.length
                        : (historyData?.totalElements ?? 0)
                    )
                  ),
                  total: String(
                    useClientPagination
                      ? filtered.length
                      : (historyData?.totalElements ?? 0)
                  ),
                })}
              </span>
              <div className="flex gap-2">
                <button
                  onClick={() => setPage((p) => Math.max(1, p - 1))}
                  disabled={page === 1}
                  className="px-3 py-1.5 rounded-md border text-sm disabled:opacity-50 hover:bg-accent transition-colors"
                >
                  {t("previous")}
                </button>
                <button
                  onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                  disabled={page === totalPages}
                  className="px-3 py-1.5 rounded-md border text-sm disabled:opacity-50 hover:bg-accent transition-colors"
                >
                  {t("next")}
                </button>
              </div>
            </div>
          )}
        </div>
      </main>
      <PortalFooter />
    </>
  )
}
