import { useState } from 'react';
import { Badge } from '../ui/Badge';
import { cn } from '@/utils/cn';
import { Phase1EligibilityModal } from './Phase1EligibilityModal';
import { FlowDetailsSection } from './expandedRowDetails/FlowDetailsSection';
import { InstitutionalAnalyticsSection } from './expandedRowDetails/InstitutionalAnalyticsSection';
import { DealerRegimeSection } from './expandedRowDetails/DealerRegimeSection';
import { TimeSequencedSection } from './expandedRowDetails/TimeSequencedSection';
import { PriceContextSection } from './expandedRowDetails/PriceContextSection';
import { AnalysisSection } from './expandedRowDetails/AnalysisSection';
import { VolumeHistorySection } from './expandedRowDetails/VolumeHistorySection';

export function ExpandedRowDetails({ row }) {
  const [showPhase1Modal, setShowPhase1Modal] = useState(false);
  
  // Check if Phase 1 data exists
  const hasPhase1Data = row.signal_tier !== undefined || row.checklist_passed !== undefined || row.flow_led_to_move !== undefined;
  
  const signal = row.tradeSignal;
  const netPremium = (row.bull_total || 0) - (row.bear_total || 0);
  const bullTotal = row.bull_total || 0;
  const bearTotal = row.bear_total || 0;
  const volume = row.Volume || row.vol_num || 0;
  const oi = row.OI || row.oi_num || 0;
  const currentPriceRaw = row.u_close || row.spot_num || row.Price || 0;
  const currentPrice = typeof currentPriceRaw === 'number' ? currentPriceRaw : parseFloat(currentPriceRaw) || 0;
  const vwapRaw = row.vwap || currentPrice;
  const vwap = typeof vwapRaw === 'number' ? vwapRaw : parseFloat(vwapRaw) || currentPrice;
  const rthOpenRaw = row.rth_open || currentPrice;
  const rthOpen = typeof rthOpenRaw === 'number' ? rthOpenRaw : parseFloat(rthOpenRaw) || currentPrice;
  const pctVsRthOpen = typeof row.PctVsRthOpen === 'number' ? row.PctVsRthOpen : parseFloat(row.PctVsRthOpen || row.pct_vs_rth_open || 0) || 0;
  const pctVsPriorClose = typeof row.PctVsPriorClose === 'number' ? row.PctVsPriorClose : parseFloat(row.PctVsPriorClose || 0) || 0;
  const session = row.session_bucket || 'RTH';
  const catalyst = row.near_alert_type || 'None';
  const tapeAlign = row.TapeAlign || row.tapeArrow || '—';
  const trend = row.flowTrendRaw || row.flowTrend?.full;
  const decay = row.flowDecayRaw || row.flowDecay?.full;
  
  // Date fields
  const createdDate = row.CreatedDate;
  const createdTime = row.CreatedTime;
  const expirationDate = row.ExpirationDate;
  
  // Additional important details
  const spot = row.Spot || row.u_close || row.spot_num || 0;
  const moneynessPct = row.moneyness_pct || 0;
  const lastFlowMinutesAgo = trend?.lastFlowMinutesAgo ?? decay?.lastFlowMinutesAgo;
  
  // Get flow trend status
  const getFlowTrend = (lastFlowMinutes) => {
    if (lastFlowMinutes === null || lastFlowMinutes === undefined) {
      return null;
    }
    if (lastFlowMinutes <= 5) {
      return {
        icon: '🔥',
        label: 'SURGING',
        color: 'red',
        message: 'Institutions actively buying RIGHT NOW'
      };
    } else if (lastFlowMinutes <= 30) {
      return {
        icon: '🟡',
        label: 'STABLE',
        color: 'yellow',
        message: 'Recent flow - institutions still positioned'
      };
    } else if (lastFlowMinutes <= 60) {
      return {
        icon: '⚠️',
        label: 'FADING',
        color: 'orange',
        message: 'Flow slowing down - watch for reversal'
      };
    } else {
      return {
        icon: '💀',
        label: 'DEAD',
        color: 'red',
        message: 'Flow too stale - institutions likely exited'
      };
    }
  };

  const flowTrend = getFlowTrend(lastFlowMinutesAgo);
  const hoursAgo = lastFlowMinutesAgo ? Math.floor(lastFlowMinutesAgo / 60) : 0;
  
  // Format dates
  const formatCreatedDate = (date) => {
    if (!date) return 'N/A';
    try {
      return new Date(date).toLocaleDateString('en-US', { 
        month: 'short', 
        day: 'numeric', 
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    } catch {
      return date;
    }
  };
  
  const formatExpirationDate = (date) => {
    if (!date) return 'N/A';
    try {
      if (typeof date === 'string' && date.includes('/')) {
        return date;
      }
      return new Date(date).toLocaleDateString('en-US', { 
        month: 'long', 
        day: 'numeric', 
        year: 'numeric' 
      });
    } catch {
      return date;
    }
  };
  
  // Extract price from entry/stop/target
  const extractPrice = (value) => {
    if (!value) return null;
    if (typeof value === 'string') {
      const match = value.match(/\$?([\d.]+)/);
      return match ? parseFloat(match[1]) : null;
    }
    if (typeof value === 'object') {
      const primary = value.primary || value.aggressive || value.tight || value.wide || value.t1;
      if (typeof primary === 'string') {
        const match = primary.match(/\$?([\d.]+)/);
        return match ? parseFloat(match[1]) : null;
      }
    }
    return null;
  };

  const entryPrice = signal?.entry ? extractPrice(signal.entry) : null;
  const stopPrice = signal?.stop ? extractPrice(signal.stop) : null;
  const target1Price = signal?.target?.t1 ? extractPrice(signal.target.t1) : null;
  const target2Price = signal?.target?.t2 ? extractPrice(signal.target.t2) : null;
  const target3Price = signal?.target?.t3 ? extractPrice(signal.target.t3) : null;

  return (
    <div className="bg-slate-800/30 border-t border-slate-700 p-6">
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Flow Details */}
        <FlowDetailsSection
          row={row}
          flowTrend={flowTrend}
          lastFlowMinutesAgo={lastFlowMinutesAgo}
          hoursAgo={hoursAgo}
          netPremium={netPremium}
          bullTotal={bullTotal}
          bearTotal={bearTotal}
          volume={volume}
          oi={oi}
        />

        {/* Institutional Analytics - Phase 1 */}
        <InstitutionalAnalyticsSection row={row} />

        {/* Phase 3: Advanced Dealer & Regime Analytics */}
        <DealerRegimeSection row={row} />

        {/* Time-Sequenced Metrics - Separate Section */}
        <TimeSequencedSection row={row} />

        {/* Price Context */}
        <PriceContextSection
          row={row}
          currentPrice={currentPrice}
          vwap={vwap}
          rthOpen={rthOpen}
          pctVsRthOpen={pctVsRthOpen}
          pctVsPriorClose={pctVsPriorClose}
          spot={spot}
          moneynessPct={moneynessPct}
          session={session}
          tapeAlign={tapeAlign}
        />

        {/* Timing & Dates */}
        <div className="space-y-3">
          <h4 className="text-sm font-semibold text-slate-300 mb-3 border-b border-slate-700 pb-2">📅 TIMING & DATES</h4>
          <div className="space-y-2 text-xs">
            <div>
              <span className="text-slate-500">Created Date:</span>
              <span className="ml-2 text-slate-300 font-semibold">
                {createdDate ? formatCreatedDate(createdDate) : 'N/A'}
              </span>
            </div>
            <div>
              <span className="text-slate-500">Created Time:</span>
              <span className="ml-2 text-slate-300 font-mono">
                {createdTime || 'N/A'}
              </span>
            </div>
            <div>
              <span className="text-slate-500">Expiration Date:</span>
              <span className="ml-2 text-slate-200 font-bold">
                {expirationDate ? formatExpirationDate(expirationDate) : 'N/A'}
              </span>
            </div>
            {lastFlowMinutesAgo !== null && lastFlowMinutesAgo !== undefined && (
              <div>
                <span className="text-slate-500">Last Flow:</span>
                <span className={cn(
                  "ml-2 font-semibold",
                  lastFlowMinutesAgo < 30 ? "text-green-400" :
                  lastFlowMinutesAgo < 60 ? "text-yellow-400" :
                  "text-slate-500"
                )}>
                  {lastFlowMinutesAgo} minutes ago
                </span>
              </div>
            )}
          </div>
        </div>

        {/* Catalyst */}
        <div className="space-y-3">
          <h4 className="text-sm font-semibold text-slate-300 mb-3 border-b border-slate-700 pb-2">⚡ CATALYST</h4>
          <div className="space-y-2 text-xs">
            {catalyst !== 'None' ? (
              <>
                <div>
                  <span className="text-slate-500">Type:</span>
                  <Badge variant="warning" className="ml-2 text-xs">{catalyst}</Badge>
                </div>
                {trend?.lastFlowMinutesAgo !== null && trend?.lastFlowMinutesAgo !== undefined && (
                  <div>
                    <span className="text-slate-500">Last Flow:</span>
                    <span className="ml-2 text-slate-300">{trend.lastFlowMinutesAgo}min ago</span>
                  </div>
                )}
              </>
            ) : (
              <div className="text-slate-500">No alerts detected</div>
            )}
          </div>
        </div>

        {/* Trade Plan */}
        {signal && signal.signal !== 'NEUTRAL' && signal.signal !== 'WAIT' && (
          <div className="space-y-3 md:col-span-2 lg:col-span-3">
            <h4 className="text-sm font-semibold text-slate-300 mb-3">🎯 SUGGESTED TRADE PLAN</h4>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {entryPrice && (
                <div className="bg-slate-800/50 rounded p-3">
                  <div className="text-xs text-slate-500 mb-1">Entry</div>
                  <div className="text-green-400 font-semibold">
                    ${typeof entryPrice === 'number' ? entryPrice.toFixed(2) : 'N/A'}
                  </div>
                  {signal.entry?.notes && (
                    <div className="text-xs text-slate-400 mt-1">{signal.entry.notes}</div>
                  )}
                </div>
              )}
              {stopPrice && (
                <div className="bg-slate-800/50 rounded p-3">
                  <div className="text-xs text-slate-500 mb-1">Stop</div>
                  <div className="text-red-400 font-semibold">
                    ${typeof stopPrice === 'number' ? stopPrice.toFixed(2) : 'N/A'}
                  </div>
                  {signal.stop?.riskPct && (
                    <div className="text-xs text-slate-400 mt-1">({signal.stop.riskPct}% risk)</div>
                  )}
                </div>
              )}
              {target1Price && (
                <div className="bg-slate-800/50 rounded p-3">
                  <div className="text-xs text-slate-500 mb-1">Target 1</div>
                  <div className="text-blue-400 font-semibold">
                    ${typeof target1Price === 'number' ? target1Price.toFixed(2) : 'N/A'}
                  </div>
                  <div className="text-xs text-slate-400 mt-1">Take 50%</div>
                </div>
              )}
              {target2Price && (
                <div className="bg-slate-800/50 rounded p-3">
                  <div className="text-xs text-slate-500 mb-1">Target 2</div>
                  <div className="text-blue-400 font-semibold">
                    ${typeof target2Price === 'number' ? target2Price.toFixed(2) : 'N/A'}
                  </div>
                  <div className="text-xs text-slate-400 mt-1">Take 30%</div>
                </div>
              )}
              {target3Price && (
                <div className="bg-slate-800/50 rounded p-3">
                  <div className="text-xs text-slate-500 mb-1">Target 3</div>
                  <div className="text-blue-400 font-semibold">
                    ${typeof target3Price === 'number' ? target3Price.toFixed(2) : 'N/A'}
                  </div>
                  <div className="text-xs text-slate-400 mt-1">Runner 20%</div>
                </div>
              )}
            </div>
            {signal.confidence && (
              <div className="mt-3 text-xs text-slate-400">
                Confidence: <span className="text-slate-200 font-semibold">{signal.confidence}%</span>
                {' • '}
                Time Horizon: <span className="text-slate-200">{signal.timeHorizon || 'INTRADAY'}</span>
              </div>
            )}
          </div>
        )}

        {/* Invalidation Rules */}
        {signal && signal.invalidation && (
          <div className="space-y-3 md:col-span-2 lg:col-span-3">
            <h4 className="text-sm font-semibold text-slate-300 mb-3">⚠️ INVALIDATION RULES</h4>
            <div className="space-y-1 text-xs text-slate-400">
              {Array.isArray(signal.invalidation) ? (
                signal.invalidation.map((rule, idx) => (
                  <div key={idx}>• {rule}</div>
                ))
              ) : (
                <div>• {signal.invalidation}</div>
              )}
            </div>
          </div>
        )}

        {/* Phase 1 & AI Analysis */}
        <AnalysisSection 
          row={row} 
          hasPhase1Data={hasPhase1Data} 
          onPhase1Click={() => setShowPhase1Modal(true)} 
        />

        {/* Last 5 Days Volume History - Table Format */}
        <VolumeHistorySection row={row} />
      </div>

      {/* Phase 1 Eligibility Modal */}
      <Phase1EligibilityModal
        row={row}
        isOpen={showPhase1Modal}
        onClose={() => setShowPhase1Modal(false)}
      />
    </div>
  );
}
