import React, { useState, useCallback, useRef, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { message, Modal, Spin } from 'antd';
import CanvasPageView from './CanvasPage';
import PublishModal from './PublishModal';
import type { SavedCanvas, CanvasItem } from './types';
import type { LayoutItem } from 'react-grid-layout';
import { fetchCanvas, updateCanvas, unpublishCanvas } from './canvasApi';
import { useTranslation } from 'react-i18next';

const CanvasEditPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { t } = useTranslation();
  const [canvas, setCanvas] = useState<SavedCanvas | null>(null);
  const [loading, setLoading] = useState(true);

  const [canvasItems, setCanvasItems] = useState<CanvasItem[]>([]);
  const [canvasLayout, setCanvasLayout] = useState<LayoutItem[]>([]);
  const [isDirty, setIsDirty] = useState(false);
  const [publishModalOpen, setPublishModalOpen] = useState(false);
  const [unpublishModalOpen, setUnpublishModalOpen] = useState(false);
  const [unpublishing, setUnpublishing] = useState(false);

  const liveRef = useRef({
    canvas,
    isDirty,
    canvasItems,
    canvasLayout,
  });
  liveRef.current = {
    canvas,
    isDirty,
    canvasItems,
    canvasLayout,
  };

  // ── Load canvas by ID ──
  useEffect(() => {
    if (!id) return;
    console.log('[CanvasEditPage] loading canvas id:', id);
    setLoading(true);
    fetchCanvas(id)
      .then((data) => {
        console.log('[CanvasEditPage] fetchCanvas result:', data);
        if (!data) {
          message.error('Canvas 不存在');
          navigate('/admin/canvas');
          return;
        }
        setCanvas(data);
        setCanvasItems(data.items ?? []);
        setCanvasLayout(data.layout ?? []);
      })
      .catch((err) => {
        console.error('[CanvasEditPage] load failed:', err);
        message.error('加载 Canvas 失败');
        navigate('/admin/canvas');
      })
      .finally(() => setLoading(false));
  }, [id]); // eslint-disable-line react-hooks/exhaustive-deps

  // ── Change handlers ──
  const handleItemsChange = useCallback((items: CanvasItem[]) => {
    setCanvasItems(items);
    setIsDirty(true);
  }, []);

  const handleLayoutChange = useCallback((layout: LayoutItem[]) => {
    setCanvasLayout(layout);
    setIsDirty(true);
  }, []);

  const handleBothChange = useCallback(
    (items: CanvasItem[], layout: LayoutItem[]) => {
      setCanvasItems(items);
      setCanvasLayout(layout);
      setIsDirty(true);
    },
    [],
  );

  // ── Save ──
  const handleSave = useCallback(async () => {
    const { canvas, canvasItems, canvasLayout } = liveRef.current;
    if (!canvas) return;
    try {
      await updateCanvas(canvas.id, {
        items: canvasItems,
        layout: canvasLayout,
      });
      setIsDirty(false);
      message.success(t('canvas.edit.saved'));
    } catch {
      message.error(t('canvas.edit.saveFailed'));
    }
  }, []);

  // ── 30s 自动保存：有未保存变更时，30 秒后自动调用 handleSave ──
  useEffect(() => {
    if (!isDirty) return;
    const timer = setTimeout(() => {
      handleSave();
    }, 30_000);
    return () => clearTimeout(timer);
  }, [isDirty, handleSave]);

  // ── Back to list ──
  const handleBack = useCallback(() => {
    navigate('/admin/canvas');
  }, [navigate]);

  // ── Unpublish ──
  const handleUnpublish = useCallback(async () => {
    const { canvas } = liveRef.current;
    if (!canvas) return;
    setUnpublishing(true);
    try {
      await unpublishCanvas(canvas.id);
      setCanvas((prev) =>
        prev ? { ...prev, publishedPageCode: null, publishedAt: null } : prev,
      );
      message.success(t('canvas.unpublishSuccess'));
      setUnpublishModalOpen(false);
    } catch {
      message.error(t('canvas.unpublishFailed'));
    } finally {
      setUnpublishing(false);
    }
  }, [t]);

  if (loading || !canvas) {
    console.log(
      '[CanvasEditPage] rendering loading state, loading=',
      loading,
      'canvas=',
      canvas,
    );
    return (
      <div
        style={{
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          minHeight: 400,
        }}
      >
        <Spin size="large" />
      </div>
    );
  }

  console.log('[CanvasEditPage] rendering editor for:', canvas.name);

  return (
    <>
      <CanvasPageView
        items={canvasItems}
        layout={canvasLayout}
        isDirty={isDirty}
        canvasName={canvas.name}
        isPublished={!!canvas.publishedPageCode}
        onItemsChange={handleItemsChange}
        onLayoutChange={handleLayoutChange}
        onBothChange={handleBothChange}
        onSave={handleSave}
        onBack={handleBack}
        onPublish={() => setPublishModalOpen(true)}
        onUnpublish={() => setUnpublishModalOpen(true)}
      />
      <PublishModal
        open={publishModalOpen}
        onClose={() => setPublishModalOpen(false)}
        activeCanvas={canvas}
        onPublishSuccess={() => {
          if (id) {
            fetchCanvas(id)
              .then((data) => {
                if (data) setCanvas(data);
              })
              .catch(() => {});
          }
        }}
      />
      <Modal
        title={t('canvas.unpublish')}
        open={unpublishModalOpen}
        onOk={handleUnpublish}
        onCancel={() => setUnpublishModalOpen(false)}
        okText={t('canvas.unpublish')}
        okButtonProps={{ danger: true }}
        cancelText={t('canvas.publishModal.cancel')}
        confirmLoading={unpublishing}
      >
        <p>{t('canvas.unpublishConfirm')}</p>
      </Modal>
    </>
  );
};

export default CanvasEditPage;
