import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Link } from '@tanstack/react-router'
import { Plus } from 'lucide-react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { qk } from '@/shared/api/query-keys'
import { useApiError } from '@/shared/lib/use-api-error'
import { Badge } from '@/shared/ui/badge'
import { Button } from '@/shared/ui/button'
import { useCreateDialog } from '@/shared/lib/use-create-dialog'
import { CreateNameDialog } from '@/shared/ui/create-name-dialog'
import { Input } from '@/shared/ui/input'
import { sortRows, useTableSort } from '@/shared/lib/table-sort'
import { SortHeader } from '@/shared/ui/sortable'
import { createGroup, deleteGroup, listGroups } from './api'
import { DurationLabel } from './DurationLabel'
import { GroupSuggestions } from './GroupSuggestions'

export function GroupsPanel() {
  const { t } = useTranslation()
  const queryClient = useQueryClient()
  const create = useCreateDialog()
  const [query, setQuery] = useState('')
  const { sort, toggle } = useTableSort('name', false)

  const { data, isLoading } = useQuery({ queryKey: qk.groups.all, queryFn: listGroups })

  const invalidate = () => queryClient.invalidateQueries({ queryKey: qk.groups.all })
  const onError = useApiError()

  const createMutation = useMutation({
    mutationFn: () => createGroup({ name: create.value.trim() }),
    onSuccess: () => {
      create.close()
      invalidate()
    },
    onError,
  })
  const deleteMutation = useMutation({ mutationFn: deleteGroup, onSuccess: invalidate, onError })

  const term = query.trim().toLowerCase()
  const matched = term
    ? (data ?? []).filter((g) => g.name.toLowerCase().includes(term))
    : (data ?? [])
  const rows = sortRows(matched, sort, {
    name: (g) => g.name.toLowerCase(),
    items: (g) => g.itemCount,
    units: (g) => g.unitCount,
    duration: (g) => g.totalDurationSeconds,
  })

  return (
    <div className="flex flex-col gap-4">
      <div className="flex flex-wrap items-start justify-between gap-2">
        <div className="flex flex-col gap-1">
          <h2 className="crt-glow text-xl font-semibold">{t('admin.groups.title')}</h2>
          <p className="text-sm text-muted-foreground">{t('admin.groups.hint')}</p>
        </div>
        <Button size="sm" onClick={create.show}>
          <Plus className="h-4 w-4" />
          {t('common.create')}
        </Button>
      </div>

      <Input
        className="max-w-xs"
        placeholder={t('common.search')}
        value={query}
        onChange={(e) => setQuery(e.target.value)}
      />

      <GroupSuggestions />

      <div className="crt-panel overflow-x-auto rounded-md">
        <table className="w-full text-sm">
          <thead className="border-b border-border text-left text-muted-foreground">
            <tr>
              <SortHeader
                label={t('admin.groups.name')}
                sortKey="name"
                sort={sort}
                onToggle={toggle}
              />
              <SortHeader
                label={t('admin.groups.items')}
                sortKey="items"
                sort={sort}
                onToggle={toggle}
              />
              <SortHeader
                label={t('admin.groups.units')}
                sortKey="units"
                sort={sort}
                onToggle={toggle}
              />
              <SortHeader
                label={t('admin.groups.duration')}
                sortKey="duration"
                sort={sort}
                onToggle={toggle}
              />
              <th className="px-4 py-2 font-medium">{t('common.actions')}</th>
            </tr>
          </thead>
          <tbody>
            {isLoading && (
              <tr>
                <td className="px-4 py-3 text-muted-foreground" colSpan={5}>
                  {t('common.loading')}
                </td>
              </tr>
            )}
            {rows.map((group) => (
              <tr key={group.id} className="border-b border-border last:border-0">
                <td className="px-4 py-2">
                  <div className="flex items-center gap-2">
                    <Link
                      to="/admin/groups/$groupId"
                      params={{ groupId: group.id }}
                      className="text-primary hover:underline"
                    >
                      {group.name}
                    </Link>
                    {group.mode === 'Dynamic' ? (
                      <Badge>{t('admin.groups.mode.Dynamic')}</Badge>
                    ) : (
                      group.hasFilter && (
                        <Badge variant="muted">{t('admin.groups.hasFilter')}</Badge>
                      )
                    )}
                  </div>
                </td>
                <td className="px-4 py-2 text-muted-foreground">{group.itemCount}</td>
                <td className="px-4 py-2 text-muted-foreground">{group.unitCount}</td>
                <td className="px-4 py-2 text-muted-foreground">
                  <DurationLabel seconds={group.totalDurationSeconds} />
                </td>
                <td className="px-4 py-2">
                  <Button
                    size="sm"
                    variant="destructive"
                    onClick={() => deleteMutation.mutate(group.id)}
                  >
                    {t('common.delete')}
                  </Button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {create.open && (
        <CreateNameDialog
          title={t('admin.groups.createTitle')}
          label={t('admin.groups.name')}
          description={t('admin.groups.hint')}
          value={create.value}
          onChange={create.setValue}
          pending={createMutation.isPending}
          onCreate={() => createMutation.mutate()}
          onClose={create.close}
        />
      )}
    </div>
  )
}
