import React, { useCallback } from 'react';
import { Button, Tooltip, Popover } from 'antd';
import {
  SaveOutlined,
  ArrowLeftOutlined,
  RocketOutlined,
  AppstoreOutlined,
  EyeOutlined,
} from '@ant-design/icons';
import ComponentThumbnail from './ComponentThumbnail';
import { CANVAS_COMPONENTS, CANVAS_DEFAULTS } from './canvasDefaults';
import { useTranslation } from 'react-i18next';
import { getComponentLabel, getVariantLabel } from './canvasI18n';

interface CanvasToolbarProps {
  isDirty: boolean;
  canvasName: string;
  isPublished: boolean;
  onSave: () => void;
  onBack: () => void;
  onPublish: () => void;
  onUnpublish: () => void;
  onPreview: () => void;
}

const CanvasToolbar: React.FC<CanvasToolbarProps> = ({
  isDirty,
  canvasName,
  isPublished,
  onSave,
  onBack,
  onPublish,
  onUnpublish,
  onPreview,
}) => {
  const { t } = useTranslation();

  const handleVariantDragStart = useCallback(
    (e: React.DragEvent, componentType: string, variantCode: string) => {
      e.dataTransfer.setData('componentType', componentType);
      e.dataTransfer.setData('variantCode', variantCode);
      e.dataTransfer.setData(
        `x-component-type/${componentType.toLowerCase()}`,
        '',
      );
      e.dataTransfer.effectAllowed = 'copy';
    },
    [],
  );

  return (
    <div
      style={{
        background: '#fff',
        borderBottom: '1px solid #eaeaea',
        flexShrink: 0,
        boxShadow: '0 1px 8px rgba(0,0,0,0.04)',
        borderRadius: 8,
        overflow: 'hidden',
      }}
    >
      {/* ── Header row ── */}
      <div
        style={{
          height: 52,
          padding: '0 24px',
          display: 'flex',
          alignItems: 'center',
        }}
      >
        {/* 左侧: 返回 + 名称 */}
        <div
          style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 14 }}
        >
          <Tooltip title={t('canvas.backToList')}>
            <Button
              size="small"
              type="text"
              icon={<ArrowLeftOutlined style={{ color: '#595959' }} />}
              onClick={onBack}
              style={{
                borderRadius: '50%',
                width: 32,
                height: 32,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            />
          </Tooltip>
          <span
            style={{
              fontWeight: 600,
              fontSize: 15,
              color: '#1a1a1a',
              letterSpacing: '0.2px',
              padding: '4px 10px',
            }}
          >
            {canvasName}
          </span>
        </div>

        {/* 中间: 组件库标题 */}
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          <Button
            size="small"
            icon={<AppstoreOutlined />}
            style={{
              fontSize: 13,
              fontWeight: 500,
              borderRadius: 8,
              border: 'none',
              background: '#4361ee',
              color: '#fff',
              boxShadow: '0 2px 8px rgba(67,97,238,0.3)',
              cursor: 'default',
            }}
          >
            {t('canvas.componentLib')}
          </Button>
        </div>

        {/* 右侧: 保存 + 发布 */}
        <div
          style={{
            flex: 1,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'flex-end',
            gap: 10,
          }}
        >
          <Button
            size="small"
            icon={<SaveOutlined />}
            onClick={onSave}
            style={{
              borderRadius: 8,
              border: 'none',
              fontWeight: 500,
              ...(isDirty
                ? {
                    background: '#4361ee',
                    color: '#fff',
                    boxShadow: '0 2px 8px rgba(67,97,238,0.3)',
                  }
                : {
                    background: '#f0f1f5',
                    color: '#999',
                  }),
              transition: 'all 200ms ease',
            }}
          >
            {isDirty ? t('canvas.saveDirty') : t('canvas.save')}
          </Button>
          <Button
            size="small"
            icon={<EyeOutlined />}
            onClick={onPreview}
            style={{
              borderRadius: 8,
              border: '1px solid #e0e0e0',
              background: 'transparent',
              color: '#555',
              fontWeight: 500,
              transition: 'all 200ms ease',
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.background = '#f7f7f8';
              e.currentTarget.style.borderColor = '#ccc';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.background = 'transparent';
              e.currentTarget.style.borderColor = '#e0e0e0';
            }}
          >
            {t('canvas.preview')}
          </Button>
          <Button
            size="small"
            icon={<RocketOutlined />}
            onClick={isPublished ? onUnpublish : onPublish}
            danger={isPublished}
            style={{
              borderRadius: 8,
              border: isPublished ? '1px solid #ff4d4f' : '1px solid #e0e0e0',
              background: isPublished ? '#fff2f0' : 'transparent',
              color: isPublished ? '#ff4d4f' : '#555',
              fontWeight: 500,
              transition: 'all 200ms ease',
            }}
          >
            {isPublished ? t('canvas.unpublish') : t('canvas.publish')}
          </Button>
        </div>
      </div>

      {/* ── Thumbnail row (always visible) ── */}
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: 24,
          padding: '16px 24px 20px',
          overflowX: 'auto',
          overflowY: 'hidden',
          borderTop: '1px solid #f0f0f0',
        }}
      >
        {CANVAS_COMPONENTS.map((type) => {
          const def = CANVAS_DEFAULTS[type];
          const variants = def?.variants ?? [];

          // ── 单 variant：thumbnail 直接可拖拽，跳过 Popover ──
          if (variants.length === 1) {
            return (
              <div
                key={type}
                draggable
                onDragStart={(e) =>
                  handleVariantDragStart(e, type, variants[0].code)
                }
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  gap: 8,
                  cursor: 'grab',
                  userSelect: 'none',
                  flexShrink: 0,
                  width: 140,
                }}
              >
                <div
                  style={{
                    border: '1px solid #eaeaea',
                    borderRadius: 10,
                    overflow: 'hidden',
                    background: '#fff',
                    transition: 'all 200ms cubic-bezier(0.4, 0, 0.2, 1)',
                  }}
                  onMouseEnter={(e) => {
                    const el = e.currentTarget;
                    el.style.borderColor = '#4361ee';
                    el.style.boxShadow = '0 4px 16px rgba(67,97,238,0.12)';
                    el.style.transform = 'translateY(-3px) scale(1.03)';
                  }}
                  onMouseLeave={(e) => {
                    const el = e.currentTarget;
                    el.style.borderColor = '#eaeaea';
                    el.style.boxShadow = 'none';
                    el.style.transform = 'translateY(0) scale(1)';
                  }}
                >
                  <ComponentThumbnail componentType={type} width={140} />
                </div>
                <span
                  style={{
                    fontSize: 11,
                    color: '#888',
                    fontWeight: 500,
                    letterSpacing: '0.3px',
                    textAlign: 'center',
                    pointerEvents: 'none',
                  }}
                >
                  {getComponentLabel(type, t)}
                </span>
              </div>
            );
          }

          // ── 多 variant：保持 Popover hover 展开 ──
          const popoverContent = (
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: 16,
                padding: 4,
              }}
            >
              {variants.map((v) => (
                <div
                  key={v.name}
                  draggable
                  onDragStart={(e) => handleVariantDragStart(e, type, v.code)}
                  style={{
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    gap: 6,
                    cursor: 'grab',
                    userSelect: 'none',
                    flexShrink: 0,
                  }}
                >
                  <div
                    style={{
                      border: '1px solid #e8e8e8',
                      borderRadius: 8,
                      overflow: 'hidden',
                      background: '#fff',
                      transition: 'all 180ms ease',
                    }}
                    onMouseEnter={(e) => {
                      const el = e.currentTarget;
                      el.style.borderColor = '#4361ee';
                      el.style.boxShadow = '0 4px 12px rgba(67,97,238,0.15)';
                      el.style.transform = 'translateY(-3px) scale(1.02)';
                    }}
                    onMouseLeave={(e) => {
                      const el = e.currentTarget;
                      el.style.borderColor = '#e8e8e8';
                      el.style.boxShadow = 'none';
                      el.style.transform = 'translateY(0) scale(1)';
                    }}
                  >
                    <ComponentThumbnail
                      componentType={type}
                      code={v.code}
                      width={124}
                    />
                  </div>
                  <span
                    style={{
                      fontSize: 10,
                      color: '#666',
                      fontWeight: 500,
                      textAlign: 'center',
                      pointerEvents: 'none',
                    }}
                  >
                    {getVariantLabel(v.label, t)}
                  </span>
                </div>
              ))}
            </div>
          );

          return (
            <Popover
              key={type}
              content={popoverContent}
              title={
                <span style={{ fontSize: 12, fontWeight: 600, color: '#333' }}>
                  {getComponentLabel(type, t)}
                </span>
              }
              trigger="hover"
              placement="bottomLeft"
              mouseEnterDelay={0.2}
              mouseLeaveDelay={0.3}
            >
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  gap: 8,
                  cursor: 'grab',
                  userSelect: 'none',
                  flexShrink: 0,
                  width: 140,
                }}
              >
                <div
                  style={{
                    border: '1px solid #eaeaea',
                    borderRadius: 10,
                    overflow: 'hidden',
                    background: '#fff',
                    transition: 'all 200ms cubic-bezier(0.4, 0, 0.2, 1)',
                  }}
                  onMouseEnter={(e) => {
                    const el = e.currentTarget;
                    el.style.borderColor = '#4361ee';
                    el.style.boxShadow = '0 4px 16px rgba(67,97,238,0.12)';
                    el.style.transform = 'translateY(-3px) scale(1.03)';
                  }}
                  onMouseLeave={(e) => {
                    const el = e.currentTarget;
                    el.style.borderColor = '#eaeaea';
                    el.style.boxShadow = 'none';
                    el.style.transform = 'translateY(0) scale(1)';
                  }}
                >
                  <ComponentThumbnail componentType={type} width={140} />
                </div>
                <span
                  style={{
                    fontSize: 11,
                    color: '#888',
                    fontWeight: 500,
                    letterSpacing: '0.3px',
                    textAlign: 'center',
                    pointerEvents: 'none',
                  }}
                >
                  {getComponentLabel(type, t)}
                </span>
              </div>
            </Popover>
          );
        })}
      </div>
    </div>
  );
};

export default CanvasToolbar;
