import { useState, useEffect } from "react"
import {
  BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer,
  PieChart, Pie, Cell, LineChart, Line, LabelList,
} from "recharts"
import { financeApi } from "../../api/finance"

const CATEGORY_COLORS = {
  "Жильё": "#ef4444",
  "Еда": "#f97316",
  "Транспорт": "#6366f1",
  "Одежда": "#8b5cf6",
  "Здоровье": "#22c55e",
  "Развлечения": "#ec4899",
  "Связь / Подписки": "#0ea5e9",
  "Путешествия": "#14b8a6",
  "Подарки": "#a855f7",
  "Бытовое": "#64748b",
  "Маркетплейсы": "#F7B538",
  "Накопления": "#0D4F4F",
  "Другое": "#78716c",
  "Красота": "#f472b6",
}

const COLORS_FALLBACK = [
  "#6366f1", "#22c55e", "#ef4444", "#f97316", "#8b5cf6",
  "#0ea5e9", "#ec4899", "#14b8a6", "#64748b", "#a855f7",
]

const getColor = (name, i) => {
  const clean = name.replace(/^[\p{Emoji}\s]+/u, "").trim()
  return CATEGORY_COLORS[clean] || COLORS_FALLBACK[i % COLORS_FALLBACK.length]
}

const fmt = (n) => Number(n).toLocaleString("ru-RU") + " ₽"
const fmtShort = (n) => {
  if (n >= 1000) return Math.round(n / 1000).toLocaleString("ru-RU") + "к"
  return n.toLocaleString("ru-RU")
}

const MONTH_NAMES = [
  "", "Янв", "Фев", "Мар", "Апр", "Май", "Июн",
  "Июл", "Авг", "Сен", "Окт", "Ноя", "Дек",
]

const SAVINGS_NAMES = ["накопления"]

const CustomTooltip = ({ active, payload, label }) => {
  if (!active || !payload?.length) return null
  return (
    <div className="bg-gray-900 text-white text-xs px-3 py-2 rounded-lg shadow-lg">
      {payload.map((p, i) => (
        <div key={i}>
          <span className="font-medium">{p.name || label}: </span>
          <span>{fmt(p.value)}</span>
        </div>
      ))}
    </div>
  )
}

const BarLabel = ({ x, y, width, height, value }) => {
  if (!value) return null
  return (
    <text x={x + width + 6} y={y + height / 2} dy={4} fontSize={11} fill="#94a3b8">
      {fmtShort(value)}
    </text>
  )
}

