import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { Spin } from 'antd';
import { GridLayout, useContainerWidth } from 'react-grid-layout';
import type { LayoutItem } from 'react-grid-layout';
import CanvasCell from '../canvas/CanvasCell';
import type { CanvasItem } from '../canvas/types';
import { customRequest } from 'helpers/http';
import 'react-grid-layout/css/styles.css';
import 'react-resizable/css/styles.css';

const COLS = 48;
const ROW_HEIGHT = 10;

interface CanvasData {
  items: CanvasItem[];
  layout: LayoutItem[];
  name: string;
}

export default function CanvasViewPage() {
  const { slug } = useParams<{ slug: string }>();
  const [data, setData] = useState<CanvasData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { width: containerWidth, containerRef, mounted } = useContainerWidth();

  useEffect(() => {
    if (!slug) return;
    setLoading(true);
    customRequest<CanvasData>(`canvas/by-page-code/${slug}`, 'GET')
      .then((d) => {
        setData(d);
        setError(null);
      })
      .catch((e) => setError(e?.message ?? String(e)))
      .finally(() => setLoading(false));
  }, [slug]);

  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      <div
        ref={containerRef as React.RefObject<HTMLDivElement>}
        style={{
          flex: 1,
          overflow: 'visible',
          position: 'relative',
          background: '#f0f2f5',
        }}
      >
        {loading ? (
          <div
            style={{
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              minHeight: 400,
            }}
          >
            <Spin size="large" />
          </div>
        ) : error || !data ? (
          <div style={{ textAlign: 'center', padding: 60, color: '#999' }}>
            {error || 'Page not found'}
          </div>
        ) : (
          mounted && (
            <div style={{ maxWidth: 1600, margin: '0 auto', width: '100%' }}>
              <GridLayout
                className="layout"
                layout={data.layout}
                width={Math.min(containerWidth, 1600)}
                gridConfig={{
                  cols: COLS,
                  rowHeight: ROW_HEIGHT,
                  margin: [8, 8],
                }}
                dragConfig={{ enabled: false }}
                resizeConfig={{ enabled: false }}
              >
                {data.items.map((item) => (
                  <CanvasCell
                    key={item.id}
                    code={item.code}
                    componentType={item.componentType}
                    selected={false}
                    isPreview={true}
                    onClick={() => {}}
                    onDoubleClick={() => {}}
                    onContextMenu={() => {}}
                  />
                ))}
              </GridLayout>
            </div>
          )
        )}
      </div>
    </div>
  );
}
