/**
 * ICTAnalysisPanel Component
 * Configuration panel for ICT (Inner Circle Trader) analysis parameters
 * OQI-006: Senales ML
 */

import React, { useState, useCallback } from 'react';
import {
  Settings2,
  Target,
  TrendingUp,
  BarChart2,
  Clock,
  Layers,
  Eye,
  EyeOff,
  RotateCcw,
  Save,
  AlertTriangle,
  CheckCircle,
  Info,
  ChevronDown,
  ChevronUp,
} from 'lucide-react';

export interface ICTParams {
  // Timeframe settings
  timeframe: '1m' | '5m' | '15m' | '1h' | '4h' | '1d';
  htfBias: '15m' | '1h' | '4h' | '1d' | '1w';

  // Order Block settings
  orderBlocks: {
    enabled: boolean;
    lookback: number;
    minImbalance: number;
    showMitigated: boolean;
  };

  // Fair Value Gap settings
  fvg: {
    enabled: boolean;
    minSize: number;
    showFilled: boolean;
    filterByTrend: boolean;
  };

  // Market Structure settings
  marketStructure: {
    enabled: boolean;
    swingLookback: number;
    showBOS: boolean;
    showCHOCH: boolean;
  };

  // Liquidity settings
  liquidity: {
    enabled: boolean;
    showBSL: boolean;
    showSSL: boolean;
    equalHighsLows: boolean;
  };

  // Session settings
  sessions: {
    showAsian: boolean;
    showLondon: boolean;
    showNewYork: boolean;
    highlightKillzones: boolean;
  };
}

export interface ICTAnalysisPanelProps {
  params: ICTParams;
  onParamsChange: (params: ICTParams) => void;
  onSave?: () => void;
  onReset?: () => void;
  isLoading?: boolean;
  readOnly?: boolean;
}

