import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Plus } from 'lucide-react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { listChannels } from '@/features/admin/channels/api'
import { qk } from '@/shared/api/query-keys'
import { useApiError } from '@/shared/lib/use-api-error'
import { useCreateDialog } from '@/shared/lib/use-create-dialog'
import { Button } from '@/shared/ui/button'
import { Card, CardContent } from '@/shared/ui/card'
import { CreateNameDialog } from '@/shared/ui/create-name-dialog'
import { Label } from '@/shared/ui/label'
import { createBumperTemplate, listBumperTemplates } from './api'
import { BumperTemplateEditor } from './components/BumperTemplateEditor'

/**
 * Блоки заставок — общие для всех каналов, как группы. Канал выбирается тут же и только для
 * образцов подстановки: посмотреть общий блок надо глазами конкретного канала, иначе
 * `{channel}` не на что заменить.
 */
export function BumpersPanel() {
  const { t } = useTranslation()
  const queryClient = useQueryClient()
  const onError = useApiError()
  const createDialog = useCreateDialog()
  const [channelId, setChannelId] = useState<string>('')

  const { data: templates } = useQuery({
    queryKey: qk.bumpers.all,
    queryFn: listBumperTemplates,
  })
  const { data: channels } = useQuery({ queryKey: qk.channels.all, queryFn: listChannels })

  const invalidate = () => {
    void queryClient.invalidateQueries({ queryKey: qk.bumpers.all })
  }

  const create = useMutation({
    mutationFn: () => createBumperTemplate(createDialog.value.trim()),
    onSuccess: () => {
      createDialog.close()
      invalidate()
    },
    onError,
  })

  return (
    <div className="flex flex-col gap-4">
      <Card>
        <CardContent className="flex flex-col gap-4">
          <p className="text-xs text-muted-foreground">{t('admin.bumpers.hint')}</p>

          <div className="flex flex-wrap items-end gap-3">
            <div className="flex flex-col gap-1.5">
              <Label>{t('admin.bumpers.sampleChannel')}</Label>
              <select
                className="h-9 min-w-56 rounded-md border border-border bg-transparent px-2 text-sm"
                value={channelId}
                onChange={(e) => setChannelId(e.target.value)}
              >
                <option value="">{t('admin.bumpers.sampleChannelNone')}</option>
                {(channels ?? []).map((channel) => (
                  <option key={channel.id} value={channel.id}>
                    {channel.name}
                  </option>
                ))}
              </select>
              <span className="text-xs text-muted-foreground">
                {t('admin.bumpers.sampleChannelHint')}
              </span>
            </div>

            <div className="flex flex-1 items-end justify-end">
              <Button size="sm" onClick={createDialog.show}>
                <Plus className="h-4 w-4" /> {t('common.create')}
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      <div className="flex flex-col gap-3">
        {(templates ?? []).map((template) => (
          <BumperTemplateEditor
            key={template.id}
            template={template}
            channelId={channelId || null}
            onChanged={invalidate}
            onError={onError}
          />
        ))}
        {templates?.length === 0 && (
          <p className="text-sm text-muted-foreground">{t('admin.bumpers.empty')}</p>
        )}
      </div>

      {createDialog.open && (
        <CreateNameDialog
          title={t('admin.bumpers.createTitle')}
          label={t('admin.bumpers.newName')}
          value={createDialog.value}
          onChange={createDialog.setValue}
          pending={create.isPending}
          onCreate={() => create.mutate()}
          onClose={createDialog.close}
        />
      )}
    </div>
  )
}
