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 { Label } from '@/shared/ui/label'
import { createChannel, listChannels } from './api'

function slugify(value: string) {
  return value
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/(^-|-$)/g, '')
}

export function ChannelsPanel() {
  const { t } = useTranslation()
  const queryClient = useQueryClient()
  const create = useCreateDialog()
  const [slug, setSlug] = useState('')

  const { data, isLoading } = useQuery({ queryKey: qk.channels.all, queryFn: listChannels })
  const invalidate = () => queryClient.invalidateQueries({ queryKey: qk.channels.all })
  const onError = useApiError()

  const createMutation = useMutation({
    mutationFn: () =>
      createChannel({
        name: create.value.trim(),
        slug: slug || slugify(create.value),
      }),
    onSuccess: () => {
      setSlug('')
      create.close()
      invalidate()
    },
    onError,
  })

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

      <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>
              <th className="px-4 py-2 font-medium">{t('admin.channels.name')}</th>
              <th className="px-4 py-2 font-medium">{t('admin.channels.slug')}</th>
              <th className="px-4 py-2 font-medium">{t('admin.channels.state')}</th>
            </tr>
          </thead>
          <tbody>
            {isLoading && (
              <tr>
                <td className="px-4 py-3 text-muted-foreground" colSpan={3}>
                  {t('common.loading')}
                </td>
              </tr>
            )}
            {data?.map((channel) => (
              <tr key={channel.id} className="border-b border-border last:border-0">
                <td className="px-4 py-2">
                  <Link
                    to="/admin/channels/$channelId"
                    params={{ channelId: channel.id }}
                    className="text-primary hover:underline"
                  >
                    {channel.name}
                  </Link>
                </td>
                <td className="px-4 py-2 text-muted-foreground">{channel.slug}</td>
                <td className="px-4 py-2">
                  {channel.isEnabled ? (
                    <Badge>{t('admin.channels.enabled')}</Badge>
                  ) : (
                    <Badge variant="muted">{t('admin.channels.disabled')}</Badge>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {create.open && (
        <CreateNameDialog
          title={t('admin.channels.createTitle')}
          label={t('admin.channels.name')}
          value={create.value}
          onChange={create.setValue}
          pending={createMutation.isPending}
          onCreate={() => createMutation.mutate()}
          onClose={create.close}
        >
          <div className="flex flex-col gap-1.5">
            <Label>{t('admin.channels.slug')}</Label>
            {/* Пустой slug выводится из названия — поле нужно только тогда, когда хочется своё. */}
            <Input
              placeholder={slugify(create.value)}
              value={slug}
              onChange={(e) => setSlug(slugify(e.target.value))}
            />
          </div>
        </CreateNameDialog>
      )}
    </div>
  )
}
