'use client';

import { useState, useCallback, useEffect } from 'react';
import { Modal, toast, Button } from '@/components/common';
import { PageContainer } from '@/components/layout';
import { cn } from '@/utils/helpers';
import { formatDateTime } from '@/utils/formatters';
import {
  maintenanceService,
  MaintenanceItem,
  MaintenanceStatusResponse,
} from '@/services/maintenanceService';
import styles from './maintenance.module.scss';

// 快捷时间选项（分钟）
const QUICK_DURATIONS = [
  { label: '5分钟', minutes: 5 },
  { label: '15分钟', minutes: 15 },
  { label: '30分钟', minutes: 30 },
  { label: '1小时', minutes: 60 },
  { label: '2小时', minutes: 120 },
];

// 获取维护状态标签
const getStatusTag = (item: MaintenanceItem) => {
  const now = new Date();
  const startTime = new Date(item.startTime);
  const endTime = new Date(item.endTime);

  if (item.isActive && now >= startTime && now <= endTime) {
    return { label: '维护中', style: 'active' };
  }
  if (now > endTime) {
    return { label: '已过期', style: 'expired' };
  }
  if (item.isActive && now < startTime) {
    return { label: '已计划', style: 'scheduled' };
  }
  if (!item.isActive && now >= startTime && now <= endTime) {
    return { label: '未激活', style: 'inactive' }; // 在时间范围内但未激活
  }
  if (!item.isActive && now < startTime) {
    return { label: '待激活', style: 'scheduled' }; // 未到开始时间且未激活
  }
  return { label: '未激活', style: 'inactive' };
};

// 获取项目样式类名
const getItemClassName = (item: MaintenanceItem) => {
  const now = new Date();
  const endTime = new Date(item.endTime);

  if (item.isActive) {
    return styles['maintenance__item--active'];
  }
  if (now > endTime) {
    return styles['maintenance__item--expired'];
  }
  return '';
};

/**
 * 系统维护管理页面
 */
