import { useCallback, useEffect, useMemo, useState } from 'react';
import { Empty, Spin, Card, Space, Typography, Tag, Button, Progress } from 'antd';
import { ThunderboltOutlined, ReloadOutlined } from '@ant-design/icons';
import type { AttributeDAG, ExpertSource, ExpertTransformationDAGResult, PromptLanguage } from '../types';
import { TransformationDAG } from './TransformationDAG';
import { useExpertTransformation } from '../hooks/useExpertTransformation';

const { Text } = Typography;

interface DualTransformationPanelProps {
  crossoverDAGA: AttributeDAG | null;  // Path A with attributes from B
  crossoverDAGB: AttributeDAG | null;  // Path B with attributes from A
  isDark: boolean;
  model?: string;
  temperature?: number;
  expertConfig: {
    expert_count: number;
    keywords_per_expert: number;
    custom_experts?: string[];
  };
  expertSource: ExpertSource;
  expertLanguage: 'en' | 'zh';
  lang?: PromptLanguage;
  shouldStartTransform: boolean;
  onTransformComplete: () => void;
  onLoadingChange: (loading: boolean) => void;
  onResultsChange?: (results: { pathA: ExpertTransformationDAGResult | null; pathB: ExpertTransformationDAGResult | null }) => void;
}

interface SinglePathTransformProps {
  label: string;
  color: 'blue' | 'green';
  attributeData: AttributeDAG | null;
  crossoverSource: string; // The query from which attributes were crossed over
  isDark: boolean;
  model?: string;
  temperature?: number;
  expertConfig: {
    expert_count: number;
    keywords_per_expert: number;
    custom_experts?: string[];
  };
  expertSource: ExpertSource;
  expertLanguage: 'en' | 'zh';
  lang?: PromptLanguage;
  shouldStart: boolean;
  onComplete: () => void;
  onResultChange: (result: ExpertTransformationDAGResult | null) => void;
}

