import { Button } from "@wordpress/components";
import { useEffect } from "@wordpress/element";
import { useSelect, useDispatch } from "@wordpress/data";
import { PREVIEW_STORE } from "../../../store/preview";
import { useResponsiveTabV2 } from "./ResponsiveTabContextV2";
import { getEnabledBreakpoints, getBreakpointConfig } from "../../../core/breakpoints";
import { tablet, mobile } from "@wordpress/icons";
import { SVG, Path } from "@wordpress/primitives";
import "./preview-device-control.scss";

const desktopPC = (
  <SVG xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
    <Path d="M21 2H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h7v2H8v2h8v-2h-2v-2h7c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H3V4h18v12z" />
  </SVG>
);

const laptop = (
  <SVG xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
    <Path d="M20 16V7c0-.6-.4-1-1-1H5c-.6 0-1 .4-1 1v9H2v2h20v-2h-2zm-2 0H6V8h12v8z" />
  </SVG>
);

const deviceIcons = {
  pc: desktopPC,
  md: laptop,
  tb: tablet,
  sp: mobile,
};

export const getDeviceWidth = (device) => {
  const config = getBreakpointConfig();
  switch (device) {
    case 'pc': return null;
    case 'md': return config.values?.md || 1140;
    case 'tb': return config.values?.tb || 840;
    case 'sp': return config.values?.sp || 540;
    default: return null;
  }
};

const getDeviceRange = (device) => {
  const config = getBreakpointConfig();
  const values = config.values;
  const enabled = config.enabled || ['pc', 'md', 'tb', 'sp'];

  switch (device) {
    case 'pc':
      if (enabled.includes('md')) {
        return `${values.md + 1}px ~ FULL`;
      } else if (enabled.includes('tb')) {
        return `${values.tb + 1}px ~ FULL`;
      }
      return 'FULL';
    case 'md':
      return `${values.tb + 1}px ~ ${values.md}px`;
    case 'tb':
      return `${values.sp + 1}px ~ ${values.tb}px`;
    case 'sp':
      return `0px ~ ${values.sp}px`;
    default:
      return '';
  }
};

const setEditorWidth = (width) => {
  const editorCanvas = document.querySelector('iframe[name="editor-canvas"]');

  if (editorCanvas) {
    // iframe要素自体をリサイズ（vw単位がプレビュー幅を基準に計算されるようにする）
    if (width) {
      editorCanvas.style.width = `${width}px`;
      editorCanvas.style.maxWidth = `${width}px`;
      editorCanvas.style.margin = '0 auto';
      editorCanvas.style.transition = 'width 0.3s ease, max-width 0.3s ease';
    } else {
      editorCanvas.style.width = '';
      editorCanvas.style.maxWidth = '';
      editorCanvas.style.margin = '';
      editorCanvas.style.transition = '';
    }
    return;
  }

  // フォールバック: iframe非使用時は.editor-styles-wrapperのmaxWidthを変更
  const editorWrapper = document.querySelector('.editor-styles-wrapper');
  if (editorWrapper) {
    if (width) {
      editorWrapper.style.maxWidth = `${width}px`;
      editorWrapper.style.margin = '0 auto';
      editorWrapper.style.transition = 'max-width 0.3s ease';
    } else {
      editorWrapper.style.maxWidth = '';
      editorWrapper.style.margin = '';
    }
  }
};

// ブロック間切替時の遅延リセット用タイマー
let pendingResetTimer = null;

const PreviewDeviceControl = () => {
  const { setActiveTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const previewDevice = useSelect(
    (select) => select(PREVIEW_STORE).getDevice(),
    []
  );
  const { setDevice } = useDispatch(PREVIEW_STORE);

  // mount時: 遅延リセットをキャンセル（ブロック間切替でプレビュー状態を維持）
  // unmount時: 150ms後にPCにリセットをスケジュール
  useEffect(() => {
    if (pendingResetTimer) {
      clearTimeout(pendingResetTimer);
      pendingResetTimer = null;
    }

    return () => {
      pendingResetTimer = setTimeout(() => {
        setDevice('pc');
        setEditorWidth(null);
        document.body.removeAttribute('data-zenblocks-preview-device');
        document.body.removeAttribute('data-zenblocks-preview-width');
        pendingResetTimer = null;
      }, 150);
    };
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  // デバイス変更時にエディタ幅とbody属性を同期
  useEffect(() => {
    const width = getDeviceWidth(previewDevice);
    setEditorWidth(width);
    document.body.setAttribute('data-zenblocks-preview-device', previewDevice);
    document.body.setAttribute('data-zenblocks-preview-width', width || '');
  }, [previewDevice]);

  const handleDeviceChange = (device) => {
    setDevice(device);
    setActiveTab(device);
  };

  const width = getDeviceWidth(previewDevice);

  const rootClassName = `zenblocks-preview-device-control${previewDevice !== 'pc' ? ' is-previewing' : ''}`;

  return (
    <div className={rootClassName}>
      <div className="zenblocks-preview-device-control__inner">
        <div className="zenblocks-preview-device-control__buttons">
          {enabledBreakpoints.map((bp) => (
            <Button
              key={bp}
              icon={deviceIcons[bp]}
              isPressed={previewDevice === bp}
              onClick={() => handleDeviceChange(bp)}
              label={bp.toUpperCase()}
              className={`zenblocks-preview-device-control__button${previewDevice === bp ? ' is-active' : ''}`}
            />
          ))}
        </div>
        <div className="zenblocks-preview-device-control__info">
          <span className="zenblocks-preview-device-control__device">
            <span className="zenblocks-preview-device-control__device-icon">
              {deviceIcons[previewDevice]}
            </span>
            {previewDevice.toUpperCase()}
          </span>
          <span className="zenblocks-preview-device-control__range">
            {getDeviceRange(previewDevice)}
          </span>
        </div>
      </div>
    </div>
  );
};

export default PreviewDeviceControl;