const ICTAnalysisPanel: React.FC<ICTAnalysisPanelProps> = ({
  params,
  onParamsChange,
  onSave,
  onReset,
  isLoading = false,
  readOnly = false,
}) => {
  const [hasChanges, setHasChanges] = useState(false);
  const [expandedSections, setExpandedSections] = useState<string[]>(['timeframe', 'orderBlocks']);

  const toggleSection = (section: string) => {
    setExpandedSections((prev) =>
      prev.includes(section) ? prev.filter((s) => s !== section) : [...prev, section]
    );
  };

  const updateParams = useCallback(
    (updates: Partial<ICTParams>) => {
      if (readOnly) return;
      onParamsChange({ ...params, ...updates });
      setHasChanges(true);
    },
    [params, onParamsChange, readOnly]
  );

  const handleSave = () => {
    if (onSave) {
      onSave();
      setHasChanges(false);
    }
  };

  const handleReset = () => {
    if (onReset) {
      onReset();
      setHasChanges(false);
    }
  };

  const timeframes = ['1m', '5m', '15m', '1h', '4h', '1d'] as const;
  const htfOptions = ['15m', '1h', '4h', '1d', '1w'] as const;

  const SectionHeader: React.FC<{
    id: string;
    icon: React.ReactNode;
    title: string;
    enabled?: boolean;
    onToggle?: (enabled: boolean) => void;
  }> = ({ id, icon, title, enabled, onToggle }) => (
    <button
      onClick={() => toggleSection(id)}
      className="w-full flex items-center justify-between p-3 bg-gray-900/50 rounded-lg hover:bg-gray-900 transition-colors"
    >
      <div className="flex items-center gap-3">
        <div className="p-1.5 bg-blue-500/20 text-blue-400 rounded">{icon}</div>
        <span className="font-medium text-white">{title}</span>
      </div>
      <div className="flex items-center gap-2">
        {enabled !== undefined && onToggle && (
          <button
            onClick={(e) => {
              e.stopPropagation();
              if (!readOnly) onToggle(!enabled);
            }}
            className={`p-1 rounded transition-colors ${
              enabled ? 'text-green-400 bg-green-500/20' : 'text-gray-500 bg-gray-700'
            }`}
          >
            {enabled ? <Eye className="w-4 h-4" /> : <EyeOff className="w-4 h-4" />}
          </button>
        )}
        {expandedSections.includes(id) ? (
          <ChevronUp className="w-4 h-4 text-gray-400" />
        ) : (
          <ChevronDown className="w-4 h-4 text-gray-400" />
        )}
      </div>
    </button>
  );

  return (
    <div className="bg-gray-800/50 rounded-xl border border-gray-700 p-4">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-cyan-500/20 text-cyan-400 rounded-lg">
            <Settings2 className="w-5 h-5" />
          </div>
          <div>
            <h3 className="font-semibold text-white">ICT Analysis Settings</h3>
            <p className="text-xs text-gray-400">Configure market structure detection</p>
          </div>
        </div>

        {!readOnly && (
          <div className="flex items-center gap-2">
            <button
              onClick={handleReset}
              disabled={isLoading || !hasChanges}
              className="flex items-center gap-1 px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors disabled:opacity-50"
            >
              <RotateCcw className="w-4 h-4" />
              Reset
            </button>
            <button
              onClick={handleSave}
              disabled={isLoading || !hasChanges}
              className="flex items-center gap-1 px-3 py-1.5 text-sm bg-cyan-500 text-white rounded-lg hover:bg-cyan-600 transition-colors disabled:opacity-50"
            >
              <Save className="w-4 h-4" />
              Save
            </button>
          </div>
        )}
      </div>

      {/* Sections */}
      <div className="space-y-3">
        {/* Timeframe Section */}
        <div>
          <SectionHeader id="timeframe" icon={<Clock className="w-4 h-4" />} title="Timeframe" />
          {expandedSections.includes('timeframe') && (
            <div className="mt-2 p-3 bg-gray-900/30 rounded-lg space-y-4">
              <div>
                <label className="block text-sm text-gray-400 mb-2">Analysis Timeframe</label>
                <div className="flex flex-wrap gap-2">
                  {timeframes.map((tf) => (
                    <button
                      key={tf}
                      onClick={() => updateParams({ timeframe: tf })}
                      disabled={readOnly}
                      className={`px-3 py-1.5 rounded text-sm transition-colors ${
                        params.timeframe === tf
                          ? 'bg-cyan-500 text-white'
                          : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
                      }`}
                    >
                      {tf}
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <label className="block text-sm text-gray-400 mb-2">HTF Bias Reference</label>
                <div className="flex flex-wrap gap-2">
                  {htfOptions.map((tf) => (
                    <button
                      key={tf}
                      onClick={() => updateParams({ htfBias: tf })}
                      disabled={readOnly}
                      className={`px-3 py-1.5 rounded text-sm transition-colors ${
                        params.htfBias === tf
                          ? 'bg-purple-500 text-white'
                          : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
                      }`}
                    >
                      {tf}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Order Blocks Section */}
        <div>
          <SectionHeader
            id="orderBlocks"
            icon={<Target className="w-4 h-4" />}
            title="Order Blocks"
            enabled={params.orderBlocks.enabled}
            onToggle={(enabled) => updateParams({ orderBlocks: { ...params.orderBlocks, enabled } })}
          />
          {expandedSections.includes('orderBlocks') && params.orderBlocks.enabled && (
            <div className="mt-2 p-3 bg-gray-900/30 rounded-lg space-y-4">
              <div>
                <label className="flex items-center justify-between text-sm text-gray-400 mb-2">
                  <span>Lookback Period</span>
                  <span className="text-white">{params.orderBlocks.lookback} candles</span>
                </label>
                <input
                  type="range"
                  min="10"
                  max="100"
                  value={params.orderBlocks.lookback}
                  onChange={(e) =>
                    updateParams({ orderBlocks: { ...params.orderBlocks, lookback: Number(e.target.value) } })
                  }
                  disabled={readOnly}
                  className="w-full h-2 bg-gray-700 rounded-lg appearance-none cursor-pointer accent-cyan-500"
                />
              </div>
              <div>
                <label className="flex items-center justify-between text-sm text-gray-400 mb-2">
                  <span>Min Imbalance %</span>
                  <span className="text-white">{params.orderBlocks.minImbalance}%</span>
                </label>
                <input
                  type="range"
                  min="0.1"
                  max="5"
                  step="0.1"
                  value={params.orderBlocks.minImbalance}
                  onChange={(e) =>
                    updateParams({ orderBlocks: { ...params.orderBlocks, minImbalance: Number(e.target.value) } })
                  }
                  disabled={readOnly}
                  className="w-full h-2 bg-gray-700 rounded-lg appearance-none cursor-pointer accent-cyan-500"
                />
              </div>
              <label className="flex items-center gap-2 text-sm text-gray-300">
                <input
                  type="checkbox"
                  checked={params.orderBlocks.showMitigated}
                  onChange={(e) =>
                    updateParams({ orderBlocks: { ...params.orderBlocks, showMitigated: e.target.checked } })
                  }
                  disabled={readOnly}
                  className="rounded border-gray-600 text-cyan-500 focus:ring-cyan-500"
                />
                Show mitigated order blocks
              </label>
            </div>
          )}
        </div>

        {/* Fair Value Gap Section */}
        <div>
          <SectionHeader
            id="fvg"
            icon={<BarChart2 className="w-4 h-4" />}
            title="Fair Value Gaps"
            enabled={params.fvg.enabled}
            onToggle={(enabled) => updateParams({ fvg: { ...params.fvg, enabled } })}
          />
          {expandedSections.includes('fvg') && params.fvg.enabled && (
            <div className="mt-2 p-3 bg-gray-900/30 rounded-lg space-y-4">
              <div>
                <label className="flex items-center justify-between text-sm text-gray-400 mb-2">
                  <span>Minimum Gap Size</span>
                  <span className="text-white">{params.fvg.minSize} pips</span>
                </label>
                <input
                  type="range"
                  min="1"
                  max="50"
                  value={params.fvg.minSize}
                  onChange={(e) => updateParams({ fvg: { ...params.fvg, minSize: Number(e.target.value) } })}
                  disabled={readOnly}
                  className="w-full h-2 bg-gray-700 rounded-lg appearance-none cursor-pointer accent-cyan-500"
                />
              </div>
              <label className="flex items-center gap-2 text-sm text-gray-300">
                <input
                  type="checkbox"
                  checked={params.fvg.showFilled}
                  onChange={(e) => updateParams({ fvg: { ...params.fvg, showFilled: e.target.checked } })}
                  disabled={readOnly}
                  className="rounded border-gray-600 text-cyan-500 focus:ring-cyan-500"
                />
                Show filled gaps
              </label>
              <label className="flex items-center gap-2 text-sm text-gray-300">
                <input
                  type="checkbox"
                  checked={params.fvg.filterByTrend}
                  onChange={(e) => updateParams({ fvg: { ...params.fvg, filterByTrend: e.target.checked } })}
                  disabled={readOnly}
                  className="rounded border-gray-600 text-cyan-500 focus:ring-cyan-500"
                />
                Filter by HTF trend direction
              </label>
            </div>
          )}
        </div>

        {/* Market Structure Section */}
        <div>
          <SectionHeader
            id="marketStructure"
            icon={<TrendingUp className="w-4 h-4" />}
            title="Market Structure"
            enabled={params.marketStructure.enabled}
            onToggle={(enabled) => updateParams({ marketStructure: { ...params.marketStructure, enabled } })}
          />
          {expandedSections.includes('marketStructure') && params.marketStructure.enabled && (
            <div className="mt-2 p-3 bg-gray-900/30 rounded-lg space-y-4">
              <div>
                <label className="flex items-center justify-between text-sm text-gray-400 mb-2">
                  <span>Swing Lookback</span>
                  <span className="text-white">{params.marketStructure.swingLookback} candles</span>
                </label>
                <input
                  type="range"
                  min="3"
                  max="20"
                  value={params.marketStructure.swingLookback}
                  onChange={(e) =>
                    updateParams({ marketStructure: { ...params.marketStructure, swingLookback: Number(e.target.value) } })
                  }
                  disabled={readOnly}
                  className="w-full h-2 bg-gray-700 rounded-lg appearance-none cursor-pointer accent-cyan-500"
                />
              </div>
              <label className="flex items-center gap-2 text-sm text-gray-300">
                <input
                  type="checkbox"
                  checked={params.marketStructure.showBOS}
                  onChange={(e) =>
                    updateParams({ marketStructure: { ...params.marketStructure, showBOS: e.target.checked } })
                  }
                  disabled={readOnly}
                  className="rounded border-gray-600 text-cyan-500 focus:ring-cyan-500"
                />
                Show Break of Structure (BOS)
              </label>
              <label className="flex items-center gap-2 text-sm text-gray-300">
                <input
                  type="checkbox"
                  checked={params.marketStructure.showCHOCH}
                  onChange={(e) =>
                    updateParams({ marketStructure: { ...params.marketStructure, showCHOCH: e.target.checked } })
                  }
                  disabled={readOnly}
                  className="rounded border-gray-600 text-cyan-500 focus:ring-cyan-500"
                />
                Show Change of Character (CHOCH)
              </label>
            </div>
          )}
        </div>

        {/* Liquidity Section */}
        <div>
          <SectionHeader
            id="liquidity"
            icon={<Layers className="w-4 h-4" />}
            title="Liquidity"
            enabled={params.liquidity.enabled}
            onToggle={(enabled) => updateParams({ liquidity: { ...params.liquidity, enabled } })}
          />
          {expandedSections.includes('liquidity') && params.liquidity.enabled && (
            <div className="mt-2 p-3 bg-gray-900/30 rounded-lg space-y-3">
              <label className="flex items-center gap-2 text-sm text-gray-300">
                <input
                  type="checkbox"
                  checked={params.liquidity.showBSL}
                  onChange={(e) => updateParams({ liquidity: { ...params.liquidity, showBSL: e.target.checked } })}
                  disabled={readOnly}
                  className="rounded border-gray-600 text-cyan-500 focus:ring-cyan-500"
                />
                Show Buy Side Liquidity (BSL)
              </label>
              <label className="flex items-center gap-2 text-sm text-gray-300">
                <input
                  type="checkbox"
                  checked={params.liquidity.showSSL}
                  onChange={(e) => updateParams({ liquidity: { ...params.liquidity, showSSL: e.target.checked } })}
                  disabled={readOnly}
                  className="rounded border-gray-600 text-cyan-500 focus:ring-cyan-500"
                />
                Show Sell Side Liquidity (SSL)
              </label>
              <label className="flex items-center gap-2 text-sm text-gray-300">
                <input
                  type="checkbox"
                  checked={params.liquidity.equalHighsLows}
                  onChange={(e) => updateParams({ liquidity: { ...params.liquidity, equalHighsLows: e.target.checked } })}
                  disabled={readOnly}
                  className="rounded border-gray-600 text-cyan-500 focus:ring-cyan-500"
                />
                Highlight Equal Highs/Lows
              </label>
            </div>
          )}
        </div>
      </div>

      {/* Info */}
      <div className="mt-4 flex items-start gap-2 p-3 bg-cyan-500/10 border border-cyan-500/30 rounded-lg">
        <Info className="w-4 h-4 text-cyan-400 flex-shrink-0 mt-0.5" />
        <div className="text-xs text-gray-300">
          <p>
            ICT (Inner Circle Trader) concepts help identify institutional order flow through market structure,
            order blocks, and liquidity zones. Adjust sensitivity based on your trading timeframe.
          </p>
        </div>
      </div>
    </div>
  );
};

export default ICTAnalysisPanel;
