/**
 * Company 页面顶部搜索栏组件 - FUI 科幻风格
 *
 * 设计特点：
 * - 左侧固定标题 + 副标题
 * - 右侧简洁搜索框
 * - 深色背景 + 金色强调色
 */

import React, { memo, useMemo, useCallback, useState } from 'react';
import {
  Box,
  Flex,
  HStack,
  VStack,
  Text,
} from '@chakra-ui/react';
import { AutoComplete, Input, Spin } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { useStockSearch } from '@hooks/useStockSearch';
import { THEME } from '../../config';
import { FUI_COLORS, FUI_GLOW, FUI_ANIMATION, FUI_GLASS } from '../../theme/fui';
import type { CompanyHeaderProps, StockSearchResult } from '../../types';

/**
 * 页面标题组件
 */
const PageTitle = memo(() => (
  <VStack align="start" spacing={1}>
    <Text
      fontSize="2xl"
      fontWeight="bold"
      color={FUI_COLORS.gold[400]}
      letterSpacing="wider"
      textShadow={FUI_GLOW.text.gold}
    >
      个股详情
    </Text>
    <Text
      fontSize="sm"
      color={FUI_COLORS.text.muted}
      letterSpacing="wide"
    >
      查看股票实时行情、财务数据和盈利预测
    </Text>
  </VStack>
));

PageTitle.displayName = 'PageTitle';

/**
 * 搜索框组件（状态自管理，减少父组件重渲染）
 */
const SearchBox = memo<{
  stockCode: string;
  onStockChange: (value: string) => void;
}>(({
  stockCode,
  onStockChange,
}) => {
  // 输入状态 - 默认为空，显示 placeholder
  const [inputCode, setInputCode] = useState('');

  // 股票搜索 Hook
  const searchHook = useStockSearch({
    limit: 10,
    debounceMs: 300,
    onSearch: () => {}, // 空回调，追踪在父组件处理
  }) as {
    searchResults: StockSearchResult[];
    isSearching: boolean;
    handleSearch: (query: string) => void;
    clearSearch: () => void;
  };

  const { searchResults, isSearching, handleSearch: doSearch, clearSearch } = searchHook;

  // 转换为 AutoComplete options
  const stockOptions = useMemo(() => {
    return searchResults.map((stock: StockSearchResult) => ({
      value: stock.stock_code,
      label: (
        <Flex justify="space-between" align="center" py={1}>
          <HStack spacing={2}>
            <Text fontWeight="bold" color={THEME.gold}>{stock.stock_code}</Text>
            <Text color={THEME.textPrimary}>{stock.stock_name}</Text>
          </HStack>
          {stock.pinyin_abbr && (
            <Text fontSize="xs" color={THEME.textMuted}>
              {stock.pinyin_abbr.toUpperCase()}
            </Text>
          )}
        </Flex>
      ),
    }));
  }, [searchResults]);

  // 选中股票
  const handleSelect = useCallback((value: string) => {
    clearSearch();
    setInputCode(value);
    if (value !== stockCode) {
      onStockChange(value);
    }
  }, [clearSearch, stockCode, onStockChange]);

  // 键盘事件 - 回车搜索
  const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && inputCode && inputCode !== stockCode) {
      onStockChange(inputCode);
    }
  }, [inputCode, stockCode, onStockChange]);

  return (
    <Box
      sx={{
        '.ant-select': {
          width: '320px !important',
        },
        '.ant-input-affix-wrapper': {
          backgroundColor: 'transparent !important',
          borderColor: `${FUI_COLORS.gold[400]} !important`,
          borderWidth: '1px !important',
          borderRadius: '6px !important',
          height: '44px !important',
          padding: '0 12px !important',
          transition: `all ${FUI_ANIMATION.duration.fast} ${FUI_ANIMATION.easing.default}`,
          '&:hover': {
            borderColor: `${FUI_COLORS.gold[300]} !important`,
            boxShadow: FUI_GLOW.gold.sm,
          },
          '&:focus-within, &.ant-input-affix-wrapper-focused': {
            borderColor: `${FUI_COLORS.gold[300]} !important`,
            boxShadow: `${FUI_GLOW.gold.md} !important`,
          },
        },
        '.ant-input': {
          backgroundColor: 'transparent !important',
          color: `${FUI_COLORS.gold[400]} !important`,
          fontSize: '14px !important',
          '&::placeholder': {
            color: `${FUI_COLORS.gold[400]} !important`,
            opacity: '0.7 !important',
          },
        },
        '.ant-input-prefix': {
          marginRight: '8px !important',
        },
      }}
    >
      <AutoComplete
        popupClassName="fui-autocomplete-dropdown"
        value={inputCode}
        options={stockOptions}
        onSearch={doSearch}
        onSelect={handleSelect}
        onChange={setInputCode}
        style={{ width: 320 }}
        dropdownStyle={{
          backgroundColor: FUI_COLORS.bg.elevated,
          borderRadius: '6px',
          border: `1px solid ${FUI_COLORS.gold[400]}`,
          boxShadow: '0 4px 20px rgba(0, 0, 0, 0.5)',
        }}
        notFoundContent={isSearching ? <Spin size="small" /> : null}
      >
        <Input
          placeholder="输入股票代码或名称"
          prefix={<SearchOutlined style={{ color: FUI_COLORS.gold[400], fontSize: 16 }} />}
          onKeyDown={handleKeyDown}
          style={{
            backgroundColor: 'transparent',
            borderColor: FUI_COLORS.gold[400],
            borderRadius: 6,
            height: 44,
            color: FUI_COLORS.gold[400],
          }}
        />
      </AutoComplete>
    </Box>
  );
});

SearchBox.displayName = 'SearchBox';

/**
 * Company 页面顶部组件
 */
const CompanyHeader: React.FC<CompanyHeaderProps> = memo(({
  stockCode,
  onStockChange,
}) => {
  return (
    <Box
      position="relative"
      bg={FUI_COLORS.bg.primary}
      borderBottom="1px solid"
      borderColor={FUI_COLORS.line.default}
      px={6}
      py={4}
    >
      <Flex
        position="relative"
        zIndex={1}
        maxW="container.xl"
        mx="auto"
        justify="space-between"
        align="center"
      >
        {/* 左侧：页面标题 */}
        <PageTitle />

        {/* 右侧：搜索框 */}
        <SearchBox
          stockCode={stockCode}
          onStockChange={onStockChange}
        />
      </Flex>
    </Box>
  );
});

CompanyHeader.displayName = 'CompanyHeader';

export default CompanyHeader;
