import { useState, useMemo, lazy, Suspense } from 'react';
import { Tabs, Row, Col, Card, Alert } from 'antd';
import { Link } from 'react-router-dom';
import CustomWave from './CustomWave';
import { useOptionsHooks } from '../../hooks/useOptionsHooks';

// Lazy load only heavy components to keep the initial render fast
const TutorialGraphDisplay = lazy(() => import('./TutorialGraphDisplay'));
const Sample = lazy(() => import('../../Route/Sample'));

// Loads only when Tab 4 is active
const Tab4PitchPane = () => {
  const {
    gender,
    setGender,
    genderName,
    audioPlayerNew,
    audioKey,
    audioSrc,
    fetchAudioData,
    handleIconClick,
    itemsAvatar,
  } = useOptionsHooks();

  return (
    <Suspense fallback={<div style={{ padding: 16 }}>Loading…</div>}>
      <Sample
        gender={gender}
        setGender={setGender}
        genderName={genderName}
        audioKey={audioKey}
        audioSrc={audioSrc}
        fetchAudioData={fetchAudioData}
        handleIconClick={handleIconClick}
        itemsAvatar={itemsAvatar}
        showDescription={true}
      />
    </Suspense>
  );
};

const GavtTutorial = () => {
  const [activeKey, setActiveKey] = useState('1');
  const [showTab4, setShowTab4] = useState(true);
  const [tab4Key, setTab4Key] = useState(0);
  const [waveKey, setWaveKey] = useState(0);

  const handleChange = (k) => {
    setActiveKey(k);
    if (k === '4') {
      // Temporarily unmount Tab4 to force re-render after layout stabilizes
      setShowTab4(false);
      requestAnimationFrame(() => {
        requestAnimationFrame(() => {
          setShowTab4(true);
          setTab4Key(v => v + 1);

          setWaveKey(w => w + 1);
        });
      });
    }
  };

  const items = useMemo(() => [
    {
      label: 'Blank Slide with Wave',
      key: '1',
      children: (
        <div style={{ background: '#fff', padding: 0, width: '80%'  }}>
          <CustomWave />
        </div>
      ),
    },
    {
      label: 'Vowel toggle',
      key: '2',
      // Wrap with Suspense for lazy loading
      children: (
        <Suspense fallback={<div style={{ padding: 16 }}>Loading…</div>}>
          <TutorialGraphDisplay currentStep="7" />
        </Suspense>
      ),
    },
    {
      label: 'Brighter/Darker toggle',
      key: '3',
      children: (
        <Suspense fallback={<div style={{ padding: 16 }}>Loading…</div>}>
          <TutorialGraphDisplay currentStep="10" />
        </Suspense>
      ),
    },
    {
      label: 'Side-by-side pitch and resonance',
      key: '4',
      children: (
        <Row gutter={24} style={{ padding: '20px' }}>
          <Col span={12}>
            <Card title="Pitch" bordered style={{ height: '1000px' }}>
              {/* Only render the Sample component when Tab4 is active and stable */}
              {activeKey === '4' && showTab4 ? (
                <div key={tab4Key}>
                  <Tab4PitchPane />
                </div>
              ) : null}
            </Card>
          </Col>
          <Col span={12}>
            <Card
              title="Resonance"
              bordered
              style={{ height: '1000px' }}
              styles={{
                body: {
                  padding: 0,
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                  height: '100%',
                },
              }}
            >
              {/* Keep this wave always loaded; add white background for visibility */}
              {activeKey === '4' ? (
                <div style={{ width: '80%', minWidth: 320, background: '#fff' }}>
                  <CustomWave key={`wave-${waveKey}`} canvasWidth="80%" />
                </div>
              ) : null}
            </Card>
          </Col>
        </Row>
      ),
    },
  ], [activeKey, showTab4, tab4Key]);

  return (
    <div style={{ marginTop: '30px', width: '100%' }}>
      <Alert
        message="Internal Test Page"
        description={
          <span>
            This page is for internal testing only and may be unstable.{' '}
            For regular use, please go to the{' '}
            <Link to="/resonance/selection">Resonance Setup</Link> page.
            <div style={{ marginTop: 8, fontSize: '0.85em', color: '#888' }}>
              Last updated for this page: Oct 28, 2025
            </div>
          </span>
        }
        type="warning"
        showIcon
        style={{ marginBottom: '20px' }}
      />

      {/* Do not wrap the entire Tabs with Suspense so Tab1 remains unaffected */}
      <Tabs
        tabPosition="left"
        activeKey={activeKey}
        onChange={handleChange}
        type="card"
        destroyInactiveTabPane
        animated={false}
        items={items}
        style={{ marginTop: '50px', width: '100%', height: '100%' }}
      />
    </div>
  );
};

export default GavtTutorial;
