import { useState, useMemo } from 'react'
import type React from 'react'
import ReactApexChart from 'react-apexcharts'
import type { ApexOptions } from 'apexcharts'
import { TrendingUp, TrendingDown, Minus } from 'lucide-react'
import { marketPrices, priceHistory, globalComparison, monthlyExport } from '@/data/market'
import type { MarketPrice, PriceTrend } from '@/data/market'

/* ─── chart shared theme ─────────────────────────────────── */
const CHART_FONT = 'Vazir, sans-serif'
const GRID_COLOR = 'rgba(26,23,18,0.08)'
const LABEL_COLOR = '#766e68'

/* ─── time range filter ──────────────────────────────────── */
type Range = '1M' | '3M' | '6M' | '1Y'
const RANGES: { label: string; value: Range; months: number }[] = [
  { label: '۱ ماه', value: '1M', months: 1 },
  { label: '۳ ماه', value: '3M', months: 3 },
  { label: '۶ ماه', value: '6M', months: 6 },
  { label: '۱ سال', value: '1Y', months: 12 },
]

/* ─── trend icon ─────────────────────────────────────────── */
function TrendIcon({ trend }: { trend: PriceTrend }) {
  if (trend === 'up') return <TrendingUp size={12} />
  if (trend === 'down') return <TrendingDown size={12} />
  return <Minus size={12} />
}

/* ─── price card ─────────────────────────────────────────── */
function PriceCard({ item }: { item: MarketPrice }) {
  const isUp = item.trend === 'up'
  const isDown = item.trend === 'down'
  const trendColor = isUp ? 'var(--green-ink)' : isDown ? 'var(--red)' : 'var(--ink-4)'
  const trendBg = isUp
    ? 'rgba(22,101,52,0.08)'
    : isDown
    ? 'rgba(155,28,28,0.08)'
    : 'rgba(26,23,18,0.06)'

  return (
    <div
      style={{
        borderLeft: '1px solid var(--rule-thin)',
        padding: 32,
        display: 'flex',
        flexDirection: 'column',
        gap: 8,
      }}
    >
      <p style={{ fontSize: 13, color: 'var(--ink-3)', marginBottom: 4 }}>{item.name}</p>
      <p
        style={{
          fontSize: 28,
          fontWeight: 900,
          color: 'var(--ink)',
          lineHeight: 1,
          fontVariantNumeric: 'tabular-nums',
          letterSpacing: '-0.5px',
        }}
      >
        {item.value.toLocaleString('fa-IR')}
      </p>
      <p style={{ fontSize: 11, color: 'var(--ink-4)' }}>{item.unit}</p>

      {/* Change badge */}
      <div
        style={{
          display: 'inline-flex',
          alignItems: 'center',
          gap: 5,
          padding: '4px 10px',
          background: trendBg,
          color: trendColor,
          fontSize: 11,
          fontWeight: 700,
          width: 'fit-content',
          marginTop: 4,
        }}
      >
        <TrendIcon trend={item.trend} />
        <span>
          {item.changePercent > 0 ? '+' : ''}
          {item.changePercent.toFixed(1)}٪
        </span>
        <span style={{ color: trendColor, opacity: 0.7, fontSize: 10 }}>
          ({item.change > 0 ? '+' : ''}
          {item.change.toLocaleString('fa-IR')})
        </span>
      </div>
    </div>
  )
}