export default function MaintenancePage() {
  // 数据状态
  const [maintenanceList, setMaintenanceList] = useState<MaintenanceItem[]>([]);
  const [currentStatus, setCurrentStatus] = useState<MaintenanceStatusResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 弹窗状态
  const [showModal, setShowModal] = useState(false);
  const [editingItem, setEditingItem] = useState<MaintenanceItem | null>(null);
  const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);

  // 表单状态
  const [formData, setFormData] = useState({
    title: '',
    message: '',
    startTime: '',
    endTime: '',
  });

  // 加载数据
  const loadData = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      const [listResponse, statusResponse] = await Promise.all([
        maintenanceService.getMaintenanceList(),
        maintenanceService.getCurrentStatus(),
      ]);

      setMaintenanceList(listResponse.items);
      setCurrentStatus(statusResponse);
    } catch (err) {
      setError((err as Error).message || '加载失败');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadData();
  }, [loadData]);

  // 打开创建弹窗
  const handleCreate = () => {
    setEditingItem(null);
    // 默认从现在开始，持续30分钟
    const now = new Date();
    const end = new Date(now.getTime() + 30 * 60 * 1000);

    setFormData({
      title: '系统升级维护',
      message: '尊敬的用户，系统正在进行升级维护，请稍后再试。给您带来的不便，敬请谅解。',
      startTime: formatLocalDateTime(now),
      endTime: formatLocalDateTime(end),
    });
    setShowModal(true);
  };

  // 打开编辑弹窗
  const handleEdit = (item: MaintenanceItem) => {
    setEditingItem(item);
    setFormData({
      title: item.title,
      message: item.message,
      startTime: formatLocalDateTime(new Date(item.startTime)),
      endTime: formatLocalDateTime(new Date(item.endTime)),
    });
    setShowModal(true);
  };

  // 格式化为本地日期时间字符串（用于 datetime-local input）
  const formatLocalDateTime = (date: Date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day}T${hours}:${minutes}`;
  };

  // 快捷设置时间
  const handleQuickDuration = (minutes: number) => {
    const now = new Date();
    const end = new Date(now.getTime() + minutes * 60 * 1000);
    setFormData(prev => ({
      ...prev,
      startTime: formatLocalDateTime(now),
      endTime: formatLocalDateTime(end),
    }));
  };

  // 关闭弹窗
  const handleCloseModal = () => {
    setShowModal(false);
    setEditingItem(null);
  };

  // 提交表单
  const handleSubmit = async () => {
    if (!formData.title.trim()) {
      toast.error('请输入维护标题');
      return;
    }
    if (!formData.message.trim()) {
      toast.error('请输入维护公告内容');
      return;
    }
    if (!formData.startTime) {
      toast.error('请选择开始时间');
      return;
    }
    if (!formData.endTime) {
      toast.error('请选择结束时间');
      return;
    }

    const startTime = new Date(formData.startTime);
    const endTime = new Date(formData.endTime);

    if (endTime <= startTime) {
      toast.error('结束时间必须晚于开始时间');
      return;
    }

    try {
      const payload = {
        title: formData.title.trim(),
        message: formData.message.trim(),
        startTime: startTime.toISOString(),
        endTime: endTime.toISOString(),
      };

      if (editingItem) {
        await maintenanceService.updateMaintenance(editingItem.id, payload);
        toast.success('维护配置已更新');
      } else {
        await maintenanceService.createMaintenance(payload);
        toast.success('维护配置已创建');
      }

      handleCloseModal();
      loadData();
    } catch (err) {
      toast.error((err as Error).message || '操作失败');
    }
  };

  // 切换激活状态
  const handleToggle = async (item: MaintenanceItem) => {
    try {
      await maintenanceService.toggleMaintenance(item.id, !item.isActive);
      toast.success(item.isActive ? '已停止维护' : '已激活维护');
      loadData();
    } catch (err) {
      toast.error((err as Error).message || '操作失败');
    }
  };

  // 删除
  const handleDelete = async (id: string) => {
    try {
      await maintenanceService.deleteMaintenance(id);
      toast.success('维护配置已删除');
      setDeleteConfirm(null);
      loadData();
    } catch (err) {
      toast.error((err as Error).message || '删除失败');
    }
  };

  return (
    <PageContainer title="系统维护">
      <div className={styles.maintenance}>
        {/* 页面标题 */}
        <div className={styles.maintenance__header}>
          <h1 className={styles.maintenance__title}>系统维护管理</h1>
        </div>

        {/* 当前状态卡片 */}
        <div
          className={cn(
            styles.maintenance__statusCard,
            currentStatus?.isUnderMaintenance && styles['maintenance__statusCard--active']
          )}
        >
          <div className={styles.maintenance__statusHeader}>
            <span className={styles.maintenance__statusIcon}>
              {currentStatus?.isUnderMaintenance ? '🔧' : '✅'}
            </span>
            <span className={styles.maintenance__statusTitle}>
              当前系统状态
              <span
                className={cn(
                  styles.maintenance__statusBadge,
                  currentStatus?.isUnderMaintenance
                    ? styles['maintenance__statusBadge--active']
                    : styles['maintenance__statusBadge--inactive']
                )}
              >
                {currentStatus?.isUnderMaintenance ? '维护中' : '正常运行'}
              </span>
            </span>
          </div>
          {currentStatus?.isUnderMaintenance && currentStatus.maintenance && (
            <>
              <div className={styles.maintenance__statusContent}>
                {currentStatus.maintenance.message}
              </div>
              <div className={styles.maintenance__statusTime}>
                预计剩余时间: {currentStatus.maintenance.remainingMinutes} 分钟
                （{formatDateTime(currentStatus.maintenance.endTime)} 结束）
              </div>
            </>
          )}
          {!currentStatus?.isUnderMaintenance && (
            <div className={styles.maintenance__statusContent}>
              移动端 APP 用户可正常访问所有功能。
            </div>
          )}
        </div>

        {/* 维护配置列表 */}
        <div className={styles.maintenance__card}>
          <div className={styles.maintenance__toolbar}>
            <div className={styles.maintenance__actions}>
              <Button variant="outline" size="sm" onClick={loadData}>
                刷新
              </Button>
            </div>
            <Button variant="primary" onClick={handleCreate}>
              + 新建维护计划
            </Button>
          </div>

          <div className={styles.maintenance__list}>
            {loading ? (
              <div className={styles.maintenance__loading}>加载中...</div>
            ) : error ? (
              <div className={styles.maintenance__error}>
                <span>{error}</span>
                <Button variant="outline" size="sm" onClick={loadData}>
                  重试
                </Button>
              </div>
            ) : maintenanceList.length === 0 ? (
              <div className={styles.maintenance__empty}>
                暂无维护计划，点击"新建维护计划"创建
              </div>
            ) : (
              maintenanceList.map((item) => {
                const status = getStatusTag(item);
                return (
                  <div
                    key={item.id}
                    className={cn(styles.maintenance__item, getItemClassName(item))}
                  >
                    <div className={styles.maintenance__itemHeader}>
                      <div className={styles.maintenance__itemMeta}>
                        <span
                          className={cn(
                            styles.maintenance__tag,
                            styles[`maintenance__tag--${status.style}`]
                          )}
                        >
                          {status.label}
                        </span>
                      </div>
                      <div className={styles.maintenance__itemActions}>
                        {status.style !== 'expired' && (
                          <button
                            className={cn(
                              styles.maintenance__actionBtn,
                              item.isActive && styles['maintenance__actionBtn--primary']
                            )}
                            onClick={() => handleToggle(item)}
                          >
                            {item.isActive ? '停止维护' : '立即激活'}
                          </button>
                        )}
                        <button
                          className={styles.maintenance__actionBtn}
                          onClick={() => handleEdit(item)}
                        >
                          编辑
                        </button>
                        <button
                          className={cn(
                            styles.maintenance__actionBtn,
                            styles['maintenance__actionBtn--danger']
                          )}
                          onClick={() => setDeleteConfirm(item.id)}
                        >
                          删除
                        </button>
                      </div>
                    </div>
                    <h3 className={styles.maintenance__itemTitle}>{item.title}</h3>
                    <p className={styles.maintenance__itemContent}>{item.message}</p>
                    <div className={styles.maintenance__itemFooter}>
                      <div className={styles.maintenance__timeRange}>
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                          <circle cx="12" cy="12" r="10" />
                          <polyline points="12 6 12 12 16 14" />
                        </svg>
                        <span>
                          {formatDateTime(item.startTime)} - {formatDateTime(item.endTime)}
                        </span>
                      </div>
                      <span>创建: {formatDateTime(item.createdAt)}</span>
                    </div>
                  </div>
                );
              })
            )}
          </div>
        </div>

        {/* 创建/编辑弹窗 */}
        <Modal
          visible={showModal}
          title={editingItem ? '编辑维护计划' : '新建维护计划'}
          onClose={handleCloseModal}
          footer={
            <div className={styles.maintenance__modalFooter}>
              <Button variant="outline" onClick={handleCloseModal}>
                取消
              </Button>
              <Button variant="primary" onClick={handleSubmit}>
                {editingItem ? '保存' : '创建'}
              </Button>
            </div>
          }
          width={600}
        >
          <div className={styles.maintenance__form}>
            <div className={styles.maintenance__formGroup}>
              <label>维护标题 *</label>
              <input
                type="text"
                value={formData.title}
                onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                placeholder="例如：系统升级维护"
                maxLength={100}
              />
            </div>

            <div className={styles.maintenance__formGroup}>
              <label>公告内容 *</label>
              <textarea
                value={formData.message}
                onChange={(e) => setFormData({ ...formData, message: e.target.value })}
                placeholder="显示给用户的维护公告内容"
                rows={4}
              />
            </div>

            <div className={styles.maintenance__formGroup}>
              <label>快捷设置时长</label>
              <div className={styles.maintenance__quickTimeSelector}>
                {QUICK_DURATIONS.map((d) => (
                  <button
                    key={d.minutes}
                    type="button"
                    className={styles.maintenance__quickTimeBtn}
                    onClick={() => handleQuickDuration(d.minutes)}
                  >
                    {d.label}
                  </button>
                ))}
              </div>
            </div>

            <div className={styles.maintenance__formRow}>
              <div className={styles.maintenance__formGroup}>
                <label>开始时间 *</label>
                <input
                  type="datetime-local"
                  value={formData.startTime}
                  onChange={(e) => setFormData({ ...formData, startTime: e.target.value })}
                />
              </div>

              <div className={styles.maintenance__formGroup}>
                <label>结束时间 *</label>
                <input
                  type="datetime-local"
                  value={formData.endTime}
                  onChange={(e) => setFormData({ ...formData, endTime: e.target.value })}
                />
              </div>
            </div>

            <div className={styles.maintenance__warning}>
              <svg viewBox="0 0 24 24" fill="currentColor">
                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z" />
              </svg>
              <div className={styles.maintenance__warningText}>
                <strong>注意：</strong>激活维护后，移动端 APP 将显示维护公告弹窗，用户将无法进行任何操作。
                请确保在维护完成后及时停止维护或等待自动过期。
              </div>
            </div>
          </div>
        </Modal>

        {/* 删除确认弹窗 */}
        <Modal
          visible={!!deleteConfirm}
          title="确认删除"
          onClose={() => setDeleteConfirm(null)}
          footer={
            <div className={styles.maintenance__modalFooter}>
              <Button variant="outline" onClick={() => setDeleteConfirm(null)}>
                取消
              </Button>
              <Button variant="danger" onClick={() => deleteConfirm && handleDelete(deleteConfirm)}>
                确认删除
              </Button>
            </div>
          }
          width={400}
        >
          <p>确定要删除这个维护计划吗？此操作无法撤销。</p>
        </Modal>
      </div>
    </PageContainer>
  );
}
