import { useState, useEffect } from 'react';
import { Modal, Button, Input, Form, toast } 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 [category, setCategory] = useState('');
  const [loading, setLoading] = useState(false);
  const { mutate } = useSWRConfig();

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!resource) return;
    setLoading(true);
    try {
      await api.resources({ id: resource.id }).put({
        title,
        description,
        url,
        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 {
      await api.resources({ id: 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">
                <Input
                  isRequired
                  label="标题"
                  placeholder="资源名称"
                  value={title}
                  onValueChange={setTitle}
                />
                <Input
                  label="描述"
                  placeholder="简短描述"
                  value={description}
                  onValueChange={setDescription}
                />
                <Input
                  isRequired
                  label="链接"
                  placeholder="https://..."
                  value={url}
                  onValueChange={setUrl}
                />
                <Input
                  label="分类"
                  placeholder="如: 工具, 文档"
                  value={category}
                  onValueChange={setCategory}
                />
                <div className="flex justify-between gap-2 mt-4">
                  <Button color="danger" variant="flat" onPress={handleDelete} isLoading={loading}>
                    删除资源
                  </Button>
                  <div className="flex gap-2">
                    <Button color="danger" variant="ghost" onPress={() => onOpenChange(false)}>
                      取消
                    </Button>
                    <Button color="primary" type="submit" isLoading={loading}>
                      保存
                    </Button>
                  </div>
                </div>
              </Form>
            </Modal.Body>
        </Modal.Dialog>
      </Modal.Container>
    </Modal>
  );
}
