import React from 'react';
import { Panel, PanelGroup, PanelResizeHandle } from 'react-resizable-panels';

import EntityTypeSelector from './EntityTypeSelector';
import OpenApiFieldsSelector from './OpenApiFieldsSelector';
import IncludeSelector from './IncludeSelector';
import FilterSelector from './FilterSelector';
import SortSelector from './SortSelector';
import PageLimitSelector from './PageLimitSelector';
import UrlDisplay from './UrlDisplay';
import ResponseDisplay from './ResponseDisplay';
import RequestHistorySection from './RequestHistorySection';
import CodeExamplesTab from './CodeExamplesTab';

/**
 * The main explorer layout component with the resizable panels
 */
const ExplorerLayout = ({
  // Panel layout
  panelSizes,
  handlePanelResize,

  // Entity and bundle selection
  entities,
  selectedEntity,
  selectedBundle,
  setSelectedEntity,
  setSelectedBundle,

  // Fields and relationships
  selectedFields,
  setSelectedFields,
  includes,
  setIncludes,
  relatedEntityFields,
  loadingRelatedFields,
  userActionRef,

  // Filters and sorts
  filters,
  setFilters,
  sorts,
  setSorts,

  // Pagination
  page,
  setPage,
  limit,
  setLimit,

  // URL and execution
  requestUrl,
  copyToClipboard,
  executeRequest,
  loading,
  autoExecute,
  setAutoExecute,

  // Response
  error,
  response,
  responseHeaders,
  responseSize,
  responseTime,

  // Builder panel state
  builderPanelActiveTab,
  setBuilderPanelActiveTab,

  // History
  requestHistory,
  onLoadHistory,

  // Notifications
  showNotification,

  // Base URL
  baseUrl
}) => {
  return (
    <div className="explorer-panels-layout">
      <PanelGroup
        direction="horizontal"
        onLayout={handlePanelResize}
        autoSaveId="jsonapi-explorer-panel-layout">
        {/* Left Sidebar Panel */}
        <Panel defaultSize={panelSizes[0]} minSize={15} className="explorer-panel explorer-panel-sidebar">
          <div className="explorer-panel-header">
            Explorer
          </div>
          <div className="explorer-panel-content" style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
            {loading && !entities.length ? (
              <div className="spinner-container">
                <div className="spinner"></div>
              </div>
            ) : error && !entities.length ? (
              <div className="messages messages--error">{error}</div>
            ) : (
              <>
                <div className="entity-panel">
                  <EntityTypeSelector
                    entities={entities}
                    selectedEntity={selectedEntity}
                    selectedBundle={selectedBundle}
                    onEntityChange={setSelectedEntity}
                    onBundleChange={setSelectedBundle}
                  />
                </div>

                <div className="panel-section">
                  <PageLimitSelector
                    page={page}
                    limit={limit}
                    onPageChange={setPage}
                    onLimitChange={setLimit}
                  />
                </div>

                <RequestHistorySection
                  history={requestHistory}
                  onLoadHistory={onLoadHistory}
                />
              </>
            )}
          </div>
        </Panel>

        {/* Resize Handle */}
        <PanelResizeHandle className="panel-resizer" />

        {/* Middle Panel - Query Builder */}
        <Panel defaultSize={panelSizes[1]} minSize={25} className="explorer-panel explorer-panel-builder">
          <div className="explorer-panel-header">
            <span>Query builder</span>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <label
                  style={{
                    marginRight: '5px',
                    display: 'flex',
                    alignItems: 'center',
                    cursor: 'pointer',
                    fontSize: '0.9rem'
                  }}
                >
                  <input
                    type="checkbox"
                    checked={autoExecute}
                    onChange={(e) => setAutoExecute(e.target.checked)}
                    style={{ marginRight: '5px' }}
                  />
                  Auto execute
                </label>
                <div
                  className="field-tooltip-wrapper js-tooltip"
                  data-tooltip="When enabled, automatically executes the query and updates the response each time a change is made to any parameter (includes, fields, filters, etc.)."
                  style={{ marginRight: '10px', cursor: 'help' }}
                >
                  <span style={{
                    display: 'inline-flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    width: '16px',
                    height: '16px',
                    borderRadius: '50%',
                    background: 'var(--gin-color-primary-light)',
                    color: 'var(--gin-color-primary)',
                    fontSize: '12px',
                    fontWeight: 'bold'
                  }}>?</span>
                </div>
              </div>
              <button
                className="explorer-toolbar-button"
                onClick={executeRequest}
                disabled={!requestUrl || loading}
                data-testid="execute-button">
                {loading ? <div className="spinner"></div> : "Execute query"}
              </button>
            </div>
          </div>

          {/* URL Preview always displayed before tabs */}
          <div className="url-display-container">
            <UrlDisplay
              url={requestUrl}
              onCopy={() => copyToClipboard(requestUrl)}
              showNotification={showNotification}
            />
          </div>

          <div className="query-panel-tabs">
            <button
              className={`query-panel-tab ${builderPanelActiveTab === 'fields' ? 'active' : ''}`}
              onClick={() => setBuilderPanelActiveTab('fields')}>
              Fields
            </button>
            <button
              className={`query-panel-tab ${builderPanelActiveTab === 'filters' ? 'active' : ''}`}
              onClick={() => setBuilderPanelActiveTab('filters')}>
              Filters
            </button>
            <button
              className={`query-panel-tab ${builderPanelActiveTab === 'includes' ? 'active' : ''}`}
              onClick={() => setBuilderPanelActiveTab('includes')}>
              Includes
            </button>
            <button
              className={`query-panel-tab ${builderPanelActiveTab === 'sort' ? 'active' : ''}`}
              onClick={() => setBuilderPanelActiveTab('sort')}>
              Sort
            </button>
            <button
              className={`query-panel-tab ${builderPanelActiveTab === 'code' ? 'active' : ''}`}
              onClick={() => setBuilderPanelActiveTab('code')}>
              &lt;/&gt;
            </button>
          </div>

          <div className="explorer-panel-content">
            {/* Different content based on selected tab */}
            {builderPanelActiveTab === 'fields' && (
              <div className="tab-content-section">
                <OpenApiFieldsSelector
                  key={`fields-${selectedEntity}-${selectedBundle}-${includes.join('-')}`}
                  selectedEntity={selectedEntity}
                  selectedBundle={selectedBundle}
                  selectedFields={selectedFields}
                  onFieldsChange={setSelectedFields}
                  relatedEntityFields={relatedEntityFields}
                  loadingRelatedFields={loadingRelatedFields}
                  baseUrl={baseUrl}
                  includes={includes}
                  onIncludeChange={setIncludes}
                />
              </div>
            )}

            {builderPanelActiveTab === 'filters' && (
              <div className="tab-content-section">
                <FilterSelector
                  selectedEntity={selectedEntity}
                  selectedBundle={selectedBundle}
                  filters={filters}
                  onFiltersChange={setFilters}
                  relatedEntityFields={relatedEntityFields}
                  baseUrl={baseUrl}
                />
              </div>
            )}

            {builderPanelActiveTab === 'includes' && (
              <div className="tab-content-section">
                <IncludeSelector
                  selectedEntity={selectedEntity}
                  selectedBundle={selectedBundle}
                  includes={includes}
                  onIncludeChange={(newIncludes) => {
                    // First set flag to indicate user action
                    userActionRef.current = true;

                    // Then update includes (this will trigger our useEffect)
                    setIncludes(newIncludes);
                  }}
                  baseUrl={baseUrl}
                />
              </div>
            )}

            {builderPanelActiveTab === 'sort' && (
              <div className="tab-content-section">
                <SortSelector
                  selectedEntity={selectedEntity}
                  selectedBundle={selectedBundle}
                  sorts={sorts}
                  onSortsChange={setSorts}
                  relatedEntityFields={relatedEntityFields}
                  baseUrl={baseUrl}
                />
              </div>
            )}

            {builderPanelActiveTab === 'code' && (
              <div className="tab-content-section">
                <CodeExamplesTab
                  requestUrl={requestUrl}
                  onCopy={(code) => copyToClipboard(code)}
                  showNotification={showNotification}
                />
              </div>
            )}
          </div>
        </Panel>

        {/* Resize Handle */}
        <PanelResizeHandle className="panel-resizer" />

        {/* Right Panel - Response */}
        <Panel defaultSize={panelSizes[2]} minSize={20} className="explorer-panel explorer-panel-response">
          <div className="explorer-panel-header">
            <span>Response</span>
            {responseTime > 0 && responseSize > 0 && (
              <div className="explorer-response-stats">
                <span>
                  {responseTime < 1000
                    ? `${Math.round(responseTime)}ms`
                    : `${(responseTime / 1000).toFixed(2)}s`}
                </span>
                <span className="ml-2">{(responseSize / 1024).toFixed(2)} KB</span>
              </div>
            )}
          </div>

          <div className="explorer-panel-content">
            {/* Error message display */}
            {error ? <div className="messages messages--error">{error}</div> : null}

            {/* Response display */}
            <ResponseDisplay
              response={response}
              responseHeaders={responseHeaders}
              onCopyJson={() => {
                if (response) {
                  try {
                    copyToClipboard(JSON.stringify(response, null, 2));
                  } catch (err) {
                    console.error('Error copying response:', err);
                    try {
                      copyToClipboard(String(response));
                    } catch (finalErr) {
                      console.error('Final error copying response:', finalErr);
                    }
                  }
                }
              }}
              onCopyPath={(path) => {
                if (path) {
                  copyToClipboard(path);
                }
              }}
            />
          </div>
        </Panel>
      </PanelGroup>
    </div>
  );
};

export default ExplorerLayout;
