import { useState, useMemo, useEffect, CSSProperties } from 'react';
import { Card, Row, Col, Avatar, Typography, Tag, Breadcrumb, Button, Radio, Descriptions, Spin, Alert, message } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { useNavigate, useParams } from 'react-router-dom';
import { useApi } from '@/hooks/useApi';
import { StockManagementService } from '@/services/stockManagement';
import { parseError } from '@/utils/errorHandler';
import { ROUTES } from '@/constants/routes';

interface SectorResponse {
  name?: string;
  description?: string | null;
  icon_url?: string | null;
  display_order?: number;
  id: string;
  created_at: string;
  updated_at: string;
}

interface ExchangeResponse {
  name?: string;
  code?: string;
  country?: string;
  timezone?: string;
  trading_hours?: string | null;
  currency?: string;
  website_url?: string | null;
  description?: string | null;
  id: string;
  created_at: string;
  updated_at: string;
}

interface StockDetailResponse {
  id: string;
  ticker_symbol: string;
  company_name: string;
  current_price?: number | null;
  opening_price?: number | null;
  closing_price?: number | null;
  high_price?: number | null;
  low_price?: number | null;
  volume?: number | null;
  market_cap?: number | null;
  industry?: string | null;
  currency: string;
  last_updated?: string | null;
  description?: string | null;
  logo_url?: string | null;
  website_url?: string | null;
  country?: string | null;
  ipo_date?: string | null;
  status: string;
  created_at: string;
  updated_at: string;
  sector: SectorResponse;
  exchange: ExchangeResponse;
}

interface StockHistoryItem {
  id: string;
  stock_id: string;
  date: string;
  open_price: number;
  close_price: number;
  high_price: number;
  low_price: number;
  volume: number;
  adjusted_close_price?: number | null;
  created_at: string;
  updated_at: string;
}

type TimeRange = '1m' | '3m' | '6m' | '1y' | 'all';

