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

const { Text } = Typography;

interface TransformationPanelProps {
  attributeData: AttributeDAG | null;
  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: ExpertTransformationDAGResult | null) => void;
}

export const TransformationPanel = forwardRef<TransformationDAGRef, TransformationPanelProps>(
  ({ attributeData, isDark, model, temperature, expertConfig, expertSource, expertLanguage, lang = 'zh', shouldStartTransform, onTransformComplete, onLoadingChange, onResultsChange }, ref) => {
    const {
      loading,
      progress,
      results,
      transformAll,
      clearResults,
    } = useExpertTransformation({ model, temperature, expertSource, expertLanguage, lang });

    // Notify parent of loading state changes
    useEffect(() => {
      onLoadingChange(loading);
    }, [loading, onLoadingChange]);

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

    // Build expert transformation input from attribute data
    const transformationInput = useMemo((): ExpertTransformationInput | null => {
      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]);

    const handleTransform = useCallback(async () => {
      if (transformationInput) {
        await transformAll(transformationInput);
        onTransformComplete();
      }
    }, [transformationInput, transformAll, onTransformComplete]);

    const handleClear = useCallback(() => {
      clearResults();
    }, [clearResults]);

    // Handle shouldStartTransform trigger from control panel
    useEffect(() => {
      if (shouldStartTransform && transformationInput && !loading && !results) {
        handleTransform();
      }
    }, [shouldStartTransform, transformationInput, loading, results, handleTransform]);

    // Calculate 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]);

    // No attribute data - show empty state
    if (!attributeData) {
      return (
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '100%',
            flexDirection: 'column',
            gap: 16,
          }}
        >
          <Empty
            description="請先在 Attribute Agent 分頁執行分析"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
          <Text type="secondary">
            Transformation Agent 需要 Attribute Agent 的分析結果
          </Text>
        </div>
      );
    }

    // Has attribute data but no results yet - show ready message
    if (!results && !loading) {
      const categoryCount = attributeData.categories.length;
      const nodeCount = attributeData.nodes.length;

      return (
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '100%',
            flexDirection: 'column',
            gap: 24,
          }}
        >
          <Card
            style={{
              textAlign: 'center',
              maxWidth: 400,
              background: isDark ? '#1f1f1f' : '#fff',
            }}
          >
            <Space direction="vertical" size="large">
              <div>
                <Text strong style={{ fontSize: 16 }}>
                  準備轉換：{attributeData.query}
                </Text>
              </div>
              <Space wrap>
                <Tag color="blue">{categoryCount} 個類別</Tag>
                <Tag color="green">{nodeCount} 個屬性</Tag>
              </Space>
              <Text type="secondary">
                專家團隊將從不同視角為每個屬性生成創新關鍵字並產生創新應用描述
              </Text>
              <Text type="secondary" style={{ fontSize: 12 }}>
                請在右側控制面板配置專家參數並開始轉換
              </Text>
            </Space>
          </Card>
        </div>
      );
    }

    // Loading state - show progress with expert info
    if (loading) {
      return (
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '100%',
            flexDirection: 'column',
            gap: 24,
          }}
        >
          <Card
            style={{
              textAlign: 'center',
              maxWidth: 450,
              background: isDark ? '#1f1f1f' : '#fff',
            }}
          >
            <Space direction="vertical" size="large" style={{ width: '100%' }}>
              <Spin size="large" />
              <div>
                <Text strong style={{ fontSize: 16 }}>
                  {progress.message || '處理中...'}
                </Text>
              </div>
              {progress.currentCategory && (
                <Tag color="processing">{progress.currentCategory}</Tag>
              )}
              {progress.experts && progress.experts.length > 0 && (
                <div>
                  <Text type="secondary" style={{ fontSize: 12 }}>
                    專家團隊：
                  </Text>
                  <div style={{ marginTop: 8 }}>
                    <Space wrap size="small">
                      {progress.experts.map((expert) => (
                        <Tag key={expert.id} color="blue" style={{ fontSize: 11 }}>
                          {expert.name}
                        </Tag>
                      ))}
                    </Space>
                  </div>
                </div>
              )}
              {progress.currentAttribute && (
                <Text type="secondary" style={{ fontSize: 12 }}>
                  當前屬性：{progress.currentAttribute}
                </Text>
              )}
              <Progress
                percent={progressPercent}
                status="active"
                strokeColor={{
                  '0%': '#108ee9',
                  '100%': '#87d068',
                }}
              />
              <Text type="secondary">
                已完成 {progress.processedCategories.length} / {transformationInput?.categories.length || 0} 個類別
              </Text>
            </Space>
          </Card>
        </div>
      );
    }

    // Has results - show DAG visualization
    if (results) {
      return (
        <div style={{ height: '100%', position: 'relative' }}>
          <div
            style={{
              position: 'absolute',
              top: 16,
              right: 16,
              zIndex: 10,
            }}
          >
            <Button
              icon={<ReloadOutlined />}
              onClick={handleClear}
            >
              重新轉換
            </Button>
          </div>
          <TransformationDAG
            ref={ref}
            data={results}
            categories={attributeData.categories}
            isDark={isDark}
          />
        </div>
      );
    }

    // Fallback - should not reach here
    return null;
  }
);

TransformationPanel.displayName = 'TransformationPanel';
