"use client"

import { useMemo, useState } from "react"
import Link from "next/link"
import { useDistributionsQuery } from "@/services/distributions"
import {
  flexRender,
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table"
import { format, isThisMonth, isThisWeek, isToday } from "date-fns"
import { de } from "date-fns/locale"
import { useTranslations } from "next-intl"
import { Lock, Plus, Search } from "lucide-react"

import type { DistributionRecord } from "@/types/api"
import type { ColumnDef, SortingState } from "@tanstack/react-table"

import { mockDistributions } from "@/data/mock/distributions"

import { useDebounce } from "@/hooks/use-debounce"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { TableSkeleton } from "@/components/ui/data-skeleton"
import { Input } from "@/components/ui/input"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"

type DateFilter = "all" | "today" | "week" | "month"

export default function DistributionsPage() {
  const t = useTranslations("distributions")
  const [sorting, setSorting] = useState<SortingState>([
    { id: "recordedAt", desc: true },
  ])
  const [memberSearch, setMemberSearch] = useState("")
  const [dateFilter, setDateFilter] = useState<DateFilter>("all")

  const debouncedSearch = useDebounce(memberSearch, 300)

  // Build query params based on date filter
  const queryParams = useMemo(() => {
    const params: {
      page?: number
      size?: number
      from?: string
      to?: string
      memberId?: string
    } = {
      size: 50,
    }
    const now = new Date()
    if (dateFilter === "today") {
      params.from = format(now, "yyyy-MM-dd")
      params.to = format(now, "yyyy-MM-dd")
    } else if (dateFilter === "week") {
      const weekStart = new Date(now)
      weekStart.setDate(now.getDate() - now.getDay() + 1) // Monday
      params.from = format(weekStart, "yyyy-MM-dd")
    } else if (dateFilter === "month") {
      const monthStart = new Date(now.getFullYear(), now.getMonth(), 1)
      params.from = format(monthStart, "yyyy-MM-dd")
    }
    return params
  }, [dateFilter])

  const { data, isLoading } = useDistributionsQuery(queryParams)

  // Use API data with mock fallback
  const allDistributions = data?.content ?? mockDistributions

  // Client-side date filter (in case API doesn't support these params yet)
  const filteredByDate = useMemo(() => {
    if (dateFilter === "today") {
      return allDistributions.filter((d) => isToday(new Date(d.recordedAt)))
    } else if (dateFilter === "week") {
      return allDistributions.filter((d) =>
        isThisWeek(new Date(d.recordedAt), { weekStartsOn: 1 })
      )
    } else if (dateFilter === "month") {
      return allDistributions.filter((d) => isThisMonth(new Date(d.recordedAt)))
    }
    return allDistributions
  }, [allDistributions, dateFilter])

  // Client-side member search filter
  const filteredData = useMemo(() => {
    if (!debouncedSearch) return filteredByDate
    const search = debouncedSearch.toLowerCase()
    return filteredByDate.filter((d) =>
      d.memberName.toLowerCase().includes(search)
    )
  }, [filteredByDate, debouncedSearch])

  const todayDistributions = useMemo(
    () => allDistributions.filter((d) => isToday(new Date(d.recordedAt))),
    [allDistributions]
  )
  const todayGrams = useMemo(
    () => todayDistributions.reduce((sum, d) => sum + d.amountGrams, 0),
    [todayDistributions]
  )

  const columns: ColumnDef<DistributionRecord>[] = useMemo(
    () => [
      {
        accessorKey: "recordedAt",
        header: t("dateTime"),
        cell: ({ row }) =>
          format(new Date(row.original.recordedAt), "dd.MM.yyyy HH:mm", {
            locale: de,
          }),
      },
      {
        accessorKey: "memberName",
        header: t("member"),
        cell: ({ row }) => (
          <span className="font-medium">{row.original.memberName}</span>
        ),
      },
      {
        accessorKey: "strainName",
        header: t("strain"),
        cell: ({ row }) => (
          <Badge variant="outline">{row.original.strainName}</Badge>
        ),
      },
      {
        accessorKey: "amountGrams",
        header: t("amount"),
        cell: ({ row }) => (
          <span className="font-mono">{row.original.amountGrams}g</span>
        ),
      },
      {
        accessorKey: "recordedBy",
        header: t("staff"),
        cell: ({ row }) => (
          <span className="text-muted-foreground">
            {row.original.recordedBy}
          </span>
        ),
      },
      {
        accessorKey: "status",
        header: t("status"),
        cell: () => (
          <div className="flex items-center gap-1.5">
            <Lock className="text-muted-foreground h-3.5 w-3.5" />
            <span className="text-muted-foreground text-xs">
              {t("completed")}
            </span>
          </div>
        ),
      },
    ],
    [t]
  )

  const table = useReactTable({
    data: filteredData,
    columns,
    state: { sorting },
    onSortingChange: setSorting,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    initialState: {
      pagination: { pageSize: 10 },
    },
  })

  return (
    <div className="space-y-6 p-4 md:p-6">
      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">{t("title")}</h1>
          <p className="text-muted-foreground text-sm">
            {t("todaySummary", {
              count: todayDistributions.length,
              grams: todayGrams,
            })}
          </p>
        </div>
        <Link href="/distributions/new">
          <Button className="gap-2">
            <Plus className="h-4 w-4" />
            {t("newDistribution")}
          </Button>
        </Link>
      </div>

      {/* Filters */}
      <Card>
        <CardContent className="p-4">
          <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
            {/* Search */}
            <div className="relative flex-1">
              <Search className="text-muted-foreground absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2" />
              <Input
                placeholder={t("searchMember")}
                value={memberSearch}
                onChange={(e) => setMemberSearch(e.target.value)}
                className="pl-9"
              />
            </div>

            {/* Date filter buttons */}
            <div className="flex gap-2">
              {(
                [
                  { key: "all", label: "Alle" },
                  { key: "today", label: t("filterToday") },
                  { key: "week", label: t("filterWeek") },
                  { key: "month", label: t("filterMonth") },
                ] as const
              ).map(({ key, label }) => (
                <Button
                  key={key}
                  variant={dateFilter === key ? "default" : "outline"}
                  size="sm"
                  onClick={() => setDateFilter(key)}
                >
                  {label}
                </Button>
              ))}
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Table or loading skeleton */}
      {isLoading ? (
        <TableSkeleton rows={8} columns={6} />
      ) : (
        <Card>
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                {table.getHeaderGroups().map((headerGroup) => (
                  <TableRow key={headerGroup.id}>
                    {headerGroup.headers.map((header) => (
                      <TableHead
                        key={header.id}
                        className="hidden sm:table-cell first:table-cell [&:nth-child(2)]:table-cell [&:nth-child(3)]:table-cell [&:nth-child(4)]:table-cell"
                      >
                        {header.isPlaceholder
                          ? null
                          : flexRender(
                              header.column.columnDef.header,
                              header.getContext()
                            )}
                      </TableHead>
                    ))}
                  </TableRow>
                ))}
              </TableHeader>
              <TableBody>
                {table.getRowModel().rows.length ? (
                  table.getRowModel().rows.map((row) => (
                    <TableRow key={row.id}>
                      {row.getVisibleCells().map((cell) => (
                        <TableCell
                          key={cell.id}
                          className="hidden sm:table-cell first:table-cell [&:nth-child(2)]:table-cell [&:nth-child(3)]:table-cell [&:nth-child(4)]:table-cell"
                        >
                          {flexRender(
                            cell.column.columnDef.cell,
                            cell.getContext()
                          )}
                        </TableCell>
                      ))}
                    </TableRow>
                  ))
                ) : (
                  <TableRow>
                    <TableCell
                      colSpan={columns.length}
                      className="h-24 text-center"
                    >
                      Keine Ausgaben gefunden.
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {/* Pagination */}
      {!isLoading && (
        <div className="flex items-center justify-between">
          <p className="text-muted-foreground text-sm">
            {table.getFilteredRowModel().rows.length} Einträge
          </p>
          <div className="flex gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => table.previousPage()}
              disabled={!table.getCanPreviousPage()}
            >
              Zurück
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => table.nextPage()}
              disabled={!table.getCanNextPage()}
            >
              Weiter
            </Button>
          </div>
        </div>
      )}
    </div>
  )
}
