import React, { useEffect, useState } from 'react';
import { Space, Table, Button, Input, Select, DatePicker, Tabs, message } from 'antd';
import type { TableProps } from 'antd';
import dayjs, { Dayjs } from 'dayjs';
import styles from './index.module.css';
import PunlishPlanModal from './components/publishPlanModal';
const { RangePicker } = DatePicker;
import { useAccountOptions } from '@src/views/publishContent/weGZH/hooks/useAccountOptions';
import { useGzhPlanList, GzhPlanType } from '@src/views/publishContent/weGZH/hooks/useGzhPlanList';
import http from '@src/http';
import { saveGzhPlanApi } from '@src/http/api';
import PunlishPlanDetailModal from './components/PunlishPlanDetailModal';

const TableHeight = window.innerHeight - 380;

const WeGZHContent: React.FC = () => {
	// 状态管理
	const [selectedAccount, setSelectedAccount] = useState<string>();
	const [videoTitle, setVideoTitle] = useState<string>('');
	const [selectedPublisher, setSelectedPublisher] = useState<number>();
	const [dateRange, setDateRange] = useState<[Dayjs | null, Dayjs | null]>();
	const [isShowAddPunlishPlan, setIsShowAddPunlishPlan] = useState<boolean>(false);
	const [actionType, setActionType] = useState<'add' | 'edit'>('add');
	const [editPlanData, setEditPlanData] = useState<GzhPlanType>();
	const [activeKey, setActiveKey] = useState<string>('1');
	const [isSubmiting, setIsSubmiting] = useState<boolean>(false);

	const { accountOptions } = useAccountOptions();
	const { gzhPlanList, getGzhPlanList, totalSize } = useGzhPlanList();

	const [isShowAddPunlishDetailPlan, setIsShowAddPunlishDetailPlan] = useState<boolean>(false);

	// 表格列配置
	const columns: TableProps<GzhPlanType>['columns'] = [
		{
			title: '公众号名称',
			dataIndex: 'accountName',
			key: 'accountName',
			width: 200,
		},
		{
			title: '场景',
			dataIndex: 'scene',
			key: 'scene',
			width: 120,
			render: (_, record) => {
				return record.scene === 0 ? '关注回复' : '自动回复';
			}
		},
		{
			title: '视频数量',
			dataIndex: 'videoCount',
			key: 'videoCount',
			width: 120,
		},
		{
			title: '视频标题',
			dataIndex: 'title',
			key: 'title',
			ellipsis: true,
			render: (_, record) => {
				return record.videoList.map(video => {
					return <div className="text-gray-600 text-sm truncate" key={video.videoId}>{video.title}</div>
				})
			}
		},
		{
			title: '计划创建时间',
			dataIndex: 'createTimestamp',
			key: 'createTimestamp',
			width: 200,
			render: (_, record) => {
				return record.createTimestamp ? dayjs(record.createTimestamp).format('YYYY-MM-DD HH:mm:ss') : '';
			}
		},
		{
			title: '发布方',
			dataIndex: 'publishStage',
			key: 'publishStage',
			width: 120,
			render: (_, record) => {
				return record.publishStage === 0 ? '平台发布' : '用户发布';
			}
		},
		{
			title: '操作',
			key: 'action',
			width: 200,
			render: (_, record) => (
				<Space size="middle">
					<Button type="link" onClick={() => editPlan(record)}>编辑</Button>
					<Button type="link" onClick={() => editPlanDetail(record)}>详情</Button>
				</Space>
			),
		},
	];

	const editPlan = (record: GzhPlanType) => {
		setEditPlanData(record);
		setActionType('edit');
		setIsShowAddPunlishPlan(true);
	};

	const editPlanDetail = (record: GzhPlanType) => {
		setEditPlanData(record);
		setActionType('edit');
		setIsShowAddPunlishDetailPlan(true);
	}

	const addPunlishPlan = () => {
		setActionType('add');
		setEditPlanData(undefined);
		setIsShowAddPunlishPlan(true);
	}

	const handleAddPunlishPlan = async (params: GzhPlanType) => {
		setIsSubmiting(true);
		const res = await http.post<GzhPlanType>(saveGzhPlanApi, params)
			.catch(err => {
				message.error(err.msg);
			})
			.finally(() => {
				setIsSubmiting(false);
			});
		if (res?.code === 0) {
			message.success('发布计划创建成功');
			getGzhPlanList({
				pageNum: 1,
				pageSize: 10,
			});
			setIsShowAddPunlishPlan(false);
		} else {
			message.error(res?.msg);
		}
	}

	useEffect(() => {
		getGzhPlanList({
			pageNum: 1,
			pageSize: 10,
		});
	}, []);

	const handleSearch = () => {
		getGzhPlanList({
			pageNum: 1,
			pageSize: 10,
			title: videoTitle,
			accountId: selectedAccount ? parseInt(selectedAccount) : undefined,
			publishStage: selectedPublisher,
			createTimestampStart: dateRange?.[0]?.unix(),
			createTimestampEnd: dateRange?.[1]?.unix(),
		});
	}

	return (
		<div>
			<div className="rounded-lg">
				<div className="text-lg font-medium mb-3">公众号内容</div>
				
				{/* 搜索区域 */}
				<div className="flex flex-wrap gap-4 mb-3">
					<div className="flex items-center gap-2">
						<span className="text-gray-600">公众号名称:</span>
						<Select
							placeholder="选择公众号"
							style={{ width: 200 }}
							value={selectedAccount}
							onChange={setSelectedAccount}
							allowClear
							options={accountOptions.map(item => ({ label: item.name, value: item.id }))}
						/>
					</div>

					<div className="flex items-center gap-2">
						<span className="text-gray-600">视频标题:</span>
						<Input
							placeholder="搜索视频标题"
							style={{ width: 200 }}
							value={videoTitle}
							allowClear
							onChange={e => setVideoTitle(e.target.value)}
						/>
					</div>

					<div className="flex items-center gap-2">
						<span className="text-gray-600">发布方:</span>
						<Select
							placeholder="选择发布方"
							style={{ width: 200 }}
							value={selectedPublisher}
							onChange={setSelectedPublisher}
							allowClear
							options={[
								{ label: '平台发布', value: 0 },
								{ label: '用户发布', value: 1 },
							]}
						/>
					</div>

					<div className="flex items-center gap-2">
						<RangePicker
							placeholder={['开始时间', '结束时间']}
							style={{ width: 400 }}
							allowClear
							value={dateRange}
							onChange={(dates) => {
								setDateRange(dates || undefined);
							}}
						/>
					</div>

					<Button type="primary" className="ml-2" onClick={ handleSearch}>搜索</Button>
				</div>
				<Tabs
					defaultActiveKey="1"
					type="card"
					size="large"
					className={styles.antTableTab}
					items={[
						{ label: '自动回复', key: '1' },
					]}
					activeKey={activeKey}
					onChange={setActiveKey}
					tabBarExtraContent={
						{ right: <Button type="primary" onClick={addPunlishPlan}>+ 创建发布</Button> }}
				/>
				{/* 表格区域 */}
				<Table
					rowKey={(record) => record.id}
					className={styles.antTable}
					columns={columns}
					dataSource={gzhPlanList}
					scroll={{ x: 'max-content', y: TableHeight }}
					pagination={{
						total: totalSize,
						pageSize: 10,
						showTotal: (total) => `共 ${total} 条`,
					}}
				/>
				<PunlishPlanModal
					visible={isShowAddPunlishPlan}
					onCancel={() => { 
						setEditPlanData(undefined);
						setIsShowAddPunlishPlan(false);
					} }
					onOk={handleAddPunlishPlan}
					actionType={actionType}
					editPlanData={editPlanData}
					isSubmiting={isSubmiting}
				/>
				<PunlishPlanDetailModal
					visible={isShowAddPunlishDetailPlan}
					onCancel={() => { 
						setEditPlanData(undefined);
						setIsShowAddPunlishDetailPlan(false);
					}}
					planData={editPlanData as GzhPlanType}
				/>
			</div>
		</div>
	);
};

export default WeGZHContent;