export default function FinanceAnalytics({ month, year }) {
  const [analytics, setAnalytics] = useState(null)
  const [summary, setSummary] = useState(null)
  const [loading, setLoading] = useState(true)
  const [showSavings, setShowSavings] = useState(false)

  useEffect(() => {
    setLoading(true)
    Promise.all([
      financeApi.getAnalytics({ months: 6, month, year }),
      financeApi.getSummary({ month, year }),
    ])
      .then(([a, s]) => {
        setAnalytics(a)
        setSummary(s)
      })
      .catch(console.error)
      .finally(() => setLoading(false))
  }, [month, year])

  if (loading) {
    return (
      <div className="space-y-4">
        {[1, 2, 3].map((i) => (
          <div key={i} className="card p-8 animate-pulse">
            <div className="h-40 bg-gray-200 dark:bg-gray-800 rounded" />
          </div>
        ))}
      </div>
    )
  }

  if (!analytics || !summary) return null

  const allExpenseCategories = (summary.by_category || []).filter(
    (c) => c.type === "expense"
  )
  const isSavings = (c) =>
    SAVINGS_NAMES.includes(c.category_name?.toLowerCase?.())
  
  const expenseCategories = showSavings
    ? allExpenseCategories
    : allExpenseCategories.filter((c) => !isSavings(c))
  
  const hasSavings = allExpenseCategories.some(isSavings)

  const barData = expenseCategories
    .sort((a, b) => b.amount - a.amount)
    .map((c, i) => ({
      name: (c.category_emoji || "") + " " + c.category_name,
      shortName: c.category_name?.length > 10
        ? c.category_name.slice(0, 10) + "…"
        : c.category_name,
      value: c.amount,
      fill: getColor(c.category_name, i),
    }))

  const pieData = barData

  const filteredTotal = expenseCategories.reduce((s, c) => s + c.amount, 0)

  const monthlyData = (analytics.monthly_trend || []).map((m) => ({
    month: MONTH_NAMES[parseInt(m.month.slice(5))] || m.month,
    income: m.income,
    expense: m.expense,
  }))

  const comp = analytics.comparison_prev_month
  const diffPct = Math.abs(Math.round(comp?.diff_percent || 0))
  const isUp = (comp?.diff_percent || 0) > 0

  const barChartHeight = Math.max(400, barData.length * 44)

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-2 gap-3">
        <div className="card p-4">
          <p className="text-xs text-gray-500 dark:text-gray-400">
            Всего расходов
          </p>
          <p className="text-xl font-bold text-gray-900 dark:text-white">
            {fmt(summary.total_expense)}
          </p>
          <p
            className={`text-xs mt-1 ${isUp ? "text-red-500" : "text-green-500"}`}
          >
            {isUp ? "↑" : "↓"} {diffPct}% vs пред. месяц
          </p>
        </div>
        <div className="card p-4">
          <p className="text-xs text-gray-500 dark:text-gray-400">
            В среднем / день
          </p>
          <p className="text-xl font-bold text-gray-900 dark:text-white">
            {fmt(Math.round(analytics.avg_daily_expense))}
          </p>
        </div>
      </div>

      {barData.length > 0 && (
        <div className="card p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-display font-bold text-gray-900 dark:text-white">
              Расходы по категориям
            </h3>
            {hasSavings && (
              <button
                onClick={() => setShowSavings(!showSavings)}
                className="text-xs px-2 py-1 rounded-full bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400"
              >
                {showSavings ? "Скрыть" : "Показать"} накопления
              </button>
            )}
          </div>
          <div style={{ height: barChartHeight }}>
            <ResponsiveContainer>
              <BarChart data={barData} layout="vertical" margin={{ left: 0, right: 50 }}>
                <XAxis
                  type="number"
                  tick={{ fontSize: 10 }}
                  stroke="#94a3b8"
                  tickFormatter={fmtShort}
                />
                <YAxis
                  type="category"
                  dataKey="name"
                  tick={{ fontSize: 11 }}
                  stroke="#94a3b8"
                  width={130}
                />
                <Tooltip content={<CustomTooltip />} />
                <Bar dataKey="value" radius={[0, 6, 6, 0]} barSize={24}>
                  {barData.map((entry, i) => (
                    <Cell key={i} fill={entry.fill} />
                  ))}
                  <LabelList content={<BarLabel />} />
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>
      )}

      {pieData.length > 0 && (
        <div className="card p-5">
          <h3 className="font-display font-bold text-gray-900 dark:text-white mb-4">
            Доля категорий
          </h3>
          <div className="flex items-start gap-4">
            <div className="w-44 h-44 flex-shrink-0">
              <ResponsiveContainer>
                <PieChart>
                  <Pie
                    data={pieData}
                    innerRadius={45}
                    outerRadius={75}
                    dataKey="value"
                    stroke="none"
                  >
                    {pieData.map((entry, i) => (
                      <Cell key={i} fill={entry.fill} />
                    ))}
                  </Pie>
                  <Tooltip content={<CustomTooltip />} />
                </PieChart>
              </ResponsiveContainer>
            </div>
            <div className="space-y-1.5 pt-2 min-w-0 flex-1">
              {pieData.map((c, i) => (
                <div key={i} className="flex items-center gap-2 text-xs">
                  <div
                    className="w-2.5 h-2.5 rounded-full flex-shrink-0"
                    style={{ backgroundColor: c.fill }}
                  />
                  <span className="text-gray-600 dark:text-gray-400 truncate">
                    {c.name}
                  </span>
                  <span className="ml-auto font-semibold text-gray-900 dark:text-white whitespace-nowrap">
                    {Math.round(
                      (c.value / filteredTotal) * 100
                    )}%
                  </span>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {monthlyData.length > 0 && (
        <div className="card p-5">
          <h3 className="font-display font-bold text-gray-900 dark:text-white mb-4">
            Тренд по месяцам
          </h3>
          <div className="h-48">
            <ResponsiveContainer>
              <LineChart data={monthlyData}>
                <XAxis
                  dataKey="month"
                  tick={{ fontSize: 12 }}
                  stroke="#94a3b8"
                />
                <YAxis
                  tick={{ fontSize: 10 }}
                  stroke="#94a3b8"
                  tickFormatter={fmtShort}
                />
                <Tooltip content={<CustomTooltip />} />
                <Line
                  type="monotone"
                  dataKey="income"
                  stroke="#22c55e"
                  strokeWidth={2}
                  name="Доходы"
                  dot={{ r: 3 }}
                />
                <Line
                  type="monotone"
                  dataKey="expense"
                  stroke="#ef4444"
                  strokeWidth={2}
                  name="Расходы"
                  dot={{ r: 3 }}
                />
              </LineChart>
            </ResponsiveContainer>
          </div>
          <div className="flex justify-center gap-6 mt-3">
            <div className="flex items-center gap-2 text-xs">
              <div className="w-3 h-0.5 bg-green-500" />
              <span className="text-gray-500">Доходы</span>
            </div>
            <div className="flex items-center gap-2 text-xs">
              <div className="w-3 h-0.5 bg-red-500" />
              <span className="text-gray-500">Расходы</span>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
