import { Button, List, Modal, Space, Tag, Typography } from 'antd';
import { useEffect, useMemo, useState } from 'react';
import { fetchPlanItems } from '../../features/planBoard/api';
import { isReleasePendingMainItem, normalizeWorkerStatus } from '../../features/planBoard/quickFilters';
import type { PlanItem } from '../../features/planBoard/types';

const { Paragraph, Text, Title } = Typography;

const RELEASE_PENDING_MAIN_MODAL_SESSION_KEY = 'work-server.release-pending-main-modal:dismissed';
type PendingMainItem = Pick<PlanItem, 'id' | 'workId' | 'note' | 'status' | 'workerStatus' | 'updatedAt'>;

function isReleaseServer() {
  if (import.meta.env.VITE_RELEASE_SERVER === 'true') {
    return true;
  }

  const explicitStage = (import.meta.env.VITE_DEPLOY_STAGE ?? import.meta.env.VITE_APP_STAGE ?? '').trim().toLowerCase();
  if (explicitStage === 'release') {
    return true;
  }

  if (typeof window === 'undefined') {
    return false;
  }

  return window.location.hostname.toLowerCase().includes('release');
}

function summarizeNote(note: string) {
  const normalized = note.replace(/\s+/g, ' ').trim();

  if (!normalized) {
    return '요약 메모가 없습니다.';
  }

  if (normalized.length <= 72) {
    return normalized;
  }

  return `${normalized.slice(0, 72)}...`;
}

function describePendingReason(item: PendingMainItem) {
  const normalizedWorkerStatus = normalizeWorkerStatus(item.workerStatus);

  if (normalizedWorkerStatus === 'main반영중') {
    return 'release 반영 후 main 병합을 진행 중입니다.';
  }

  if (normalizedWorkerStatus === 'main반영실패') {
    return 'main 반영 단계에서 실패했습니다. 재시도가 필요합니다.';
  }

  if (normalizedWorkerStatus === 'main반영대기') {
    return 'release 반영은 끝났고 main 반영 순서를 기다리는 중입니다.';
  }

  return 'release 반영은 완료됐지만 main에는 아직 적용되지 않았습니다.';
}

function formatUpdatedAt(value: string) {
  return new Date(value).toLocaleString('ko-KR', {
    timeZone: 'Asia/Seoul',
  });
}

export function ReleasePendingMainModal() {
  const [open, setOpen] = useState(false);
  const [items, setItems] = useState<PendingMainItem[]>([]);

  useEffect(() => {
    if (!isReleaseServer() || typeof window === 'undefined') {
      return;
    }

    if (window.sessionStorage.getItem(RELEASE_PENDING_MAIN_MODAL_SESSION_KEY) === 'true') {
      return;
    }

    let cancelled = false;

    void fetchPlanItems('all')
      .then((planItems) => {
        if (cancelled) {
          return;
        }

        const nextItems = planItems
          .filter(isReleasePendingMainItem)
          .sort((left, right) => new Date(right.updatedAt).getTime() - new Date(left.updatedAt).getTime())
          .slice(0, 12)
          .map((item) => ({
            id: item.id,
            workId: item.workId,
            note: item.note,
            status: item.status,
            workerStatus: item.workerStatus,
            updatedAt: item.updatedAt,
          }));

        if (nextItems.length === 0) {
          window.sessionStorage.setItem(RELEASE_PENDING_MAIN_MODAL_SESSION_KEY, 'true');
          return;
        }

        setItems(nextItems);
        setOpen(true);
      })
      .catch(() => {
        // Keep startup resilient even when the plan API is temporarily unavailable.
      });

    return () => {
      cancelled = true;
    };
  }, []);

  const title = useMemo(() => `main 미반영 항목 ${items.length}건`, [items.length]);

  const handleClose = () => {
    if (typeof window !== 'undefined') {
      window.sessionStorage.setItem(RELEASE_PENDING_MAIN_MODAL_SESSION_KEY, 'true');
    }

    setOpen(false);
  };

  return (
    <Modal
      open={open}
      onCancel={handleClose}
      title={title}
      width={720}
      destroyOnClose
      rootClassName="release-pending-main-modal"
      footer={[
        <Button key="confirm" type="primary" onClick={handleClose}>
          확인
        </Button>,
      ]}
    >
      <Space direction="vertical" size={16} className="release-pending-main-modal__body">
        <div>
          <Title level={5} className="release-pending-main-modal__title">
            release 서버 기준으로 main에 아직 반영되지 않은 작업입니다.
          </Title>
          <Paragraph type="secondary" className="release-pending-main-modal__copy">
            최신 반영 순서대로 최대 12건까지 표시합니다.
          </Paragraph>
        </div>
        <List
          dataSource={items}
          className="release-pending-main-modal__list"
          renderItem={(item) => (
            <List.Item className="release-pending-main-modal__item">
              <Space direction="vertical" size={8} className="release-pending-main-modal__item-body">
                <Space size={[8, 8]} wrap>
                  <Text strong>{item.workId.trim() || `#${item.id}`}</Text>
                  <Tag color={item.workerStatus === 'main반영실패' ? 'error' : 'gold'}>
                    {item.workerStatus ?? item.status}
                  </Tag>
                  <Text type="secondary">{formatUpdatedAt(item.updatedAt)}</Text>
                </Space>
                <Text className="release-pending-main-modal__summary">{summarizeNote(item.note)}</Text>
                <Text type="secondary">{describePendingReason(item)}</Text>
              </Space>
            </List.Item>
          )}
        />
      </Space>
    </Modal>
  );
}