/* ─── comparison tool ────────────────────────────────────── */
function ComparisonTool() {
  const [productA, setProductA] = useState(marketPrices[0].id)
  const [productB, setProductB] = useState(marketPrices[1].id)

  const itemA = marketPrices.find((m) => m.id === productA)!
  const itemB = marketPrices.find((m) => m.id === productB)!

  const selectStyle: React.CSSProperties = {
    border: '1px solid var(--ink)',
    padding: '8px 14px',
    fontSize: 12,
    fontFamily: 'inherit',
    background: 'var(--paper)',
    color: 'var(--ink)',
    borderRadius: 0,
    cursor: 'pointer',
    outline: 'none',
    direction: 'rtl',
    flex: 1,
  }

  return (
    <div>
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: 16,
          marginBottom: 32,
          flexWrap: 'wrap',
        }}
      >
        <select
          value={productA}
          onChange={(e) => setProductA(e.target.value)}
          style={selectStyle}
        >
          {marketPrices.map((m) => (
            <option key={m.id} value={m.id}>
              {m.name}
            </option>
          ))}
        </select>
        <span
          style={{
            fontSize: 16,
            fontWeight: 900,
            color: 'var(--ink-4)',
            padding: '0 8px',
          }}
        >
          در برابر
        </span>
        <select
          value={productB}
          onChange={(e) => setProductB(e.target.value)}
          style={selectStyle}
        >
          {marketPrices.map((m) => (
            <option key={m.id} value={m.id}>
              {m.name}
            </option>
          ))}
        </select>
      </div>

      {/* Side-by-side comparison */}
      <div
        className="grid grid-cols-[1fr_auto_1fr] max-md:grid-cols-1 border border-[var(--rule-thin)]"
      >
        <div className="max-md:border-b max-md:border-[var(--rule-thin)]" style={{ padding: 32, textAlign: 'center' }}>
          <p style={{ fontSize: 13, color: 'var(--ink-3)', marginBottom: 8 }}>{itemA.name}</p>
          <p
            style={{
              fontSize: 32,
              fontWeight: 900,
              color: 'var(--ink)',
              lineHeight: 1,
            }}
          >
            {itemA.value.toLocaleString('fa-IR')}
          </p>
          <p style={{ fontSize: 11, color: 'var(--ink-5)', marginTop: 4 }}>{itemA.unit}</p>
          <div
            style={{
              display: 'inline-flex',
              alignItems: 'center',
              gap: 4,
              marginTop: 12,
              padding: '4px 12px',
              background:
                itemA.trend === 'up'
                  ? 'rgba(22,101,52,0.08)'
                  : itemA.trend === 'down'
                  ? 'rgba(155,28,28,0.08)'
                  : 'rgba(26,23,18,0.06)',
              color:
                itemA.trend === 'up'
                  ? 'var(--green-ink)'
                  : itemA.trend === 'down'
                  ? 'var(--red)'
                  : 'var(--ink-4)',
              fontSize: 12,
              fontWeight: 700,
            }}
          >
            <TrendIcon trend={itemA.trend} />
            {itemA.changePercent > 0 ? '+' : ''}
            {itemA.changePercent.toFixed(1)}٪
          </div>
        </div>

        {/* VS divider */}
        <div
          style={{
            width: 60,
          }}
          className="max-md:hidden border-r border-l border-[var(--rule-thin)] flex items-center justify-center"
        >
          <span
            style={{
              fontSize: 16,
              fontWeight: 900,
              color: 'var(--ink-4)',
              letterSpacing: '2px',
              writingMode: 'vertical-rl',
            }}
          >
            VS
          </span>
        </div>

        <div style={{ padding: 32, textAlign: 'center' }}>
          <p style={{ fontSize: 13, color: 'var(--ink-3)', marginBottom: 8 }}>{itemB.name}</p>
          <p
            style={{
              fontSize: 32,
              fontWeight: 900,
              color: 'var(--ink)',
              lineHeight: 1,
            }}
          >
            {itemB.value.toLocaleString('fa-IR')}
          </p>
          <p style={{ fontSize: 11, color: 'var(--ink-5)', marginTop: 4 }}>{itemB.unit}</p>
          <div
            style={{
              display: 'inline-flex',
              alignItems: 'center',
              gap: 4,
              marginTop: 12,
              padding: '4px 12px',
              background:
                itemB.trend === 'up'
                  ? 'rgba(22,101,52,0.08)'
                  : itemB.trend === 'down'
                  ? 'rgba(155,28,28,0.08)'
                  : 'rgba(26,23,18,0.06)',
              color:
                itemB.trend === 'up'
                  ? 'var(--green-ink)'
                  : itemB.trend === 'down'
                  ? 'var(--red)'
                  : 'var(--ink-4)',
              fontSize: 12,
              fontWeight: 700,
            }}
          >
            <TrendIcon trend={itemB.trend} />
            {itemB.changePercent > 0 ? '+' : ''}
            {itemB.changePercent.toFixed(1)}٪
          </div>
        </div>
      </div>

      <p
        style={{
          fontSize: 11,
          color: 'var(--ink-5)',
          textAlign: 'center',
          marginTop: 16,
          fontStyle: 'italic',
        }}
      >
        نمودار مقایسه‌ای در نسخه‌های آینده تکمیل می‌شود
      </p>
    </div>
  )
}

