import React, { useEffect, useState } from 'react';
import { Button, Card, Form, Input, Space, Switch, Tabs, message } from 'antd';
import { PlusOutlined, SaveOutlined } from '@ant-design/icons';
import {
  getHomeMaterialCategories,
  getHomeMaterialConfig,
  getHomeMaterialWatermarks,
  saveHomeMaterialConfig,
} from '../api';
import type { HomeMaterialCategory, HomeMaterialConfig, HomeMaterialWatermark } from '../types';
import HomeMaterialAssetTable from './homeMaterials/HomeMaterialAssetTable';
import HomeMaterialCategoryPanel from './homeMaterials/HomeMaterialCategoryPanel';
import HomeMaterialUploadModal from './homeMaterials/HomeMaterialUploadModal';
import WatermarkLibraryModal from './homeMaterials/WatermarkLibraryModal';

const AdminHomeMaterials: React.FC = () => {
  const [form] = Form.useForm<HomeMaterialConfig>();
  const [configLoading, setConfigLoading] = useState(false);
  const [categories, setCategories] = useState<HomeMaterialCategory[]>([]);
  const [watermarks, setWatermarks] = useState<HomeMaterialWatermark[]>([]);
  const [uploadOpen, setUploadOpen] = useState(false);
  const [reloadKey, setReloadKey] = useState(0);

  const loadBase = async () => {
    const [catRes, wmRes] = await Promise.all([
      getHomeMaterialCategories({ page: 1, pageSize: 200 }),
      getHomeMaterialWatermarks({ page: 1, pageSize: 200, isActive: true }),
    ]);
    setCategories(catRes.items);
    setWatermarks(wmRes.items);
  };

  const loadConfig = async () => {
    setConfigLoading(true);
    try {
      const cfg = await getHomeMaterialConfig();
      form.setFieldsValue(cfg);
    } finally {
      setConfigLoading(false);
    }
  };

  useEffect(() => {
    loadConfig();
    loadBase();
  }, []);

  const saveConfig = async () => {
    const values = await form.validateFields();
    await saveHomeMaterialConfig(values);
    message.success('配置已保存');
  };

  const refreshAll = async () => {
    await loadBase();
    setReloadKey(k => k + 1);
  };

  return (
    <div>
      <Card style={{ marginBottom: 16 }} loading={configLoading}>
        <Form form={form} layout="inline" initialValues={{ enabled: false, title: '行业素材案例', subtitle: '精选图片与视频素材展示', showOriginalInAdmin: true }}>
          <Form.Item name="enabled" label="首页展示" valuePropName="checked"><Switch /></Form.Item>
          <Form.Item name="title" label="标题" rules={[{ required: true, message: '请输入标题' }]}><Input style={{ width: 220 }} /></Form.Item>
          <Form.Item name="subtitle" label="副标题"><Input style={{ width: 320 }} /></Form.Item>
          <Form.Item name="showOriginalInAdmin" label="后台展示原素材" valuePropName="checked"><Switch /></Form.Item>
          <Form.Item>
            <Button type="primary" icon={<SaveOutlined />} onClick={saveConfig}>保存配置</Button>
          </Form.Item>
        </Form>
      </Card>

      <Card
        title="首页素材行业装修"
        extra={(
          <Space>
            <Button onClick={refreshAll}>刷新</Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => setUploadOpen(true)}>上传素材</Button>
          </Space>
        )}
      >
        <Tabs
          items={[
            {
              key: 'assets',
              label: '素材管理',
              children: <HomeMaterialAssetTable categories={categories} watermarks={watermarks} reloadKey={reloadKey} />,
            },
            {
              key: 'categories',
              label: '行业类别',
              children: <HomeMaterialCategoryPanel onChanged={refreshAll} />,
            },
            {
              key: 'watermarks',
              label: '水印库',
              children: <WatermarkLibraryModal embedded onChanged={refreshAll} />,
            },
          ]}
        />
      </Card>

      <HomeMaterialUploadModal
        open={uploadOpen}
        onClose={() => setUploadOpen(false)}
        categories={categories}
        watermarks={watermarks}
        onSuccess={refreshAll}
      />
    </div>
  );
};

export default AdminHomeMaterials;
