import React, { useEffect, useState } from 'react';
import {
  Area,
  AreaChart,
  CartesianGrid,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts';
import { ChevronDown, ChevronUp, ExternalLink } from 'lucide-react';
import { Company, CompanyPriceChartRange, CompanyPricePoint } from '../../types/financial';
import {
  CompanyIdentity,
  PriceDisplay,
  MetricGrid,
  SectionTitle,
  ExpandableText,
  InlineTable,
} from '../ui';

interface CompanyPanelProps {
  company: Company;
}

const chartRangeOrder: CompanyPriceChartRange[] = ['1D', '5D', '1M', '6M', 'YTD', '1Y', '5Y', 'MAX'];

const formatCurrency = (value: number) => {
  if (value >= 1e12) return `$${(value / 1e12).toFixed(2)}T`;
  if (value >= 1e9) return `$${(value / 1e9).toFixed(2)}B`;
  if (value >= 1e6) return `$${(value / 1e6).toFixed(2)}M`;
  return `$${value.toFixed(2)}`;
};

const formatCompactNumber = (value: number) =>
  new Intl.NumberFormat('en-US', {
    notation: 'compact',
    maximumFractionDigits: value >= 10_000 ? 1 : 0,
  }).format(value);

const marketTimeZone = 'America/New_York';

const getPointDate = (point: CompanyPricePoint) => {
  if (!point.timestamp) {
    return null;
  }

  const value = new Date(point.timestamp);
  return Number.isNaN(value.getTime()) ? null : value;
};

const formatPointLabel = (point: CompanyPricePoint, range: CompanyPriceChartRange | null) => {
  const date = getPointDate(point);
  if (!date) {
    return point.label;
  }

  switch (range) {
    case '1D':
      return new Intl.DateTimeFormat('en-US', {
        hour: 'numeric',
        minute: '2-digit',
        hour12: false,
        timeZone: marketTimeZone,
      }).format(date);
    case '5D':
      return new Intl.DateTimeFormat('en-US', {
        weekday: 'short',
        day: 'numeric',
        timeZone: marketTimeZone,
      }).format(date);
    case '1M':
    case '6M':
    case 'YTD':
    case '1Y':
      return new Intl.DateTimeFormat('en-US', {
        month: 'short',
        day: 'numeric',
        timeZone: marketTimeZone,
      }).format(date);
    case '5Y':
    case 'MAX':
      return new Intl.DateTimeFormat('en-US', {
        month: 'short',
        year: 'numeric',
        timeZone: marketTimeZone,
      }).format(date);
    default:
      return point.label;
  }
};

const ChartTooltip = ({
  active,
  payload,
  selectedRange,
}: {
  active?: boolean;
  payload?: Array<{ value?: number | string; payload?: CompanyPricePoint }>;
  selectedRange: CompanyPriceChartRange | null;
}) => {
  const point = payload?.[0]?.payload;
  if (!active || !payload?.length || payload[0]?.value == null || !point) {
    return null;
  }

  return (
    <div className="border border-term-border bg-term-surface px-3 py-2 font-mono shadow-lg">
      <div className="text-[10px] uppercase tracking-wider text-term-text-tertiary">
        {formatPointLabel(point, selectedRange)}
      </div>
      <div className="mt-1 text-sm text-term-text">
        ${typeof payload[0].value === 'number' ? payload[0].value.toFixed(2) : payload[0].value}
      </div>
    </div>
  );
};

export const CompanyPanel: React.FC<CompanyPanelProps> = ({ company }) => {
  const [showAllMetrics, setShowAllMetrics] = useState(false);
  const [selectedRange, setSelectedRange] = useState<CompanyPriceChartRange>('1D');

  const profile = company.profile;
  const chartColor = company.change >= 0 ? 'var(--semantic-positive)' : 'var(--semantic-negative)';
  const rangeMap = company.priceChartRanges;
  const availableRanges = chartRangeOrder.filter((range) => (rangeMap?.[range]?.length ?? 0) > 1);
  const availableRangeKey = availableRanges.join('|');
  const fallbackRange = availableRanges[0] ?? (company.priceChart?.length ? '1D' : null);

  useEffect(() => {
    if (!fallbackRange) {
      return;
    }

    if (!availableRanges.includes(selectedRange)) {
      setSelectedRange(fallbackRange);
    }
  }, [availableRangeKey, fallbackRange, selectedRange]);

  const activeRange = availableRanges.includes(selectedRange) ? selectedRange : fallbackRange;
  const chartPoints =
    (activeRange && rangeMap?.[activeRange]?.length ? rangeMap[activeRange] : null) ??
    company.priceChart ??
    [];
  const chartSeries = chartPoints.map((point) => ({
    ...point,
    displayLabel: formatPointLabel(point, activeRange),
  }));
  const chartVisible = chartPoints.length > 1;
  const chartPrices = chartVisible ? chartPoints.map((point) => point.price) : [];
  const minChartPrice = chartVisible ? Math.min(...chartPrices) : null;
  const maxChartPrice = chartVisible ? Math.max(...chartPrices) : null;
  const yAxisDomain =
    minChartPrice != null && maxChartPrice != null
      ? [
          Math.max(0, minChartPrice - Math.max((maxChartPrice - minChartPrice) * 0.15, 1)),
          maxChartPrice + Math.max((maxChartPrice - minChartPrice) * 0.15, 1),
        ]
      : ['auto', 'auto'] as [number | 'auto', number | 'auto'];

  const allMetrics: Array<{ label: string; value: string }> = [
    { label: 'Market Cap', value: formatCurrency(company.marketCap) },
  ];

  if (company.volume != null) {
    allMetrics.push({
      label: company.volumeLabel ?? 'Volume',
      value: formatCompactNumber(company.volume),
    });
  }

  if (company.pe != null) {
    allMetrics.push({ label: 'P/E Ratio', value: company.pe.toFixed(1) });
  }

  if (company.eps != null) {
    allMetrics.push({ label: 'EPS', value: `$${company.eps.toFixed(2)}` });
  }

  if (company.high52Week != null) {
    allMetrics.push({ label: '52W High', value: `$${company.high52Week.toFixed(2)}` });
  }

  if (company.low52Week != null) {
    allMetrics.push({ label: '52W Low', value: `$${company.low52Week.toFixed(2)}` });
  }

  const visibleMetrics = showAllMetrics ? allMetrics : allMetrics.slice(0, 4);

  const detailsRows: Array<{ label: string; value: string; href?: string }> = [];

  if (profile?.ceo) {
    detailsRows.push({ label: 'CEO', value: profile.ceo });
  }

  if (profile?.employees != null) {
    detailsRows.push({ label: 'Employees', value: formatCompactNumber(profile.employees) });
  }

  if (profile?.founded) {
    detailsRows.push({ label: 'Founded', value: String(profile.founded) });
  }

  if (profile?.headquarters) {
    detailsRows.push({ label: 'Headquarters', value: profile.headquarters });
  }

  if (profile?.sector) {
    detailsRows.push({ label: 'Sector', value: profile.sector });
  }

  if (profile?.website) {
    detailsRows.push({
      label: 'Website',
      value: profile.website.replace(/^https?:\/\//, '').replace(/\/$/, ''),
      href: profile.website,
    });
  }

  return (
    <div className="company-panel space-y-6 py-4 overflow-auto">
      {/* Header Section */}
      <section className="company-header">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <CompanyIdentity
            name={company.name}
            symbol={company.symbol}
            sector={profile?.sector}
            headquarters={profile?.headquarters}
          />
          <PriceDisplay
            price={company.price}
            change={company.change}
            changePercent={company.changePercent}
            inline
          />
        </div>
      </section>

      {/* Chart Section */}
      {chartVisible && (
        <section className="chart-section border-b border-term-border-subtle pb-6">
          <div className="flex items-center justify-between mb-4">
            <div>
              <div className="text-[11px] font-mono uppercase tracking-wider text-term-text-tertiary">Price Chart</div>
              <div className="mt-1 text-xs font-mono text-term-text-muted">
                {activeRange ? `${activeRange} · ` : ''}
                {chartPoints[0] ? formatPointLabel(chartPoints[0], activeRange) : ''}
                {' — '}
                {chartPoints[chartPoints.length - 1]
                  ? formatPointLabel(chartPoints[chartPoints.length - 1], activeRange)
                  : ''}
              </div>
            </div>
            <div className="text-right font-mono">
              <div className="text-[10px] uppercase tracking-wide text-term-text-tertiary">Range</div>
              <div className="mt-1 text-sm text-term-text">
                ${minChartPrice?.toFixed(2)} — ${maxChartPrice?.toFixed(2)}
              </div>
            </div>
          </div>

          {availableRanges.length > 1 && (
            <div className="mb-4 flex flex-wrap gap-2">
              {availableRanges.map((range) => {
                const isActive = range === activeRange;

                return (
                  <button
                    key={range}
                    className={`min-w-[48px] border px-3 py-1.5 text-[11px] font-mono uppercase tracking-wide transition-colors ${
                      isActive
                        ? 'border-info bg-[var(--term-status-info)] text-[var(--term-status-info-strong)]'
                        : 'border-term-border bg-term-surface text-term-text-tertiary hover:border-term-border-focus hover:text-term-text'
                    }`}
                    onClick={() => setSelectedRange(range)}
                    type="button"
                  >
                    {range}
                  </button>
                );
              })}
            </div>
          )}

          <div className="h-64">
            <ResponsiveContainer width="100%" height="100%">
              <AreaChart
                key={activeRange ?? 'default'}
                data={chartSeries}
                margin={{ top: 16, right: 10, bottom: 6, left: 0 }}
              >
                <defs>
                  <linearGradient id={`company-chart-${company.symbol}`} x1="0" x2="0" y1="0" y2="1">
                    <stop offset="0%" stopColor={chartColor} stopOpacity={0.3} />
                    <stop offset="100%" stopColor={chartColor} stopOpacity={0} />
                  </linearGradient>
                </defs>
                <CartesianGrid stroke={"var(--term-border-subtle)"} strokeDasharray="3 6" vertical={false} />
                <XAxis
                  axisLine={false}
                  dataKey="displayLabel"
                  minTickGap={48}
                  tick={{ fill: "var(--term-text-muted)", fontFamily: 'ui-monospace, SFMono-Regular, monospace', fontSize: 10 }}
                  tickLine={false}
                />
                <YAxis
                  axisLine={false}
                  domain={yAxisDomain as [string | number, string | number]}
                  orientation="right"
                  tick={{ fill: "var(--term-text-muted)", fontFamily: 'ui-monospace, SFMono-Regular, monospace', fontSize: 10 }}
                  tickFormatter={(value: number) => `$${value.toFixed(0)}`}
                  tickLine={false}
                  width={56}
                />
                <Tooltip
                  content={<ChartTooltip selectedRange={activeRange} />}
                  cursor={{ stroke: "var(--term-border)", strokeDasharray: '3 4' }}
                />
                <Area
                  activeDot={{ fill: chartColor, r: 4, stroke: 'var(--term-bg-surface)', strokeWidth: 2 }}
                  dataKey="price"
                  fill={`url(#company-chart-${company.symbol})`}
                  isAnimationActive={false}
                  stroke={chartColor}
                  strokeWidth={2}
                  type="monotone"
                />
              </AreaChart>
            </ResponsiveContainer>
          </div>
        </section>
      )}

      {/* Key Metrics */}
      <section className="metrics-section">
        <div className="flex items-center justify-between mb-3">
          <SectionTitle>Key Metrics</SectionTitle>
          {allMetrics.length > 4 && (
            <button
              onClick={() => setShowAllMetrics(!showAllMetrics)}
              className="flex items-center gap-1 text-xs font-mono text-term-text-muted transition-colors hover:text-term-text"
            >
              {showAllMetrics ? (
                <>
                  <span>Show less</span>
                  <ChevronUp className="h-3 w-3" />
                </>
              ) : (
                <>
                  <span>Show all ({allMetrics.length})</span>
                  <ChevronDown className="h-3 w-3" />
                </>
              )}
            </button>
          )}
        </div>

        <MetricGrid metrics={visibleMetrics} columns={4} />
      </section>

      {/* Description */}
      {profile?.description && (
        <section className="description-section border-t border-term-border-subtle pt-4">
          <SectionTitle>Overview</SectionTitle>
          <ExpandableText text={profile.description} />
          {profile.wikiUrl && (
            <a
              className="mt-3 inline-flex items-center gap-1 text-sm font-mono text-info transition-colors hover:text-term-text"
              href={profile.wikiUrl}
              rel="noreferrer"
              target="_blank"
            >
              <span>Wikipedia</span>
              <ExternalLink className="h-3 w-3" />
            </a>
          )}
        </section>
      )}

      {/* Company Details */}
      {detailsRows.length > 0 && (
        <section className="details-section border-t border-term-border-subtle pt-4">
          <SectionTitle>Company Details</SectionTitle>
          <InlineTable rows={detailsRows} columns={2} />
        </section>
      )}
    </div>
  );
};