const StockDetailPage = () => {
  const navigate = useNavigate();
  const { stockId } = useParams<{ stockId: string }>();
  const [messageApi, contextHolder] = message.useMessage();

  const [stockDetail, setStockDetail] = useState<StockDetailResponse | null>(null);
  const [stockHistory, setStockHistory] = useState<StockHistoryItem[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [historyLoading, setHistoryLoading] = useState<boolean>(false);
  const [selectedTimeRange, setSelectedTimeRange] = useState<TimeRange>('3m');

  const { data: detailData, loading: detailLoading, error: detailError, execute: fetchDetail } = useApi(
    StockManagementService.getStocksDetails
  );

  const { data: historyData, loading: historyApiLoading, error: historyError, execute: fetchHistory } = useApi(
    StockManagementService.getStockHistory
  );

  useEffect(() => {
    if (stockId) {
      void fetchDetail(stockId);
    }
  }, [stockId, fetchDetail]);

  useEffect(() => {
    if (stockId) {
      setHistoryLoading(true);
      void fetchHistory({ stock_id: stockId, limit: 365, offset: 0 });
    }
  }, [stockId, fetchHistory]);

  useEffect(() => {
    if (detailData) {
      setStockDetail(detailData as StockDetailResponse);
      setLoading(false);
    }
  }, [detailData]);

  useEffect(() => {
    if (historyData) {
      setStockHistory(historyData as StockHistoryItem[]);
      setHistoryLoading(false);
    }
  }, [historyData]);

  useEffect(() => {
    if (detailError) {
      const { message: errorMessage } = parseError(detailError);
      messageApi.error(errorMessage || 'Failed to load stock details');
      setLoading(false);
    }
  }, [detailError, messageApi]);

  useEffect(() => {
    if (historyError) {
      const { message: errorMessage } = parseError(historyError);
      messageApi.error(errorMessage || 'Failed to load stock history');
      setHistoryLoading(false);
    }
  }, [historyError, messageApi]);

  const priceChange = useMemo(() => {
    return stockDetail && stockDetail.current_price && stockDetail.closing_price
      ? stockDetail.current_price - stockDetail.closing_price
      : 0;
  }, [stockDetail]);

  const priceChangePercent = useMemo(() => {
    return stockDetail && stockDetail.current_price && stockDetail.closing_price && stockDetail.closing_price !== 0
      ? ((stockDetail.current_price - stockDetail.closing_price) / stockDetail.closing_price) * 100
      : 0;
  }, [stockDetail]);

  const isPriceUp = useMemo(() => priceChange >= 0, [priceChange]);

  const formattedMarketCap = useMemo(() => {
    if (!stockDetail || !stockDetail.market_cap) return 'N/A';
    const cap = stockDetail.market_cap;
    if (cap >= 1e12) return (cap / 1e12).toFixed(2) + 'T';
    if (cap >= 1e9) return (cap / 1e9).toFixed(2) + 'B';
    if (cap >= 1e6) return (cap / 1e6).toFixed(2) + 'M';
    return cap.toLocaleString();
  }, [stockDetail]);

  const yearsSinceIPO = useMemo(() => {
    if (!stockDetail || !stockDetail.ipo_date) return null;
    return Math.floor((Date.now() - new Date(stockDetail.ipo_date).getTime()) / (365.25 * 24 * 60 * 60 * 1000));
  }, [stockDetail]);

  const weekHigh52 = useMemo(() => {
    return stockHistory.length > 0 ? Math.max(...stockHistory.map(h => h.high_price)) : null;
  }, [stockHistory]);

  const weekLow52 = useMemo(() => {
    return stockHistory.length > 0 ? Math.min(...stockHistory.map(h => h.low_price)) : null;
  }, [stockHistory]);

  const handleBackClick = () => {
    navigate(ROUTES.HOME);
  };

  const handleTimeRangeChange = (e: { target: { value: TimeRange } }) => {
    setSelectedTimeRange(e.target.value);
  };

  const breadcrumbItems = useMemo(() => [
    { title: 'Home', href: ROUTES.HOME },
    { title: 'Stocks', href: ROUTES.HOME },
    { title: stockDetail?.company_name || 'Loading...' }
  ], [stockDetail]);

  const mainContainerStyle: CSSProperties = {
    minHeight: '100vh',
    height: '100%',
    width: '100%',
    display: 'flex',
    flexDirection: 'column',
    padding: '24px',
    backgroundColor: '#f5f5f5'
  };

  const headerSectionStyle: CSSProperties = {
    display: 'flex',
    alignItems: 'center',
    gap: '16px',
    marginBottom: '24px'
  };

  const headerInfoStyle: CSSProperties = {
    flex: 1,
    display: 'flex',
    flexDirection: 'column',
    gap: '4px'
  };

  const priceSectionStyle: CSSProperties = {
    textAlign: 'right',
    display: 'flex',
    flexDirection: 'column',
    gap: '4px'
  };

  if (loading || detailLoading) {
    return (
      <div style={mainContainerStyle}>
        {contextHolder}
        <Spin size="large" style={{ margin: 'auto' }} />
      </div>
    );
  }

  if (detailError && !stockDetail) {
    return (
      <div style={mainContainerStyle}>
        {contextHolder}
        <Alert
          message="Error"
          description="Failed to load stock details"
          type="error"
          showIcon
        />
      </div>
    );
  }

  return (
    <div style={mainContainerStyle}>
      {contextHolder}
      
      <Breadcrumb items={breadcrumbItems} style={{ marginBottom: '16px' }} />
      
      <Button
        type="link"
        icon={<ArrowLeftOutlined />}
        onClick={handleBackClick}
        style={{ marginBottom: '16px', paddingLeft: '0' }}
      >
        Back to Stocks
      </Button>

      <div style={headerSectionStyle}>
        <Avatar
          size={64}
          shape="square"
          src={stockDetail?.logo_url}
          alt="Company Logo"
        >
          {stockDetail?.ticker_symbol?.charAt(0)}
        </Avatar>

        <div style={headerInfoStyle}>
          <Typography.Text type="secondary" strong style={{ fontSize: '14px' }}>
            {stockDetail?.ticker_symbol}
          </Typography.Text>
          <Typography.Title level={2} style={{ margin: '0' }}>
            {stockDetail?.company_name}
          </Typography.Title>
          <Tag color={stockDetail?.status === 'ACTIVE' ? 'green' : 'red'}>
            {stockDetail?.status}
          </Tag>
        </div>

        <div style={priceSectionStyle}>
          <Typography.Title level={1} style={{ margin: '0', fontSize: '36px' }}>
            {stockDetail?.currency} {stockDetail?.current_price?.toFixed(2) || 'N/A'}
          </Typography.Title>
          <Typography.Text
            style={{
              fontSize: '16px',
              fontWeight: '600',
              color: isPriceUp ? '#52c41a' : '#ff4d4f'
            }}
          >
            {isPriceUp ? '+' : ''}{priceChange.toFixed(2)} ({isPriceUp ? '+' : ''}{priceChangePercent.toFixed(2)}%)
          </Typography.Text>
        </div>
      </div>

      <div style={{ marginBottom: '24px' }}>
        <Row gutter={[16, 16]}>
          <Col xs={12} sm={12} md={6} lg={6}>
            <Card size="small" title="Opening Price">
              <Typography.Text strong>
                {stockDetail?.currency} {stockDetail?.opening_price?.toFixed(2) || 'N/A'}
              </Typography.Text>
            </Card>
          </Col>
          <Col xs={12} sm={12} md={6} lg={6}>
            <Card size="small" title="Closing Price">
              <Typography.Text strong>
                {stockDetail?.currency} {stockDetail?.closing_price?.toFixed(2) || 'N/A'}
              </Typography.Text>
            </Card>
          </Col>
          <Col xs={12} sm={12} md={6} lg={6}>
            <Card size="small" title="High Price">
              <Typography.Text strong>
                {stockDetail?.currency} {stockDetail?.high_price?.toFixed(2) || 'N/A'}
              </Typography.Text>
            </Card>
          </Col>
          <Col xs={12} sm={12} md={6} lg={6}>
            <Card size="small" title="Low Price">
              <Typography.Text strong>
                {stockDetail?.currency} {stockDetail?.low_price?.toFixed(2) || 'N/A'}
              </Typography.Text>
            </Card>
          </Col>
          <Col xs={12} sm={12} md={6} lg={6}>
            <Card size="small" title="Volume">
              <Typography.Text strong>
                {stockDetail?.volume?.toLocaleString() || 'N/A'}
              </Typography.Text>
            </Card>
          </Col>
          <Col xs={12} sm={12} md={6} lg={6}>
            <Card size="small" title="Market Cap">
              <Typography.Text strong>
                {stockDetail?.currency} {formattedMarketCap}
              </Typography.Text>
            </Card>
          </Col>
          <Col xs={12} sm={12} md={6} lg={6}>
            <Card size="small" title="52-Week High">
              <Typography.Text strong>
                {weekHigh52 ? `${stockDetail?.currency} ${weekHigh52.toFixed(2)}` : 'N/A'}
              </Typography.Text>
            </Card>
          </Col>
          <Col xs={12} sm={12} md={6} lg={6}>
            <Card size="small" title="52-Week Low">
              <Typography.Text strong>
                {weekLow52 ? `${stockDetail?.currency} ${weekLow52.toFixed(2)}` : 'N/A'}
              </Typography.Text>
            </Card>
          </Col>
        </Row>
      </div>

      <Card title="Price History" style={{ marginBottom: '24px' }}>
        <Radio.Group
          value={selectedTimeRange}
          onChange={handleTimeRangeChange}
          optionType="button"
          buttonStyle="solid"
          style={{ marginBottom: '16px' }}
        >
          <Radio.Button value="1m">1M</Radio.Button>
          <Radio.Button value="3m">3M</Radio.Button>
          <Radio.Button value="6m">6M</Radio.Button>
          <Radio.Button value="1y">1Y</Radio.Button>
          <Radio.Button value="all">All</Radio.Button>
        </Radio.Group>

        {historyLoading || historyApiLoading ? (
          <Spin />
        ) : stockHistory.length > 0 ? (
          <div style={{ height: '300px', width: '100%' }}>
            <Typography.Text type="secondary">
              Chart visualization would render here with {stockHistory.length} data points
            </Typography.Text>
          </div>
        ) : (
          <Typography.Text type="secondary">No historical data available</Typography.Text>
        )}
      </Card>

      <Card title="Company Information" style={{ marginBottom: '24px' }}>
        <Typography.Paragraph
          ellipsis={{ rows: 4, expandable: true, symbol: 'more' }}
          style={{ marginBottom: '16px' }}
        >
          {stockDetail?.description || 'No description available'}
        </Typography.Paragraph>

        <Descriptions bordered column={2} size="small">
          <Descriptions.Item label="Sector">
            {stockDetail?.sector?.name || 'N/A'}
          </Descriptions.Item>
          <Descriptions.Item label="Industry">
            {stockDetail?.industry || 'N/A'}
          </Descriptions.Item>
          <Descriptions.Item label="Exchange">
            {stockDetail?.exchange?.name || 'N/A'}
          </Descriptions.Item>
          <Descriptions.Item label="Exchange Code">
            {stockDetail?.exchange?.code || 'N/A'}
          </Descriptions.Item>
          <Descriptions.Item label="Currency">
            {stockDetail?.currency || 'N/A'}
          </Descriptions.Item>
          <Descriptions.Item label="Country">
            {stockDetail?.country || 'N/A'}
          </Descriptions.Item>
          <Descriptions.Item label="IPO Date">
            {stockDetail?.ipo_date || 'N/A'}
          </Descriptions.Item>
          <Descriptions.Item label="Years Since IPO">
            {yearsSinceIPO !== null ? `${yearsSinceIPO} years` : 'N/A'}
          </Descriptions.Item>
          <Descriptions.Item label="Status">
            {stockDetail?.status || 'N/A'}
          </Descriptions.Item>
        </Descriptions>

        {stockDetail?.website_url && (
          <Typography.Link
            href={stockDetail.website_url}
            target="_blank"
            rel="noopener noreferrer"
            style={{ marginTop: '12px', display: 'block' }}
          >
            Visit Company Website
          </Typography.Link>
        )}
      </Card>

      <Typography.Text
        type="secondary"
        style={{ marginTop: '16px', display: 'block', fontSize: '12px' }}
      >
        Last Updated: {stockDetail?.last_updated ? new Date(stockDetail.last_updated).toLocaleString() : 'N/A'}
      </Typography.Text>
    </div>
  );
};

export default StockDetailPage;