import React from 'react';
import { Button, Typography, Card, Space, Divider } from '@douyinfe/semi-ui';
import { useState, useEffect } from 'react';
import { RecordSelectionCard } from './components/RecordSelectionCard';
import { useRecordSelection } from './hooks/useRecordSelection';
import { QueryResultsDisplay } from './components/QueryResultsDisplay';
import { LabelSelectionCard } from './components/LabelSelectionCard';
import { TimelineModal } from './components/TimelineModal';
import { apiService } from './services/apiService';
import { TABLE_CONFIG, LABEL_CONFIG } from './constants/config';
import type { RecordDetail, QueryResult, LabelOptions } from './types';

const { Title } = Typography;

export default function App() {
  // 使用自定义 Hook 管理记录选择
  const {
    selectedRecords,
    recordDetails,
    loading,
    handleSelectRecords,
    handleClearRecords
  } = useRecordSelection();

  // 查询结果状态
  const [queryResults, setQueryResults] = useState<QueryResult[]>([]);
  const [secondaryProcessResults, setSecondaryProcessResults] = useState<QueryResult[]>([]);
  const [pricingDetailsResults, setPricingDetailsResults] = useState<QueryResult[]>([]);
  const [queryLoading, setQueryLoading] = useState(false);
  const [secondaryProcessLoading, setSecondaryProcessLoading] = useState(false);
  const [pricingDetailsLoading, setPricingDetailsLoading] = useState(false);

  // 标签相关状态
  const [labelOptions, setLabelOptions] = useState<LabelOptions>({});
  const [selectedLabels, setSelectedLabels] = useState<{[key: string]: string | string[]}>({});
  const [expectedDate, setExpectedDate] = useState<Date | null>(null);
  const [labelLoading, setLabelLoading] = useState(false);

  // 时效计算相关状态
  const [timelineVisible, setTimelineVisible] = useState(false);
  const [timelineLoading, setTimelineLoading] = useState(false);
  const [timelineResults, setTimelineResults] = useState<any[]>([]);
  const [timelineAdjustments, setTimelineAdjustments] = useState<{[key: number]: number}>({});

  // 初始化标签选项
  useEffect(() => {
    const initializeLabelOptions = async () => {
      setLabelLoading(true);
      try {
        const options = await apiService.fetchLabelOptions();
        setLabelOptions(options);
      } catch (error) {
        console.error('获取标签选项失败:', error);
      } finally {
        setLabelLoading(false);
      }
    };

    initializeLabelOptions();
  }, []);

  // 当记录选择变化时，自动执行查询
  useEffect(() => {
    if (selectedRecords.length > 0 && recordDetails.length > 0) {
      // 自动清空标签选择
      setSelectedLabels({});
      setExpectedDate(null);
      
      // 提取第一条记录的标签信息
      const firstRecord = recordDetails[0];
      const extractedLabels: {[key: string]: string | string[]} = {};
      
      // 提取标签1-10的值
      for (let i = 1; i <= 10; i++) {
        const labelKey = `标签${i}`;
        const fieldValue = firstRecord[labelKey];
        if (fieldValue && fieldValue !== '') {
          const isMultiSelect = i === 7 || i === 8 || i === 10;
          if (isMultiSelect && Array.isArray(fieldValue)) {
            extractedLabels[labelKey] = fieldValue;
          } else if (!isMultiSelect && typeof fieldValue === 'string') {
            extractedLabels[labelKey] = fieldValue;
          }
        }
      }
      
      setSelectedLabels(extractedLabels);
      
      // 顺序执行查询
      executeQueries();
    }
  }, [selectedRecords, recordDetails]);

  // 执行所有查询
  const executeQueries = async () => {
    try {
      await Promise.all([
        handleQueryDatabase(),
        handleSecondaryProcessQuery(),
        handlePricingDetailsQuery()
      ]);
    } catch (error) {
      console.error('查询执行失败:', error);
    }
  };

  // 面料数据查询
  const handleQueryDatabase = async () => {
    if (selectedRecords.length === 0) return;
    
    setQueryLoading(true);
    try {
      const results = await apiService.queryDatabase(selectedRecords);
      setQueryResults(results);
    } catch (error) {
      console.error('面料数据查询失败:', error);
      setQueryResults([]);
    } finally {
      setQueryLoading(false);
    }
  };

  // 二次工艺查询
  const handleSecondaryProcessQuery = async () => {
    if (selectedRecords.length === 0) return;
    
    setSecondaryProcessLoading(true);
    try {
      const results = await apiService.querySecondaryProcess(selectedRecords);
      setSecondaryProcessResults(results);
    } catch (error) {
      console.error('二次工艺查询失败:', error);
      setSecondaryProcessResults([]);
    } finally {
      setSecondaryProcessLoading(false);
    }
  };

  // 工艺价格查询
  const handlePricingDetailsQuery = async () => {
    if (selectedRecords.length === 0 || recordDetails.length === 0) return;
    
    const packId = recordDetails[0]?.packId;
    if (!packId) {
      console.error('缺少 packId，无法执行工艺价格查询');
      return;
    }
    
    setPricingDetailsLoading(true);
    try {
      const results = await apiService.queryPricingDetails(packId);
      setPricingDetailsResults(results);
    } catch (error) {
      console.error('工艺价格查询失败:', error);
      setPricingDetailsResults([]);
    } finally {
      setPricingDetailsLoading(false);
    }
  };

  // 标签选择变化处理
  const handleLabelChange = (labelKey: string, value: string | string[]) => {
    setSelectedLabels(prev => ({
      ...prev,
      [labelKey]: value
    }));
  };

  // 计算预计时间
  const handleCalculateTimeline = async () => {
    if (Object.keys(selectedLabels).length === 0) {
      console.warn('请先选择标签');
      return;
    }
    
    setTimelineLoading(true);
    try {
      const results = await apiService.calculateTimeline(selectedLabels, expectedDate);
      setTimelineResults(results);
      setTimelineVisible(true);
    } catch (error) {
      console.error('时效计算失败:', error);
    } finally {
      setTimelineLoading(false);
    }
  };

  // 清空所有数据
  const handleClearAll = () => {
    handleClearRecords();
    setSelectedLabels({});
    setExpectedDate(null);
    setQueryResults([]);
    setSecondaryProcessResults([]);
    setPricingDetailsResults([]);
    setTimelineResults([]);
    setTimelineAdjustments({});
  };

  return (
    <div style={{ padding: '20px', maxWidth: '1200px', margin: '0 auto' }}>
      <Title heading={2} style={{ marginBottom: '24px', textAlign: 'center' }}>
        版单数据管理系统
      </Title>

      {/* 记录选择卡片 */}
      <RecordSelectionCard
        selectedRecords={selectedRecords}
        recordDetails={recordDetails}
        loading={loading}
        onSelectRecords={handleSelectRecords}
        onClearRecords={handleClearAll}
      />

      {/* 标签选择卡片 */}
      {labelOptions && Object.keys(labelOptions).length > 0 && (
        <LabelSelectionCard
          labelOptions={labelOptions}
          selectedLabels={selectedLabels}
          expectedDate={expectedDate}
          timelineLoading={timelineLoading}
          onLabelChange={handleLabelChange}
          onExpectedDateChange={setExpectedDate}
          onCalculateTimeline={handleCalculateTimeline}
        />
      )}

      {/* 查询结果展示 */}
      <QueryResultsDisplay
        queryResults={queryResults}
        secondaryProcessResults={secondaryProcessResults}
        pricingDetailsResults={pricingDetailsResults}
        queryLoading={queryLoading}
        secondaryProcessLoading={secondaryProcessLoading}
        pricingDetailsLoading={pricingDetailsLoading}
      />

      {/* 时效计算模态框 */}
      <TimelineModal
        visible={timelineVisible}
        loading={timelineLoading}
        results={timelineResults}
        adjustments={timelineAdjustments}
        onClose={() => setTimelineVisible(false)}
        onAdjustmentChange={setTimelineAdjustments}
      />
    </div>
  );
}