function SinglePathTransform({
  label,
  color,
  attributeData,
  crossoverSource,
  isDark,
  model,
  temperature,
  expertConfig,
  expertSource,
  expertLanguage,
  lang = 'zh',
  shouldStart,
  onComplete,
  onResultChange,
}: SinglePathTransformProps) {
  const {
    loading,
    progress,
    results,
    transformAll,
    clearResults,
  } = useExpertTransformation({ model, temperature, expertSource, expertLanguage, lang });

  // Notify parent of results changes
  useEffect(() => {
    onResultChange(results);
  }, [results, onResultChange]);

  // Build transformation input
  const transformationInput = useMemo(() => {
    if (!attributeData) return null;

    const attributesByCategory: Record<string, string[]> = {};
    for (const node of attributeData.nodes) {
      if (!attributesByCategory[node.category]) {
        attributesByCategory[node.category] = [];
      }
      attributesByCategory[node.category].push(node.name);
    }

    return {
      query: attributeData.query,
      categories: attributeData.categories,
      attributesByCategory,
      expertConfig,
    };
  }, [attributeData, expertConfig]);

  // Handle transform trigger
  useEffect(() => {
    if (shouldStart && transformationInput && !loading && !results) {
      transformAll(transformationInput).then(() => onComplete());
    }
  }, [shouldStart, transformationInput, loading, results, transformAll, onComplete]);

  // Progress percentage
  const progressPercent = useMemo(() => {
    if (!transformationInput || progress.step === 'idle') return 0;
    const totalCategories = transformationInput.categories.length;
    if (totalCategories === 0) return 0;
    const completed = progress.processedCategories.length;
    return Math.round((completed / totalCategories) * 100);
  }, [transformationInput, progress]);

  const headerStyle: React.CSSProperties = {
    padding: '8px 12px',
    background: isDark ? '#1f1f1f' : '#fafafa',
    borderBottom: `1px solid ${isDark ? '#303030' : '#f0f0f0'}`,
    display: 'flex',
    alignItems: 'center',
    gap: 8,
  };

  if (!attributeData || attributeData.nodes.length === 0) {
    return (
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
        <div style={headerStyle}>
          <Tag color={color}>{label}</Tag>
          <Text type="secondary">No crossover attributes selected</Text>
        </div>
        <div style={{ flex: 1, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
          <Empty description="Select crossover pairs first" />
        </div>
      </div>
    );
  }

  if (loading) {
    return (
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
        <div style={headerStyle}>
          <Tag color={color}>{label}</Tag>
          <Text strong>{attributeData.query}</Text>
          <Text type="secondary">← receiving {attributeData.nodes.length} attributes</Text>
        </div>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', gap: 16 }}>
          <Spin size="large" />
          <Text>{progress.message}</Text>
          <Progress percent={progressPercent} style={{ width: 200 }} />
        </div>
      </div>
    );
  }

  if (results) {
    return (
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
        <div style={headerStyle}>
          <Tag color={color}>{label}</Tag>
          <Text strong>{attributeData.query}</Text>
          <Text type="secondary">
            {results.results.reduce((sum, r) => sum + r.descriptions.length, 0)} descriptions
          </Text>
          <div style={{ flex: 1 }} />
          <Button size="small" icon={<ReloadOutlined />} onClick={clearResults}>
            Clear
          </Button>
        </div>
        <div style={{ flex: 1, overflow: 'hidden' }}>
          <TransformationDAG
            data={results}
            categories={attributeData.categories}
            isDark={isDark}
            crossoverSource={crossoverSource}
          />
        </div>
      </div>
    );
  }

  // Ready state - show attributes to transform
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={headerStyle}>
        <Tag color={color}>{label}</Tag>
        <Text strong>{attributeData.query}</Text>
        <Text type="secondary">← {attributeData.nodes.length} attributes to transform</Text>
      </div>
      <div style={{ flex: 1, padding: 16, overflow: 'auto' }}>
        <Card size="small" title="Crossover Attributes">
          <Space wrap>
            {attributeData.nodes.map(node => (
              <Tag key={node.id} color={color === 'blue' ? 'green' : 'blue'}>
                {node.name}
                <Text type="secondary" style={{ marginLeft: 4, fontSize: 10 }}>
                  ({node.category})
                </Text>
              </Tag>
            ))}
          </Space>
        </Card>
        <Text type="secondary" style={{ display: 'block', marginTop: 12, fontSize: 12 }}>
          These attributes will be transformed with "{attributeData.query}" as context.
        </Text>
      </div>
    </div>
  );
}

export function DualTransformationPanel({
  crossoverDAGA,
  crossoverDAGB,
  isDark,
  model,
  temperature,
  expertConfig,
  expertSource,
  expertLanguage,
  lang = 'zh',
  shouldStartTransform,
  onTransformComplete,
  onLoadingChange,
  onResultsChange,
}: DualTransformationPanelProps) {
  const [resultA, setResultA] = useState<ExpertTransformationDAGResult | null>(null);
  const [resultB, setResultB] = useState<ExpertTransformationDAGResult | null>(null);
  const [triggerA, setTriggerA] = useState(false);
  const [triggerB, setTriggerB] = useState(false);

  // Handle external transform trigger
  useEffect(() => {
    if (shouldStartTransform) {
      setTriggerA(true);
      setTriggerB(true);
      onLoadingChange(true);
    }
  }, [shouldStartTransform, onLoadingChange]);

  // Notify parent of results
  useEffect(() => {
    onResultsChange?.({ pathA: resultA, pathB: resultB });
  }, [resultA, resultB, onResultsChange]);

  const handleCompleteA = useCallback(() => {
    setTriggerA(false);
  }, []);

  const handleCompleteB = useCallback(() => {
    setTriggerB(false);
  }, []);

  // When both are done, notify parent
  useEffect(() => {
    if (!triggerA && !triggerB && (resultA || resultB)) {
      onLoadingChange(false);
      onTransformComplete();
    }
  }, [triggerA, triggerB, resultA, resultB, onLoadingChange, onTransformComplete]);

  const containerStyle: React.CSSProperties = {
    display: 'flex',
    flexDirection: 'column',
    height: '100%',
    gap: 2,
  };

  const pathContainerStyle: React.CSSProperties = {
    flex: 1,
    minHeight: 0,
    borderRadius: 6,
    overflow: 'hidden',
    border: `1px solid ${isDark ? '#303030' : '#f0f0f0'}`,
  };

  const dividerStyle: React.CSSProperties = {
    height: 4,
    background: isDark ? '#303030' : '#f0f0f0',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  };

  // Show empty state if no crossover data
  if (!crossoverDAGA && !crossoverDAGB) {
    return (
      <div style={{ height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
        <Empty
          description={
            <Space direction="vertical" align="center">
              <ThunderboltOutlined style={{ fontSize: 32, color: isDark ? '#444' : '#ccc' }} />
              <Text>Select crossover pairs first</Text>
              <Text type="secondary">
                Go to the Crossover tab and select attribute pairs to transform
              </Text>
            </Space>
          }
        />
      </div>
    );
  }

  return (
    <div style={containerStyle}>
      {/* Path A - Top (receives attributes from Path B) */}
      <div style={pathContainerStyle}>
        <SinglePathTransform
          label="Path A"
          color="blue"
          attributeData={crossoverDAGA}
          crossoverSource={crossoverDAGB?.query || 'Path B'}
          isDark={isDark}
          model={model}
          temperature={temperature}
          expertConfig={expertConfig}
          expertSource={expertSource}
          expertLanguage={expertLanguage}
          lang={lang}
          shouldStart={triggerA}
          onComplete={handleCompleteA}
          onResultChange={setResultA}
        />
      </div>

      {/* Divider */}
      <div style={dividerStyle}>
        <div style={{
          width: 40,
          height: 3,
          borderRadius: 2,
          background: isDark ? '#505050' : '#d0d0d0',
        }} />
      </div>

      {/* Path B - Bottom (receives attributes from Path A) */}
      <div style={pathContainerStyle}>
        <SinglePathTransform
          label="Path B"
          color="green"
          attributeData={crossoverDAGB}
          crossoverSource={crossoverDAGA?.query || 'Path A'}
          isDark={isDark}
          model={model}
          temperature={temperature}
          expertConfig={expertConfig}
          expertSource={expertSource}
          expertLanguage={expertLanguage}
          lang={lang}
          shouldStart={triggerB}
          onComplete={handleCompleteB}
          onResultChange={setResultB}
        />
      </div>
    </div>
  );
}
