import { useId, useState } from 'react'

import { zodResolver } from '@hookform/resolvers/zod'
import { Controller, useForm } from 'react-hook-form'
import { toast } from 'sonner'
import z from 'zod'

import { createSysApi, updateSysApi } from '@/api'
import { Badge } from '@/components/ui/badge.tsx'
import { Button } from '@/components/ui/button.tsx'
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog.tsx'
import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select.tsx'
import { Spinner } from '@/components/ui/spinner.tsx'
import { HttpMethod, HttpMethodClass } from '@/enum'
import { SysApiFormSchema, type SysApi, type SysApiForm } from '@/schemas'

interface Props {
  currentRow?: SysApi | null
  onClose: () => void
  onConfirm: () => void
  open: boolean
}

export function ActionsDialog({ open, currentRow, onClose, onConfirm }: Props) {
  const isEdit = !!currentRow?.id

  const formId = useId()

  const [loading, setLoading] = useState(false)

  const form = useForm<z.infer<typeof SysApiFormSchema>>({
    resolver: zodResolver(SysApiFormSchema),
    defaultValues: currentRow
      ? { ...currentRow }
      : {
          name: '',
          path: '',
          group_name: '',
          method: '' as HttpMethod,
          sort: 0,
        },
  })

  const onSubmit = async (values: SysApiForm) => {
    try {
      setLoading(true)
      if (values.id) {
        await updateSysApi(values.id, values)
      } else {
        await createSysApi(values)
      }
      toast('操作成功！')
      onConfirm()
    } finally {
      setLoading(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent onCloseAutoFocus={() => form.reset()}>
        <DialogHeader>
          <DialogTitle>{isEdit ? '编辑' : '创建'}接口</DialogTitle>
          <DialogDescription />
        </DialogHeader>

        <form id={formId} onSubmit={form.handleSubmit(onSubmit)}>
          <FieldGroup className='gap-4'>
            <Controller
              name='name'
              control={form.control}
              render={({ field, fieldState }) => (
                <Field data-invalid={fieldState.invalid}>
                  <FieldLabel htmlFor='name'>接口名称</FieldLabel>
                  <Input
                    {...field}
                    id='name'
                    aria-invalid={fieldState.invalid}
                    placeholder='请输入接口名称'
                    autoComplete='off'
                  />
                  {fieldState.invalid && <FieldError errors={[fieldState.error]} />}
                </Field>
              )}
            />

            <Controller
              name='group_name'
              control={form.control}
              render={({ field, fieldState }) => (
                <Field data-invalid={fieldState.invalid}>
                  <FieldLabel htmlFor='group_name'>分组名称</FieldLabel>
                  <Input
                    {...field}
                    id='group_name'
                    aria-invalid={fieldState.invalid}
                    placeholder='请输入分组名称'
                    autoComplete='off'
                  />
                  {fieldState.invalid && <FieldError errors={[fieldState.error]} />}
                </Field>
              )}
            />

            <Controller
              name='path'
              control={form.control}
              render={({ field, fieldState }) => (
                <Field data-invalid={fieldState.invalid}>
                  <FieldLabel htmlFor='path'>接口路径</FieldLabel>
                  <Input
                    {...field}
                    id='path'
                    aria-invalid={fieldState.invalid}
                    placeholder='请输入接口路径'
                    autoComplete='off'
                  />
                  {fieldState.invalid && <FieldError errors={[fieldState.error]} />}
                </Field>
              )}
            />

            <Controller
              name='method'
              control={form.control}
              render={({ field, fieldState }) => (
                <Field data-invalid={fieldState.invalid}>
                  <FieldLabel>接口方法</FieldLabel>
                  <Select value={field.value} onValueChange={(value) => field.onChange(value)}>
                    <SelectTrigger className='w-full'>
                      <SelectValue placeholder='请选择接口方法' />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectGroup>
                        {Object.values(HttpMethod).map((option) => (
                          <SelectItem key={option} value={option}>
                            <Badge className={HttpMethodClass[option]}>{option}</Badge>
                          </SelectItem>
                        ))}
                      </SelectGroup>
                    </SelectContent>
                  </Select>
                  {fieldState.invalid && <FieldError errors={[fieldState.error]} />}
                </Field>
              )}
            />

            <Controller
              name='sort'
              control={form.control}
              render={({ field, fieldState }) => (
                <Field data-invalid={fieldState.invalid}>
                  <FieldLabel htmlFor='sort'>排序</FieldLabel>
                  <Input
                    type='number'
                    {...field}
                    id='sort'
                    aria-invalid={fieldState.invalid}
                    placeholder='请输入排序'
                    autoComplete='off'
                  />
                  {fieldState.invalid && <FieldError errors={[fieldState.error]} />}
                </Field>
              )}
            />
          </FieldGroup>
        </form>

        <DialogFooter>
          <DialogClose asChild>
            <Button disabled={loading} variant='outline'>
              取消
            </Button>
          </DialogClose>
          <Button disabled={loading} form={formId} type='submit'>
            保存
            {loading && <Spinner data-icon='inline-start' />}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
