import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Button,
  Card,
  message,
  Tag,
  Spin,
  Modal,
  Input,
  Typography,
} from 'antd';
import { PlusOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons';
import {
  fetchCanvases,
  createCanvas,
  deleteCanvas,
  updateCanvas,
} from './canvasApi';
import type { SavedCanvas } from './types';
import IsolatedLivePreview from './IsolatedLivePreview';
import { useTranslation } from 'react-i18next';

const COLS = 48;
const ROW_HEIGHT = 10;
const MARGIN = 8;

/**
 * 将 canvas items + layout 转为绝对定位的 JSX，模拟 GridLayout 效果。
 * 使用内联样式绝对定位，无需 import，LivePreview scope 可直接渲染。
 */
function buildPreviewCode(canvas: SavedCanvas): string {
  const { items, layout } = canvas;
  const itemById = Object.fromEntries(items.map((it) => [it.id, it]));

  // 用 1200px 作为容器宽度来计算列宽
  const containerWidth = 1200;
  const colWidth = (containerWidth - MARGIN * (COLS + 1)) / COLS;

  const children = layout
    .map((l) => {
      const item = itemById[l.i];
      if (!item) return '';
      const x = Math.round(MARGIN + l.x * (colWidth + MARGIN));
      const y = Math.round(MARGIN + l.y * (ROW_HEIGHT + MARGIN));
      const w = Math.round(l.w * colWidth + (l.w - 1) * MARGIN);
      const h = Math.round(l.h * ROW_HEIGHT + (l.h - 1) * MARGIN);
      const code = item.code.trim();
      const isFunction =
        code.startsWith('()') ||
        code.startsWith('(props)') ||
        code.startsWith('function ');
      const embeddedCode = isFunction ? `{(${code})()}` : code;
      return `<div style={{ position: 'absolute', left: ${x}, top: ${y}, width: ${w}, height: ${h}, background: '#fff', overflow: 'hidden' }}>\n  ${embeddedCode}\n</div>`;
    })
    .filter(Boolean);

  const totalH =
    layout.reduce((m, l) => Math.max(m, l.y + l.h), 0) * (ROW_HEIGHT + MARGIN);

  return `<div style={{ position: 'relative', width: ${containerWidth}, height: ${totalH}, background: '#f0f0f0' }}>\n${children.join('\n')}\n</div>`;
}

const CanvasListPage: React.FC = () => {
  const navigate = useNavigate();
  const [canvases, setCanvases] = useState<SavedCanvas[]>([]);
  const [loading, setLoading] = useState(true);
  const { t } = useTranslation();

  console.log('[CanvasListPage] rendered, pathname:', window.location.pathname);

  useEffect(() => {
    fetchCanvases()
      .then(setCanvases)
      .catch(() => message.error(t('canvas.list.loadFailed')))
      .finally(() => setLoading(false));
  }, []);

  const handleCreate = useCallback(async () => {
    try {
      const nextNum =
        Math.max(
          0,
          ...canvases
            .map((p) => {
              const m = p.name.match(/^Canvas\s+(\d+)$/);
              return m ? parseInt(m[1], 10) : 0;
            })
            .filter((n) => n > 0),
        ) + 1;
      const newCanvas = await createCanvas(`Canvas ${nextNum}`);
      navigate(`/admin/canvas/edit/${newCanvas.id}`);
    } catch {
      message.error(t('canvas.list.createFailed'));
    }
  }, [canvases, navigate]);

  const handleDelete = useCallback(async (id: string) => {
    try {
      await deleteCanvas(id);
      setCanvases((prev) => prev.filter((c) => c.id !== id));
      message.success(t('canvas.list.deleted'));
    } catch {
      message.error(t('canvas.list.deleteFailed'));
    }
  }, []);

  // ── 重命名逻辑 ──
  const [renameModal, setRenameModal] = useState<{
    id: string;
    name: string;
    isPublished: boolean;
  } | null>(null);
  const [renameValue, setRenameValue] = useState('');
  const [renameError, setRenameError] = useState('');
  const [renameLoading, setRenameLoading] = useState(false);
  const renameInputRef = useRef<any>(null);

  const openRename = useCallback((canvas: SavedCanvas) => {
    setRenameModal({
      id: canvas.id,
      name: canvas.name,
      isPublished: !!canvas.publishedPageCode,
    });
    setRenameValue(canvas.name);
    setRenameError('');
  }, []);

  const handleRename = useCallback(async () => {
    if (!renameModal) return;
    const trimmed = renameValue.trim();
    if (!trimmed) {
      setRenameError(t('canvas.list.renameEmpty'));
      return;
    }
    if (trimmed === renameModal.name) {
      setRenameModal(null);
      return;
    }
    setRenameLoading(true);
    try {
      await updateCanvas(renameModal.id, { name: trimmed });
      setCanvases((prev) =>
        prev.map((c) =>
          c.id === renameModal.id ? { ...c, name: trimmed } : c,
        ),
      );
      setRenameModal(null);
      message.success(t('canvas.list.renamed'));
      // 如果已发布，清除导航缓存并刷新
      if (renameModal.isPublished) {
        sessionStorage.removeItem('oiterpages');
        sessionStorage.removeItem('oiterprolepages');
        window.location.reload();
      }
    } catch (err: any) {
      if (err?.response?.status === 409 || err?.status === 409) {
        setRenameError(t('canvas.list.renameDuplicate'));
      } else {
        message.error(t('canvas.list.renameFailed'));
      }
    } finally {
      setRenameLoading(false);
    }
  }, [renameModal, renameValue]);

  // ── 删除确认 ──
  const [deleteConfirm, setDeleteConfirm] = useState<SavedCanvas | null>(null);

  if (loading) {
    return (
      <div
        style={{
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          minHeight: 400,
        }}
      >
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div
      style={{
        background: '#f0f2f5',
        minHeight: 'calc(100vh - 64px)',
      }}
    >
      {/* Header */}
      <Card style={{ marginBottom: 16 }}>
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}
        >
          <Typography.Title level={4} style={{ margin: 0 }}>
            {t('canvas.list.title')}
          </Typography.Title>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
            {t('canvas.list.create')}
          </Button>
        </div>
      </Card>

      {/* Grid */}
      <Card>
        {canvases.length > 0 ? (
          <div
            style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(3, 1fr)',
              gap: 20,
            }}
          >
            {canvases.map((canvas) => (
              <div
                key={canvas.id}
                style={{
                  background: '#fff',
                  borderRadius: 8,
                  overflow: 'hidden',
                  border: '1px solid #e5e5e5',
                  cursor: 'pointer',
                  transition: 'box-shadow 0.2s',
                }}
                onMouseEnter={(e) => {
                  (e.currentTarget as HTMLDivElement).style.boxShadow =
                    '0 4px 12px rgba(0,0,0,0.1)';
                }}
                onMouseLeave={(e) => {
                  (e.currentTarget as HTMLDivElement).style.boxShadow = 'none';
                }}
                onClick={() => navigate(`/admin/canvas/edit/${canvas.id}`)}
              >
                {/* Thumbnail */}
                <div
                  style={{
                    height: 180,
                    overflow: 'hidden',
                    background: '#f0f0f0',
                    position: 'relative',
                    pointerEvents: 'none',
                  }}
                >
                  {canvas.items.length > 0 ? (
                    <div
                      style={{
                        transform: 'scale(0.28)',
                        transformOrigin: 'top left',
                        width: 1200,
                        height: 640,
                      }}
                    >
                      <IsolatedLivePreview code={buildPreviewCode(canvas)} />
                    </div>
                  ) : (
                    <div
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        height: '100%',
                        color: '#bbb',
                        fontSize: 14,
                      }}
                    >
                      空画布
                    </div>
                  )}
                </div>

                {/* Info */}
                <div
                  style={{
                    padding: '12px 16px',
                    borderTop: '1px solid #f0f0f0',
                  }}
                >
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                      marginBottom: 8,
                    }}
                  >
                    <span
                      style={{
                        fontWeight: 500,
                        fontSize: 14,
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                        maxWidth: 160,
                      }}
                    >
                      {canvas.name}
                    </span>
                    <Tag color={canvas.publishedPageCode ? 'green' : 'default'}>
                      {canvas.publishedPageCode
                        ? t('canvas.list.published')
                        : t('canvas.list.unpublished')}
                    </Tag>
                  </div>
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                    }}
                  >
                    <span style={{ fontSize: 12, color: '#999' }}>
                      修改于{' '}
                      {new Date(canvas.updatedAt).toLocaleString('zh-CN')}
                    </span>
                    <div style={{ display: 'flex', gap: 4 }}>
                      <Button
                        type="text"
                        size="small"
                        icon={<EditOutlined />}
                        onClick={(e) => {
                          e.stopPropagation();
                          openRename(canvas);
                        }}
                        style={{ fontSize: 12, color: '#666' }}
                      >
                        {t('canvas.list.rename')}
                      </Button>
                      <Button
                        type="text"
                        size="small"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={(e) => {
                          e.stopPropagation();
                          setDeleteConfirm(canvas);
                        }}
                        style={{ fontSize: 12 }}
                      >
                        {t('canvas.list.deleteBtn')}
                      </Button>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div
            style={{ textAlign: 'center', color: '#999', padding: '80px 0' }}
          >
            <p>还没有 Canvas，点击上方按钮新建一个吧</p>
          </div>
        )}
      </Card>

      {/* 重命名 Modal */}
      <Modal
        title={t('canvas.list.renameTitle')}
        open={!!renameModal}
        onOk={handleRename}
        onCancel={() => setRenameModal(null)}
        confirmLoading={renameLoading}
        okText={t('canvas.list.ok')}
        cancelText={t('canvas.list.cancel')}
        afterOpenChange={(open) => {
          if (open) {
            setTimeout(() => renameInputRef.current?.select(), 50);
          }
        }}
      >
        <Input
          ref={renameInputRef}
          value={renameValue}
          onChange={(e) => {
            setRenameValue(e.target.value);
            setRenameError('');
          }}
          onPressEnter={handleRename}
          status={renameError ? 'error' : undefined}
          placeholder={t('canvas.list.renamePlaceholder')}
        />
        {renameModal?.isPublished && (
          <div style={{ color: '#faad14', fontSize: 12, marginTop: 8 }}>
            {t('canvas.list.renamePublishedWarning')}
          </div>
        )}
        {renameError && (
          <div style={{ color: '#ff4d4f', fontSize: 12, marginTop: 4 }}>
            {renameError}
          </div>
        )}
      </Modal>

      {/* 删除确认 Modal */}
      <Modal
        title={t('canvas.list.deleteTitle')}
        open={!!deleteConfirm}
        onOk={() => {
          if (deleteConfirm) {
            handleDelete(deleteConfirm.id);
            setDeleteConfirm(null);
          }
        }}
        onCancel={() => setDeleteConfirm(null)}
        okText={t('canvas.list.deleteBtn')}
        okButtonProps={{ danger: true }}
        cancelText={t('canvas.list.cancel')}
      >
        <p>
          {deleteConfirm?.publishedPageCode
            ? t('canvas.list.deletePublishedConfirm')
            : t('canvas.list.deleteConfirm')}
        </p>
      </Modal>
    </div>
  );
};

export default CanvasListPage;
