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 { addGroupElements, createGroup, listGroups } from '@/features/admin/groups/api'
import { qk } from '@/shared/api/query-keys'
import { useCreateDialog } from '@/shared/lib/use-create-dialog'
import { Button } from '@/shared/ui/button'
import { CreateNameDialog } from '@/shared/ui/create-name-dialog'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/shared/ui/select'
import { cn } from '@/shared/lib/cn'
import { readDragItem } from './dnd'
import { formatClock } from './format'

/**
 * Группы роликов собираются здесь же, а не в общем редакторе групп (см. 6.7): в выбранную группу
 * перетаскиваются и отдельные ролики, и готовые блоки — стык умеет и то и другое.
 */
export function ClipGroupPanel({ onError }: Readonly<{ onError: (error: unknown) => void }>) {
  const { t } = useTranslation()
  const queryClient = useQueryClient()
  const [selected, setSelected] = useState('')
  const create = useCreateDialog()
  const [over, setOver] = useState(false)

  const { data: groups } = useQuery({ queryKey: qk.groups.all, queryFn: listGroups })
  const invalidate = () => {
    void queryClient.invalidateQueries({ queryKey: qk.groups.all })
  }

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

  const addMutation = useMutation({
    mutationFn: (element: { elementKind: 'Show' | 'Collection'; elementId: string }) =>
      addGroupElements(selected, [element]),
    onSuccess: invalidate,
    onError,
  })

  const group = groups?.find((g) => g.id === selected)

  const drop = (event: React.DragEvent) => {
    event.preventDefault()
    setOver(false)
    const item = readDragItem(event)
    if (!item || !selected) return
    addMutation.mutate({
      elementKind: item.kind === 'block' ? 'Collection' : 'Show',
      elementId: item.id,
    })
  }

  return (
    <div className="flex flex-col gap-2">
      <h3 className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
        {t('admin.interstitials.groups')}
      </h3>

      <Select value={selected} onValueChange={setSelected}>
        <SelectTrigger>
          <SelectValue placeholder={t('admin.interstitials.pickGroup')} />
        </SelectTrigger>
        <SelectContent>
          {(groups ?? []).map((g) => (
            <SelectItem key={g.id} value={g.id}>
              {g.name}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      <div
        onDragOver={(e) => {
          e.preventDefault()
          setOver(true)
        }}
        onDragLeave={() => setOver(false)}
        onDrop={drop}
        className={cn(
          'crt-panel flex min-h-20 flex-col items-center justify-center gap-1 rounded-md border border-dashed border-border px-3 py-4 text-center text-xs',
          over && selected && 'border-primary bg-primary/5',
        )}
      >
        {selected ? (
          <>
            <span className="text-muted-foreground">{t('admin.interstitials.dropToGroup')}</span>
            {group && (
              <span className="text-muted-foreground">
                {t('admin.groups.items')}: {group.itemCount} ·{' '}
                {formatClock(group.totalDurationSeconds)}
              </span>
            )}
            {group && (
              <Link
                to="/admin/groups/$groupId"
                params={{ groupId: group.id }}
                className="text-primary hover:underline"
              >
                {t('admin.interstitials.openGroup')}
              </Link>
            )}
          </>
        ) : (
          <span className="text-muted-foreground">{t('admin.interstitials.pickGroupFirst')}</span>
        )}
      </div>

      <Button size="sm" variant="outline" onClick={create.show}>
        <Plus className="h-4 w-4" />
        {t('common.create')}
      </Button>

      {create.open && (
        <CreateNameDialog
          title={t('admin.interstitials.createGroupTitle')}
          label={t('admin.interstitials.newGroupName')}
          value={create.value}
          onChange={create.setValue}
          pending={createMutation.isPending}
          onCreate={() => createMutation.mutate()}
          onClose={create.close}
        />
      )}
    </div>
  )
}
