import React, { useEffect, useMemo } from 'react';
import {
  Card,
  Button,
  Slider,
  Statistic,
  Row,
  Col,
  Empty,
  Spin,
  Alert,
  Typography,
  Space,
  Divider,
} from 'antd';
import {
  FilterOutlined,
  ReloadOutlined,
  CheckCircleOutlined,
  ClusterOutlined,
  CopyOutlined,
} from '@ant-design/icons';
import { useDeduplication } from '../hooks/useDeduplication';
import { GroupCard } from './deduplication/GroupCard';
import type {
  ExpertTransformationDAGResult,
  ExpertTransformationDescription,
  DeduplicationMethod,
  PromptLanguage,
} from '../types';

const { Title, Text } = Typography;

interface DeduplicationPanelProps {
  transformationResult: ExpertTransformationDAGResult | null;
  isDark: boolean;
  threshold: number;
  onThresholdChange: (value: number) => void;
  method: DeduplicationMethod;
  onMethodChange?: (method: DeduplicationMethod) => void;  // Optional, handled in App.tsx sidebar
  lang?: PromptLanguage;
}

/**
 * Panel for deduplicating transformation descriptions
 */
export const DeduplicationPanel: React.FC<DeduplicationPanelProps> = ({
  transformationResult,
  isDark,
  threshold,
  onThresholdChange,
  method,
  lang = 'zh',
  // onMethodChange is handled in App.tsx sidebar
}) => {
  const { loading, result, error, progress, deduplicate, clearResult } = useDeduplication();

  // Extract all descriptions from transformation result
  const allDescriptions = useMemo<ExpertTransformationDescription[]>(() => {
    if (!transformationResult) return [];

    const descriptions: ExpertTransformationDescription[] = [];
    for (const categoryResult of transformationResult.results) {
      descriptions.push(...categoryResult.descriptions);
    }
    return descriptions;
  }, [transformationResult]);

  // Clear result when transformation result or method changes
  useEffect(() => {
    clearResult();
  }, [transformationResult, method, clearResult]);

  const handleDeduplicate = () => {
    if (allDescriptions.length > 0) {
      deduplicate(allDescriptions, threshold, method, lang);
    }
  };

  const containerStyle: React.CSSProperties = {
    height: '100%',
    display: 'flex',
    flexDirection: 'column',
    padding: 16,
    overflow: 'hidden',
  };

  const headerCardStyle: React.CSSProperties = {
    marginBottom: 16,
    background: isDark ? '#1f1f1f' : '#fff',
    borderRadius: 8,
  };

  const resultsContainerStyle: React.CSSProperties = {
    flex: 1,
    overflow: 'auto',
    paddingRight: 8,
  };

  // No transformation data
  if (!transformationResult) {
    return (
      <div style={{ ...containerStyle, justifyContent: 'center', alignItems: 'center' }}>
        <Empty
          description={
            <Space direction="vertical" size={4}>
              <Text style={{ color: isDark ? '#999' : '#666' }}>
                No transformation data available
              </Text>
              <Text type="secondary" style={{ fontSize: 12 }}>
                Please run the Transformation Agent first
              </Text>
            </Space>
          }
        />
      </div>
    );
  }

  // No descriptions found
  if (allDescriptions.length === 0) {
    return (
      <div style={{ ...containerStyle, justifyContent: 'center', alignItems: 'center' }}>
        <Empty description="No descriptions found in transformation result" />
      </div>
    );
  }

  return (
    <div style={containerStyle}>
      {/* Header Card with Controls */}
      <Card size="small" style={headerCardStyle}>
        <Row gutter={[16, 16]} align="middle">
          <Col span={6}>
            <Statistic
              title="Total Descriptions"
              value={allDescriptions.length}
              prefix={<FilterOutlined />}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="Unique Groups"
              value={result?.total_groups ?? '-'}
              prefix={<ClusterOutlined />}
              valueStyle={{ color: result ? '#52c41a' : undefined }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="Duplicates Found"
              value={result?.total_duplicates ?? '-'}
              prefix={<CopyOutlined />}
              valueStyle={{ color: result?.total_duplicates ? '#fa8c16' : undefined }}
            />
          </Col>
          <Col span={6}>
            <Space direction="vertical" size={4} style={{ width: '100%' }}>
              <Text type="secondary" style={{ fontSize: 12 }}>
                Similarity Threshold: {(threshold * 100).toFixed(0)}%
              </Text>
              <Slider
                min={0.5}
                max={1.0}
                step={0.05}
                value={threshold}
                onChange={onThresholdChange}
                disabled={loading}
                tooltip={{ formatter: (val) => `${((val ?? 0) * 100).toFixed(0)}%` }}
              />
            </Space>
          </Col>
        </Row>

        <Divider style={{ margin: '12px 0' }} />

        <Row justify="space-between" align="middle">
          <Col>
            <Text type="secondary" style={{ fontSize: 12 }}>
              {progress.message || 'Ready to analyze'}
            </Text>
          </Col>
          <Col>
            <Space>
              {result && (
                <Button
                  icon={<ReloadOutlined />}
                  onClick={clearResult}
                  disabled={loading}
                >
                  Clear
                </Button>
              )}
              <Button
                type="primary"
                icon={<CheckCircleOutlined />}
                onClick={handleDeduplicate}
                loading={loading}
              >
                {loading ? 'Processing...' : 'Deduplicate'}
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* Error Alert */}
      {error && (
        <Alert
          message="Deduplication Error"
          description={error}
          type="error"
          showIcon
          closable
          style={{ marginBottom: 16 }}
        />
      )}

      {/* Loading State */}
      {loading && (
        <div style={{ textAlign: 'center', padding: 40 }}>
          <Spin size="large" />
          <div style={{ marginTop: 16 }}>
            <Text type="secondary">{progress.message}</Text>
          </div>
        </div>
      )}

      {/* Results */}
      {!loading && result && (
        <div style={resultsContainerStyle}>
          <Title level={5} style={{ marginBottom: 16, color: isDark ? '#fff' : '#000' }}>
            <ClusterOutlined style={{ marginRight: 8 }} />
            {result.total_groups} Groups
            {result.total_duplicates > 0 && (
              <Text type="secondary" style={{ fontSize: 14, fontWeight: 'normal', marginLeft: 8 }}>
                ({result.total_duplicates} duplicates removed)
              </Text>
            )}
          </Title>

          {result.groups.map((group, index) => (
            <GroupCard
              key={group.group_id}
              group={group}
              isDark={isDark}
              index={index}
            />
          ))}

          {result.total_groups === 0 && (
            <Empty description="No groups found" />
          )}
        </div>
      )}

      {/* Initial State - show prompt */}
      {!loading && !result && !error && (
        <div style={{ textAlign: 'center', padding: 40 }}>
          <FilterOutlined style={{ fontSize: 48, color: '#1890ff', marginBottom: 16 }} />
          <Title level={4} style={{ color: isDark ? '#fff' : '#000' }}>
            Ready to Deduplicate
          </Title>
          <Text type="secondary">
            Click the "Deduplicate" button to analyze {allDescriptions.length} descriptions
            and group similar ones together.
          </Text>
        </div>
      )}
    </div>
  );
};

export default DeduplicationPanel;
