import { useEffect, useState } from 'react';
import { App as AntApp, Empty, Form } from 'antd';
import type { PromptTemplate } from '../../api';
import { PromptTemplateAPI } from '../../api';
import PromptLibraryHero from './components/PromptLibraryHero';
import PromptTemplateGrid from './components/PromptTemplateGrid';
import PromptTemplateEditorModal from './components/PromptTemplateEditorModal';

export default function PromptLibraryPage(props: { onSelect?: (tpl: PromptTemplate) => void }) {
  const { onSelect } = props;
  const { message } = AntApp.useApp();
  const [scope, setScope] = useState<'all' | 'mine' | 'public'>('all');
  const [q, setQ] = useState('');
  const [list, setList] = useState<PromptTemplate[]>([]);
  const [loading, setLoading] = useState(false);
  const [editorOpen, setEditorOpen] = useState(false);
  const [editing, setEditing] = useState<PromptTemplate | null>(null);
  const [form] = Form.useForm();

  const load = async () => {
    setLoading(true);
    try {
      const data = await PromptTemplateAPI.list({ scope, q });
      setList(data);
    } catch (e: any) {
      message.error('加载失败：' + (e?.message ?? e));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [scope]);

  const openCreate = () => {
    setEditing(null);
    form.resetFields();
    form.setFieldsValue({ visibility: 'private', category: '通用' });
    setEditorOpen(true);
  };

  const openEdit = (t: PromptTemplate) => {
    setEditing(t);
    form.setFieldsValue({
      title: t.title,
      body: t.body,
      category: t.category,
      visibility: t.visibility
    });
    setEditorOpen(true);
  };

  const onSave = async () => {
    const v = await form.validateFields();
    try {
      if (editing) {
        await PromptTemplateAPI.update(editing.id, v);
        message.success('已更新');
      } else {
        await PromptTemplateAPI.create(v);
        message.success('已创建');
      }
      setEditorOpen(false);
      load();
    } catch (e: any) {
      message.error('保存失败：' + (e?.response?.data?.error ?? e?.message ?? e));
    }
  };

  const onUse = async (t: PromptTemplate) => {
    await PromptTemplateAPI.use(t.id).catch(() => {});
    if (onSelect) onSelect(t);
    else {
      navigator.clipboard?.writeText(t.body).then(() => message.success('内容已复制到剪贴板'));
    }
  };

  const onDelete = async (t: PromptTemplate) => {
    await PromptTemplateAPI.remove(t.id);
    message.success('已删除');
    load();
  };

  const formatDate = (ts: number) =>
    new Date(ts).toLocaleDateString('zh-CN', {
      month: 'numeric',
      day: 'numeric'
    });

  return (
    <div className="feature-cover-container">
      <div className="page-container">
        <PromptLibraryHero scope={scope} q={q} onChangeScope={setScope} onChangeQ={setQ} onSearch={load} onCreate={openCreate} />
        <PromptTemplateGrid
          loading={loading}
          list={list}
          hasOnSelect={!!onSelect}
          onUse={onUse}
          onEdit={openEdit}
          onDelete={onDelete}
          formatDate={formatDate}
        />
        <PromptTemplateEditorModal open={editorOpen} editing={editing} form={form} onCancel={() => setEditorOpen(false)} onOk={onSave} />
      </div>
      <div className="feature-cover">
        <Empty description="功能规划中，本期不支持" />
      </div>
    </div>
  );
}
