"use client"

import { useMemo, useState } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { useMembersQuery } from "@/services/members"
import {
  flexRender,
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table"
import { useTranslations } from "next-intl"
import { ArrowUpDown, Plus, Search } from "lucide-react"

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

import { mockMembers } from "@/data/mock/members"

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

function StatusBadge({
  status,
  t,
}: {
  status: Member["status"]
  t: ReturnType<typeof useTranslations>
}) {
  const variants: Record<Member["status"], string> = {
    ACTIVE:
      "bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400",
    SUSPENDED:
      "bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400",
    EXPELLED: "bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400",
  }

  const labels: Record<Member["status"], string> = {
    ACTIVE: t("active"),
    SUSPENDED: t("suspended"),
    EXPELLED: t("expelled"),
  }

  return (
    <span
      className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${variants[status]}`}
    >
      {labels[status]}
    </span>
  )
}

function QuotaBar({ percent }: { percent: number }) {
  const color =
    percent >= 90
      ? "bg-red-500"
      : percent >= 70
        ? "bg-amber-500"
        : "bg-green-500"

  return (
    <div className="flex items-center gap-2">
      <div className="bg-muted h-2 w-16 rounded-full">
        <div
          className={`h-2 rounded-full ${color}`}
          style={{ width: `${Math.min(percent, 100)}%` }}
        />
      </div>
      <span className="text-muted-foreground text-xs">{percent}%</span>
    </div>
  )
}

export default function MembersPage() {
  const t = useTranslations("members")
  const router = useRouter()
  const [sorting, setSorting] = useState<SortingState>([])
  const [globalFilter, setGlobalFilter] = useState("")
  const [pageSize, setPageSize] = useState(10)

  // Debounce search for API calls (300ms)
  const debouncedSearch = useDebounce(globalFilter, 300)

  // Query backend with debounced search
  const { data: membersData, isLoading } = useMembersQuery({
    search: debouncedSearch || undefined,
    size: pageSize,
  })

  // Fallback to mock data when backend is unavailable
  const members: Member[] = membersData?.content ?? mockMembers

  const columns = useMemo<ColumnDef<Member>[]>(
    () => [
      {
        accessorFn: (row) => `${row.firstName} ${row.lastName}`,
        id: "name",
        header: ({ column }) => (
          <Button
            variant="ghost"
            className="-ml-4"
            onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
          >
            {t("name")}
            <ArrowUpDown className="ml-2 h-4 w-4" />
          </Button>
        ),
        cell: ({ row }) => (
          <div>
            <div className="font-medium">
              {row.original.firstName} {row.original.lastName}
            </div>
            <div className="text-muted-foreground text-sm md:hidden">
              {row.original.email}
            </div>
          </div>
        ),
      },
      {
        accessorKey: "email",
        header: ({ column }) => (
          <Button
            variant="ghost"
            className="-ml-4"
            onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
          >
            {t("email")}
            <ArrowUpDown className="ml-2 h-4 w-4" />
          </Button>
        ),
        cell: ({ getValue }) => (
          <span className="text-muted-foreground">{getValue() as string}</span>
        ),
      },
      {
        accessorKey: "status",
        header: t("status"),
        cell: ({ getValue }) => (
          <StatusBadge status={getValue() as Member["status"]} t={t} />
        ),
      },
      {
        accessorKey: "joinedAt",
        header: ({ column }) => (
          <Button
            variant="ghost"
            className="-ml-4"
            onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
          >
            {t("memberSince")}
            <ArrowUpDown className="ml-2 h-4 w-4" />
          </Button>
        ),
        cell: ({ getValue }) => {
          const date = new Date(getValue() as string)
          return date.toLocaleDateString("de-DE", {
            day: "2-digit",
            month: "2-digit",
            year: "numeric",
          })
        },
      },
      {
        accessorKey: "monthlyQuotaUsedPercent",
        header: t("quota"),
        cell: ({ getValue }) => <QuotaBar percent={getValue() as number} />,
      },
      {
        id: "actions",
        header: t("actions"),
        cell: ({ row }) => (
          <Button
            variant="outline"
            size="sm"
            onClick={() => router.push(`/members/${row.original.id}`)}
          >
            {t("edit")}
          </Button>
        ),
      },
    ],
    [t, router]
  )

  const table = useReactTable({
    data: members,
    columns,
    state: {
      sorting,
      globalFilter,
      pagination: { pageIndex: 0, pageSize },
    },
    onSortingChange: setSorting,
    onGlobalFilterChange: setGlobalFilter,
    getCoreRowModel: getCoreRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    globalFilterFn: (row, _columnId, filterValue) => {
      const search = filterValue.toLowerCase()
      const name =
        `${row.original.firstName} ${row.original.lastName}`.toLowerCase()
      const email = row.original.email.toLowerCase()
      return name.includes(search) || email.includes(search)
    },
  })

  return (
    <div className="flex flex-col gap-6 p-4 md:p-6">
      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <h1 className="text-2xl font-bold tracking-tight">{t("title")}</h1>
        <Link href="/members/new">
          <Button>
            <Plus className="mr-2 h-4 w-4" />
            {t("addMember")}
          </Button>
        </Link>
      </div>

      {/* Search + Filter */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center">
        <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("search")}
            value={globalFilter}
            onChange={(e) => setGlobalFilter(e.target.value)}
            className="pl-9"
          />
        </div>
        <div className="flex items-center gap-2">
          <span className="text-muted-foreground text-sm">{t("perPage")}</span>
          <Select
            value={String(pageSize)}
            onChange={(e) => setPageSize(Number(e.target.value))}
            className="w-20"
          >
            <option value="10">10</option>
            <option value="20">20</option>
            <option value="50">50</option>
          </Select>
        </div>
      </div>

      {/* Loading state */}
      {isLoading ? (
        <TableSkeleton rows={pageSize} columns={6} />
      ) : (
        <>
          {/* Desktop table */}
          <div className="hidden md:block">
            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  {table.getHeaderGroups().map((headerGroup) => (
                    <TableRow key={headerGroup.id}>
                      {headerGroup.headers.map((header) => (
                        <TableHead key={header.id}>
                          {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}>
                            {flexRender(
                              cell.column.columnDef.cell,
                              cell.getContext()
                            )}
                          </TableCell>
                        ))}
                      </TableRow>
                    ))
                  ) : (
                    <TableRow>
                      <TableCell
                        colSpan={columns.length}
                        className="h-24 text-center"
                      >
                        {t("noResults")}
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </div>
          </div>

          {/* Mobile card layout */}
          <div className="flex flex-col gap-3 md:hidden">
            {table.getRowModel().rows.length ? (
              table.getRowModel().rows.map((row) => (
                <div
                  key={row.id}
                  className="bg-card rounded-lg border p-4 shadow-sm"
                  onClick={() => router.push(`/members/${row.original.id}`)}
                  role="button"
                  tabIndex={0}
                  onKeyDown={(e) => {
                    if (e.key === "Enter" || e.key === " ") {
                      router.push(`/members/${row.original.id}`)
                    }
                  }}
                >
                  <div className="flex items-start justify-between">
                    <div>
                      <p className="font-medium">
                        {row.original.firstName} {row.original.lastName}
                      </p>
                      <p className="text-muted-foreground text-sm">
                        {row.original.email}
                      </p>
                    </div>
                    <StatusBadge status={row.original.status} t={t} />
                  </div>
                  <div className="mt-3 flex items-center justify-between">
                    <span className="text-muted-foreground text-xs">
                      {t("memberSince")}:{" "}
                      {new Date(row.original.joinedAt).toLocaleDateString(
                        "de-DE"
                      )}
                    </span>
                    <QuotaBar percent={row.original.monthlyQuotaUsedPercent} />
                  </div>
                </div>
              ))
            ) : (
              <p className="text-muted-foreground py-8 text-center">
                {t("noResults")}
              </p>
            )}
          </div>

          {/* Pagination */}
          <div className="flex items-center justify-between">
            <p className="text-muted-foreground text-sm">
              {t("showing", {
                from:
                  table.getState().pagination.pageIndex *
                    table.getState().pagination.pageSize +
                  1,
                to: Math.min(
                  (table.getState().pagination.pageIndex + 1) *
                    table.getState().pagination.pageSize,
                  table.getFilteredRowModel().rows.length
                ),
                total: table.getFilteredRowModel().rows.length,
              })}
            </p>
            <div className="flex gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => table.previousPage()}
                disabled={!table.getCanPreviousPage()}
              >
                {t("previous")}
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => table.nextPage()}
                disabled={!table.getCanNextPage()}
              >
                {t("next")}
              </Button>
            </div>
          </div>
        </>
      )}
    </div>
  )
}