/* ─── main component ─────────────────────────────────────── */
export default function Market() {
  const [priceRange, setPriceRange] = useState<Range>('1Y')

  /* Filter price history based on selected range */
  const filteredHistory = useMemo(() => {
    const range = RANGES.find((r) => r.value === priceRange)!
    return priceHistory.slice(-range.months)
  }, [priceRange])

  /* Line chart options */
  const lineOptions: ApexOptions = {
    chart: {
      type: 'area',
      toolbar: { show: false },
      fontFamily: CHART_FONT,
      background: 'transparent',
      animations: { enabled: true, speed: 400 },
    },
    colors: ['#9b1c1c'],
    stroke: { width: 2, curve: 'smooth' },
    fill: {
      type: 'gradient',
      gradient: {
        shadeIntensity: 1,
        opacityFrom: 0.15,
        opacityTo: 0,
        stops: [0, 100],
      },
    },
    grid: {
      borderColor: GRID_COLOR,
      strokeDashArray: 3,
    },
    xaxis: {
      categories: filteredHistory.map((p) => p.month),
      labels: {
        style: { fontFamily: CHART_FONT, colors: LABEL_COLOR, fontSize: '11px' },
        rotate: -35,
      },
      axisBorder: { color: GRID_COLOR },
      axisTicks: { color: GRID_COLOR },
    },
    yaxis: {
      opposite: true,
      labels: {
        style: { fontFamily: CHART_FONT, colors: LABEL_COLOR, fontSize: '11px' },
        formatter: (val: number) => val.toLocaleString('fa-IR'),
      },
    },
    tooltip: {
      theme: 'light',
      style: { fontFamily: CHART_FONT, fontSize: '12px' },
      y: { formatter: (val: number) => val.toLocaleString('fa-IR') + ' تومان/کیلو' },
    },
    dataLabels: { enabled: false },
  }

  const lineSeries = [
    {
      name: 'شمش فولاد',
      data: filteredHistory.map((p) => p.price),
    },
  ]

  /* Bar chart options */
  const barOptions: ApexOptions = {
    chart: {
      type: 'bar',
      toolbar: { show: false },
      fontFamily: CHART_FONT,
      background: 'transparent',
      animations: { enabled: true, speed: 400 },
    },
    colors: ['#2e2a25'],
    plotOptions: {
      bar: {
        borderRadius: 0,
        columnWidth: '65%',
      },
    },
    grid: {
      borderColor: GRID_COLOR,
      strokeDashArray: 3,
    },
    xaxis: {
      categories: monthlyExport.map((e) => e.month),
      labels: {
        style: { fontFamily: CHART_FONT, colors: LABEL_COLOR, fontSize: '11px' },
        rotate: -35,
      },
      axisBorder: { color: GRID_COLOR },
      axisTicks: { color: GRID_COLOR },
    },
    yaxis: {
      opposite: true,
      labels: {
        style: { fontFamily: CHART_FONT, colors: LABEL_COLOR, fontSize: '11px' },
        formatter: (val: number) => (val / 1000).toFixed(0) + 'k',
      },
    },
    tooltip: {
      theme: 'light',
      style: { fontFamily: CHART_FONT, fontSize: '12px' },
      y: {
        formatter: (val: number) =>
          (val / 1000).toLocaleString('fa-IR') + ' هزار تن',
      },
    },
    dataLabels: { enabled: false },
  }

  const barSeries = [
    {
      name: 'صادرات',
      data: monthlyExport.map((e) => e.tonnage),
    },
  ]

  /* Section heading style */
  const SectionHeading = ({
    title,
    subtitle,
    children,
  }: {
    title: string
    subtitle?: string
    children?: React.ReactNode
  }) => (
    <div
      style={{
        display: 'flex',
        alignItems: 'flex-end',
        justifyContent: 'space-between',
        marginBottom: 32,
        flexWrap: 'wrap',
        gap: 12,
      }}
    >
      <div>
        <h2
          style={{
            fontSize: 22,
            fontWeight: 900,
            color: 'var(--ink)',
            letterSpacing: '-0.5px',
          }}
        >
          {title}
        </h2>
        {subtitle && (
          <p style={{ fontSize: 12, color: 'var(--ink-5)', marginTop: 4 }}>{subtitle}</p>
        )}
      </div>
      {children}
    </div>
  )

  return (
    <div style={{ direction: 'rtl' }}>
      {/* ─── Page Header ───────────────────────────────── */}
      <div
        style={{
          maxWidth: 1280,
          margin: '0 auto',
          padding: '48px 48px 32px',
          borderBottom: '3px solid var(--ink)',
        }}
      >
        <div
          style={{
            display: 'flex',
            alignItems: 'flex-end',
            justifyContent: 'space-between',
            flexWrap: 'wrap',
            gap: 16,
          }}
        >
          <div>
            <h1
              style={{
                fontSize: 36,
                fontWeight: 900,
                letterSpacing: '-1px',
                color: 'var(--ink)',
                marginBottom: 6,
              }}
            >
              داشبورد بازار
            </h1>
            <p style={{ fontSize: 15, fontWeight: 300, color: 'var(--ink-3)' }}>
              قیمت‌های لحظه‌ای، روند تاریخی و تحلیل صادرات فولاد ایران
            </p>
          </div>
          <div
            style={{
              fontSize: 11,
              color: 'var(--ink-5)',
              border: '1px solid var(--rule-thin)',
              padding: '6px 14px',
              display: 'flex',
              alignItems: 'center',
              gap: 8,
            }}
          >
            <span
              style={{
                width: 7,
                height: 7,
                borderRadius: '50%',
                background: 'var(--green-ink)',
                display: 'inline-block',
              }}
            />
            آخرین بروزرسانی: ۴ خرداد ۱۴۰۴
          </div>
        </div>
      </div>

      {/* ─── Section 1: Price Grid ──────────────────────── */}
      <div
        style={{
          borderBottom: '2px solid var(--ink)',
          padding: '48px 0',
        }}
      >
        <div style={{ maxWidth: 1280, margin: '0 auto', padding: '0 48px' }}>
          <SectionHeading
            title="قیمت‌های امروز"
            subtitle="قیمت بازار داخلی — تومان به کیلوگرم / دلار به تن"
          />
          <div
            className="grid grid-cols-4 max-lg:grid-cols-2 max-sm:grid-cols-1 border-t border-r border-[var(--rule-thin)] price-grid"
          >
            {marketPrices.map((item) => (
              <PriceCard key={item.id} item={item} />
            ))}
          </div>
        </div>
      </div>

      {/* ─── Section 2: Price History Chart ────────────── */}
      <div
        style={{
          borderBottom: '2px solid var(--ink)',
          padding: '64px 0',
        }}
      >
        <div style={{ maxWidth: 1280, margin: '0 auto', padding: '0 48px' }}>
          <SectionHeading
            title="روند قیمت شمش فولاد"
            subtitle="تومان به کیلوگرم"
          >
            {/* Range selector */}
            <div style={{ display: 'flex', gap: 0 }}>
              {RANGES.map((r, rIdx) => (
                <button
                  key={r.value}
                  onClick={() => setPriceRange(r.value)}
                  style={{
                    padding: '6px 16px',
                    fontSize: 11,
                    fontWeight: 700,
                    border: '1px solid var(--ink)',
                    borderLeft: rIdx === 0 ? '1px solid var(--ink)' : 'none',
                    background: priceRange === r.value ? 'var(--ink)' : 'transparent',
                    color: priceRange === r.value ? 'var(--paper)' : 'var(--ink)',
                    cursor: 'pointer',
                    fontFamily: 'inherit',
                    borderRadius: 0,
                    transition: 'all 120ms',
                  }}
                >
                  {r.label}
                </button>
              ))}
            </div>
          </SectionHeading>

          <div
            style={{
              border: '1px solid var(--rule-thin)',
              padding: '24px 8px 8px',
              background: 'var(--paper)',
            }}
          >
            <ReactApexChart
              options={lineOptions}
              series={lineSeries}
              type="area"
              height={320}
            />
          </div>
        </div>
      </div>

      {/* ─── Section 3: Global Comparison Table ─────────── */}
      <div
        style={{
          borderBottom: '2px solid var(--ink)',
          padding: '64px 0',
        }}
      >
        <div style={{ maxWidth: 1280, margin: '0 auto', padding: '0 48px' }}>
          <SectionHeading
            title="مقایسه جهانی"
            subtitle="قیمت شمش فولاد در بازارهای اصلی"
          />
          <table
            style={{
              borderCollapse: 'collapse',
              width: '100%',
              fontSize: 13,
            }}
          >
            <thead>
              <tr style={{ background: 'var(--ink)', color: 'var(--paper)' }}>
                {['کشور', 'قیمت شمش (دلار/تن)', 'ارز', 'مقایسه با ایران'].map((h) => (
                  <th
                    key={h}
                    style={{
                      padding: '14px 20px',
                      textAlign: 'right',
                      fontWeight: 700,
                      fontSize: 11,
                      letterSpacing: '0.5px',
                      textTransform: 'uppercase',
                    }}
                  >
                    {h}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {globalComparison.map((item, i) => {
                const isIran = item.country === 'ایران'
                return (
                  <tr
                    key={item.country}
                    style={{
                      background: i % 2 === 0 ? 'var(--paper)' : 'var(--paper-2)',
                      borderBottom: '1px solid var(--rule-thin)',
                    }}
                  >
                    <td style={{ padding: '14px 20px', fontWeight: isIran ? 700 : 400 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <span style={{ fontSize: 18 }}>{item.flag}</span>
                        {item.country}
                        {isIran && (
                          <span
                            style={{
                              fontSize: 9,
                              fontWeight: 700,
                              color: 'var(--paper)',
                              background: 'var(--red)',
                              padding: '2px 6px',
                              letterSpacing: '1px',
                            }}
                          >
                            ایران
                          </span>
                        )}
                      </div>
                    </td>
                    <td style={{ padding: '14px 20px', fontWeight: 700 }}>
                      {item.currency === 'USD'
                        ? `$${item.price.toLocaleString()}`
                        : item.price.toLocaleString('fa-IR') + ' تومان/کیلو'}
                    </td>
                    <td style={{ padding: '14px 20px', color: 'var(--ink-4)' }}>
                      {item.currency}
                    </td>
                    <td style={{ padding: '14px 20px' }}>
                      {isIran ? (
                        <span
                          style={{
                            fontSize: 10,
                            color: 'var(--ink-5)',
                            fontStyle: 'italic',
                          }}
                        >
                          مبنا
                        </span>
                      ) : (
                        <span
                          style={{
                            fontSize: 11,
                            fontWeight: 600,
                            color: item.price > 500 ? 'var(--green-ink)' : 'var(--red)',
                          }}
                        >
                          {item.price > 500 ? 'بالاتر از میانگین' : 'پایین‌تر از میانگین'}
                        </span>
                      )}
                    </td>
                  </tr>
                )
              })}
            </tbody>
          </table>
        </div>
      </div>

      {/* ─── Section 4: Export Bar Chart ─────────────────── */}
      <div
        style={{
          borderBottom: '2px solid var(--ink)',
          padding: '64px 0',
        }}
      >
        <div style={{ maxWidth: 1280, margin: '0 auto', padding: '0 48px' }}>
          <SectionHeading
            title="صادرات ماهانه"
            subtitle="هزار تن — بر اساس داده‌های گمرک ایران"
          />
          <div
            style={{
              border: '1px solid var(--rule-thin)',
              padding: '24px 8px 8px',
              background: 'var(--paper)',
            }}
          >
            <ReactApexChart options={barOptions} series={barSeries} type="bar" height={280} />
          </div>
        </div>
      </div>

      {/* ─── Section 5: Comparison Tool ──────────────────── */}
      <div style={{ padding: '64px 0' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto', padding: '0 48px' }}>
          <SectionHeading
            title="ابزار مقایسه"
            subtitle="مقایسه قیمت لحظه‌ای دو محصول"
          />
          <ComparisonTool />
        </div>
      </div>

      {/* ─── Responsive styles ─────────────────────────── */}
      <style>{`
        @media (max-width: 767px) {
          .price-grid {
            grid-template-columns: 1fr 1fr !important;
          }
        }
        @media (max-width: 480px) {
          .price-grid {
            grid-template-columns: 1fr !important;
          }
        }
      `}</style>
    </div>
  )
}
