import { useMutation } from '@tanstack/react-query'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import type { ChannelDto } from '@/shared/api/types'
import { Button } from '@/shared/ui/button'
import { Input } from '@/shared/ui/input'
import { Label } from '@/shared/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/shared/ui/select'
import { toast } from '@/shared/ui/toast-store'
import { updateChannelSettings, updateChannelTime } from '../api'
import { CollapsibleCard } from './CollapsibleCard'

export function SettingsCard({
  channel,
  readyAssets,
  bare,
  onSaved,
  onError,
}: Readonly<{
  channel: ChannelDto
  readyAssets: { id: string; originalFileName: string }[]
  bare?: boolean
  onSaved: () => void
  onError: (e: unknown) => void
}>) {
  const { t } = useTranslation()
  const [name, setName] = useState(channel.name)
  const [isEnabled, setIsEnabled] = useState(channel.isEnabled)
  const [fillerAssetId, setFillerAssetId] = useState(channel.fillerAssetId ?? '')
  const [number, setNumber] = useState(channel.number?.toString() ?? '')
  const [offsetHours, setOffsetHours] = useState(channel.utcOffsetMinutes / 60)
  // Начало вещательных суток приходит как «06:00:00» — в поле нужен формат «06:00».
  const [dayStart, setDayStart] = useState(channel.dayStartTime.slice(0, 5))

  useEffect(() => {
    setName(channel.name)
    setIsEnabled(channel.isEnabled)
    setFillerAssetId(channel.fillerAssetId ?? '')
    setNumber(channel.number?.toString() ?? '')
    setOffsetHours(channel.utcOffsetMinutes / 60)
    setDayStart(channel.dayStartTime.slice(0, 5))
  }, [channel])

  const save = useMutation({
    // Время канала живёт отдельной командой — сохраняем обе за одно нажатие.
    mutationFn: async () => {
      await updateChannelSettings(channel.id, {
        name: name.trim(),
        isEnabled,
        fillerAssetId: fillerAssetId || null,
      })
      await updateChannelTime(channel.id, {
        number: number.trim() === '' ? null : Number(number),
        utcOffsetMinutes: Math.round(offsetHours * 60),
        dayStartTime: `${dayStart}:00`,
      })
    },
    onSuccess: () => {
      toast.success(t('settings.saved'))
      onSaved()
    },
    onError,
  })

  return (
    <CollapsibleCard
      title={t('admin.channels.settings')}
      defaultOpen
      bare={bare}
      contentClassName="grid gap-4 sm:grid-cols-2"
    >
      <div className="flex flex-col gap-1.5">
        <Label>{t('admin.channels.name')}</Label>
        <Input value={name} onChange={(e) => setName(e.target.value)} />
      </div>
      <div className="flex flex-col gap-1.5">
        <Label>{t('admin.channels.number')}</Label>
        <Input
          type="number"
          min={1}
          value={number}
          placeholder={t('admin.channels.numberPlaceholder')}
          onChange={(e) => setNumber(e.target.value)}
        />
      </div>
      <div className="flex flex-col gap-1.5">
        <Label>{t('admin.channels.utcOffset')}</Label>
        <Input
          type="number"
          min={-12}
          max={14}
          step={1}
          value={offsetHours}
          onChange={(e) => setOffsetHours(Number(e.target.value))}
        />
        <p className="text-xs text-muted-foreground">{t('admin.channels.utcOffsetHint')}</p>
      </div>
      <div className="flex flex-col gap-1.5">
        <Label>{t('admin.channels.dayStart')}</Label>
        <Input type="time" value={dayStart} onChange={(e) => setDayStart(e.target.value)} />
        <p className="text-xs text-muted-foreground">{t('admin.channels.dayStartHint')}</p>
      </div>
      <div className="flex flex-col gap-1.5">
        <Label>{t('admin.channels.filler')}</Label>
        <Select
          value={fillerAssetId || 'none'}
          onValueChange={(v) => setFillerAssetId(v === 'none' ? '' : v)}
        >
          <SelectTrigger>
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="none">{t('admin.channels.noFiller')}</SelectItem>
            {readyAssets.map((a) => (
              <SelectItem key={a.id} value={a.id}>
                {a.originalFileName}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
      <label className="flex items-center gap-2 text-sm">
        <input
          type="checkbox"
          checked={isEnabled}
          onChange={(e) => setIsEnabled(e.target.checked)}
        />
        {t('admin.channels.enabledLabel')}
      </label>
      <div className="flex items-end justify-end sm:col-span-2">
        <Button size="sm" disabled={save.isPending} onClick={() => save.mutate()}>
          {t('common.save')}
        </Button>
      </div>
    </CollapsibleCard>
  )
}
