import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { Plus } from 'lucide-react'
import { toast } from '@/shared/ui/toast-store'
import { Button } from '@/shared/ui/button'
import { Input } from '@/shared/ui/input'
import { Label } from '@/shared/ui/label'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/shared/ui/dialog'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/shared/ui/select'
import { HttpError } from '@/shared/api/client'
import type { AvailableInboundDto } from '@/shared/api/types'
import { createConfig } from './api'

export function CreateConfigDialog({ inbounds }: { inbounds: AvailableInboundDto[] }) {
  const { t } = useTranslation()
  const queryClient = useQueryClient()
  const [open, setOpen] = useState(false)
  const [inboundId, setInboundId] = useState('')
  const [label, setLabel] = useState('')
  const [deviceLimit, setDeviceLimit] = useState('')

  const createMutation = useMutation({
    mutationFn: () => createConfig(inboundId, label.trim() || undefined, deviceLimit ? Number(deviceLimit) : undefined),
    onSuccess: async () => {
      toast.success(t('configs.created'))
      await queryClient.invalidateQueries({ queryKey: ['my-configs'] })
      setOpen(false)
      setInboundId('')
      setLabel('')
      setDeviceLimit('')
    },
    onError: (error) => {
      const message =
        error instanceof HttpError && error.status === 409 ? t('configs.quotaExceeded') : t('auth.genericError')
      toast.error(message)
    },
  })

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button>
          <Plus className="h-4 w-4" />
          {t('configs.create')}
        </Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{t('configs.create')}</DialogTitle>
        </DialogHeader>
        <form
          className="flex flex-col gap-4"
          onSubmit={(e) => {
            e.preventDefault()
            if (inboundId) createMutation.mutate()
          }}
        >
          <div className="flex flex-col gap-1.5">
            <Label>{t('configs.location')}</Label>
            <Select value={inboundId} onValueChange={setInboundId}>
              <SelectTrigger>
                <SelectValue placeholder={t('configs.selectLocation')} />
              </SelectTrigger>
              <SelectContent>
                {inbounds.map((inbound) => (
                  <SelectItem key={inbound.inboundId} value={inbound.inboundId}>
                    {inbound.displayName} ({inbound.protocol})
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="flex flex-col gap-1.5">
            <Label htmlFor="label">{t('configs.label')}</Label>
            <Input id="label" value={label} onChange={(e) => setLabel(e.target.value)} />
          </div>
          <div className="flex flex-col gap-1.5">
            <Label htmlFor="deviceLimit">{t('configs.deviceLimitLabel')}</Label>
            <Input
              id="deviceLimit"
              type="number"
              min={0}
              placeholder={t('configs.deviceLimitPlaceholder')}
              value={deviceLimit}
              onChange={(e) => setDeviceLimit(e.target.value)}
            />
          </div>
          <Button type="submit" disabled={!inboundId || createMutation.isPending}>
            {t('configs.create')}
          </Button>
        </form>
      </DialogContent>
    </Dialog>
  )
}
