import { useState, useEffect } from 'react'
import {
  Modal,
  Button,
  Input,
  Form,
  toast,
  TextField,
  Label,
  FieldError,
} from '@heroui/react'
import { api } from '../api/client'
import { useSWRConfig } from 'swr'
import { Resource } from '../hooks/useApi'

export function EditResourceModal({
  isOpen,
  onOpenChange,
  resource,
}: {
  isOpen: boolean
  onOpenChange: (isOpen: boolean) => void
  resource: Resource | null
}) {
  const [title, setTitle] = useState('')
  const [description, setDescription] = useState('')
  const [url, setUrl] = useState('')
  const [icon, setIcon] = useState('')
  const [category, setCategory] = useState('')
  const [loading, setLoading] = useState(false)
  const { mutate } = useSWRConfig()

  useEffect(() => {
    if (resource) {
      setTitle(resource.title)
      setDescription(resource.description || '')
      setUrl(resource.url)
      setIcon(resource.icon || '')
      setCategory(resource.category || '')
    }
  }, [resource])

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    if (!resource) return
    setLoading(true)
    try {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      await (api.resources as any)[resource.id].put({
        title,
        description,
        url,
        icon,
        category,
      })
      mutate('/resources')
      onOpenChange(false)
    } catch (err) {
      console.error(err)
      toast.danger('更新失败')
    } finally {
      setLoading(false)
    }
  }

  const handleDelete = async () => {
    if (!resource || !confirm('确定要删除这个资源吗？')) return
    setLoading(true)
    try {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      await (api.resources as any)[resource.id].delete()
      mutate('/resources')
      onOpenChange(false)
    } catch (err) {
      console.error(err)
      toast.danger('删除失败')
    } finally {
      setLoading(false)
    }
  }

  return (
    <Modal isOpen={isOpen} onOpenChange={onOpenChange}>
      <Modal.Backdrop>
        <Modal.Container>
          <Modal.Dialog>
            <Modal.Header>
              <Modal.Heading>编辑资源</Modal.Heading>
              <Modal.CloseTrigger />
            </Modal.Header>
            <Modal.Body>
              <Form
                validationBehavior="native"
                onSubmit={handleSubmit}
                className="flex flex-col gap-4"
              >
                <TextField
                  isRequired
                  name="title"
                  value={title}
                  onChange={setTitle}
                >
                  <Label>标题</Label>
                  <Input placeholder="资源名称" variant="secondary" />
                  <FieldError />
                </TextField>

                <TextField
                  name="description"
                  value={description}
                  onChange={setDescription}
                >
                  <Label>描述</Label>
                  <Input placeholder="简短描述" variant="secondary" />
                  <FieldError />
                </TextField>

                <TextField isRequired name="url" value={url} onChange={setUrl}>
                  <Label>链接</Label>
                  <Input placeholder="https://..." variant="secondary" />
                  <FieldError />
                </TextField>

                <TextField name="icon" value={icon} onChange={setIcon}>
                  <Label>图标 URL</Label>
                  <Input placeholder="如: /icon/hlae.png" variant="secondary" />
                  <FieldError />
                </TextField>

                <TextField
                  name="category"
                  value={category}
                  onChange={setCategory}
                >
                  <Label>版本/分类</Label>
                  <Input placeholder="如: v2.189.6" variant="secondary" />
                  <FieldError />
                </TextField>

                <div className="mt-4 flex justify-between gap-2">
                  <Button
                    variant="danger"
                    onPress={handleDelete}
                    isPending={loading}
                  >
                    删除资源
                  </Button>
                  <div className="flex gap-2">
                    <Button variant="ghost" onPress={() => onOpenChange(false)}>
                      取消
                    </Button>
                    <Button type="submit" isPending={loading}>
                      保存
                    </Button>
                  </div>
                </div>
              </Form>
            </Modal.Body>
          </Modal.Dialog>
        </Modal.Container>
      </Modal.Backdrop>
    </Modal>
  )
}
