"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

type Book = {
  id: number;
  title: string;
  wordCount: number;
  coverUrl: string | null;
  bookId: string;
  tags: string | null;
};

export default function BooksClient({
  books,
  createAction,
  updateAction,
  deleteAction,
}: {
  books: Book[];
  createAction: (formData: FormData) => Promise<void>;
  updateAction: (formData: FormData) => Promise<void>;
  deleteAction: (formData: FormData) => Promise<void>;
}) {
  const [showCreate, setShowCreate] = useState(false);
  const [editing, setEditing] = useState<Book | null>(null);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-semibold">单词书管理</h1>
        <Button onClick={() => setShowCreate(true)}>新建单词书</Button>
      </div>

      <div className="overflow-hidden rounded-md border">
        <div className="grid grid-cols-12 bg-gray-50 p-3 text-sm font-medium text-gray-600">
          <div className="col-span-2">封面</div>
          <div className="col-span-4">标题</div>
          <div className="col-span-2">单词数量</div>
          <div className="col-span-3">bookId</div>
          <div className="col-span-1 text-right pr-2">操作</div>
        </div>
        <div className="divide-y">
          {books.map((b) => (
            <button
              key={b.id}
              className="grid w-full grid-cols-12 items-center gap-2 p-3 text-left hover:bg-gray-50"
              onClick={() => setEditing(b)}
            >
              <div className="col-span-2">
                {b.coverUrl ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img src={b.coverUrl} alt={b.title} className="h-12 w-12 rounded object-cover" />
                ) : (
                  <div className="h-12 w-12 rounded bg-gray-200" />
                )}
              </div>
              <div className="col-span-4 truncate text-sm">{b.title}</div>
              <div className="col-span-2 text-sm">{b.wordCount}</div>
              <div className="col-span-3 truncate text-sm">{b.bookId}</div>
              <div className="col-span-1 text-right text-sm text-blue-600">编辑</div>
            </button>
          ))}
          {books.length === 0 && <div className="p-4 text-sm text-gray-500">暂无单词书</div>}
        </div>
      </div>

      {showCreate && (
        <Modal title="新建单词书" onClose={() => setShowCreate(false)}>
          <form action={createAction} className="space-y-4" onSubmit={() => setShowCreate(false)}>
            <div className="space-y-2">
              <Label htmlFor="title">标题</Label>
              <Input id="title" name="title" required />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="wordCount">单词数量</Label>
                <Input id="wordCount" name="wordCount" type="number" min={0} defaultValue={0} required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="bookId">bookId</Label>
                <Input id="bookId" name="bookId" required />
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="coverUrl">封面 URL</Label>
              <Input id="coverUrl" name="coverUrl" placeholder="https://..." />
            </div>
            <div className="space-y-2">
              <Label htmlFor="tags">标签（逗号分隔）</Label>
              <Input id="tags" name="tags" placeholder="小学,入门,PEP" />
            </div>
            <div className="flex justify-end gap-2">
              <Button type="button" variant="outline" onClick={() => setShowCreate(false)}>
                取消
              </Button>
              <Button type="submit">创建</Button>
            </div>
          </form>
        </Modal>
      )}

      {editing && (
        <Modal title="编辑单词书" onClose={() => setEditing(null)}>
          <div className="space-y-4">
            {/* 删除表单：单独的表单，避免嵌套 */}
            <form
              action={deleteAction}
              onSubmit={(e) => {
                if (!confirm(`确认删除《${editing.title}》？这将同时删除与其 bookId(${editing.bookId}) 关联的所有单词。`)) {
                  e.preventDefault();
                } else {
                  setEditing(null);
                }
              }}
            >
              <input type="hidden" name="id" value={editing.id} />
              <Button type="submit" className="bg-red-600 text-white hover:bg-red-700">删除</Button>
            </form>

            {/* 更新表单 */}
            <form action={updateAction} className="space-y-4" onSubmit={() => setEditing(null)}>
              <input type="hidden" name="id" value={editing.id} />
              <div className="space-y-2">
                <Label>标题</Label>
                <Input name="title" defaultValue={editing.title} required />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>单词数量</Label>
                  <Input name="wordCount" type="number" min={0} defaultValue={editing.wordCount} required />
                </div>
                <div className="space-y-2">
                  <Label>bookId</Label>
                  <Input name="bookId" defaultValue={editing.bookId} required />
                </div>
              </div>
              <div className="space-y-2">
                <Label>封面 URL</Label>
                <Input name="coverUrl" defaultValue={editing.coverUrl ?? ''} />
              </div>
              <div className="space-y-2">
                <Label>标签（逗号分隔）</Label>
                <Input name="tags" defaultValue={editing.tags ?? ''} />
              </div>
              <div className="flex justify-end gap-2">
                <Button type="button" variant="outline" onClick={() => setEditing(null)}>
                  取消
                </Button>
                <Button type="submit">保存</Button>
              </div>
            </form>
          </div>
        </Modal>
      )}
    </div>
  );
}

function Modal({ title, onClose, children }: { title: string; onClose: () => void; children: React.ReactNode }) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      <div className="absolute inset-0 bg-black/30" onClick={onClose} />
      <div className="relative z-10 w-full max-w-lg rounded-lg bg-white p-6 shadow-lg">
        <div className="mb-4 text-lg font-semibold">{title}</div>
        {children}
      </div>
    </div>
  );
}
