import { useQuery } from '@tanstack/react-query'
import { useState } from 'react'
import api from '@/lib/api'
import { FilterableTable } from '@/components/FilterableTable'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { CollapsibleSection } from '@/components/CollapsibleSection'
import { MetricCard } from '@/components/MetricCard'
import { formatCurrency, formatNumber } from '@/lib/utils'
import { MonthPicker } from '@/components/MonthPicker'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts'

export function InventoryTurnoverPage() {
  const [month, setMonth] = useState('2026-04')

  const { data, isLoading } = useQuery({
    queryKey: ['analytics-enhanced/inventory/turnover', month],
    queryFn: () => api.get('/analytics-enhanced/inventory/turnover', { params: { month } }),
  })

  if (isLoading) {
    return <LoadingSpinner text="加载库存周转数据..." />
  }

  const turnover = (data as any)?.data?.turnover || []
  const wasteTop = (data as any)?.data?.waste_top || []

  const totalOpening = turnover.reduce((s: number, r: any) => s + Number(r.opening_value || 0), 0)
  const totalConsumption = turnover.reduce((s: number, r: any) => s + Number(r.consumption_value || 0), 0)
  const totalWaste = turnover.reduce((s: number, r: any) => s + Number(r.waste_value || 0), 0)
  const totalEnding = turnover.reduce((s: number, r: any) => s + Number(r.ending_value || 0), 0)
  const avgTurnoverDays = turnover.length > 0
    ? turnover.reduce((s: number, r: any) => s + Number(r.turnover_days || 0), 0) / turnover.length
    : 0

  const turnoverChartData = turnover.slice(0, 15).map((r: any) => ({
    name: r.store_name,
    周转天数: Number(r.turnover_days || 0),
    期末库存: Number(r.ending_value || 0),
  }))

  const wasteChartData = wasteTop.slice(0, 10).map((r: any) => ({
    name: r.material_name,
    损耗金额: Number(r.waste_value || 0),
  }))

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold">库存周转与损耗</h1>
          <p className="mt-0.5 text-xs text-muted-foreground">周转天数 · 损耗TOP · 门店对比 · {month}</p>
        </div>
        <MonthPicker month={month} onChange={setMonth} />
      </div>

      {/* 概览指标 */}
      <CollapsibleSection title="库存总览" subtitle="全门店库存汇总">
        <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
          <MetricCard title="期初库存" value={totalOpening} format="currency" description="月初库存总值" />
          <MetricCard title="消耗金额" value={totalConsumption} format="currency" description="当月消耗总值" />
          <MetricCard title="期末库存" value={totalEnding} format="currency" description="月末库存总值" />
          <MetricCard title="平均周转天数" value={avgTurnoverDays} format="number" description="库存平均周转天数" />
        </div>
        <div className="mt-3 grid grid-cols-2 gap-3 md:grid-cols-4">
          <MetricCard title="损耗金额" value={totalWaste} format="currency" description="当月损耗总金额" status="bad" />
          <MetricCard title="损耗率" value={totalConsumption > 0 ? totalWaste / totalConsumption * 100 : 0} format="percent" description="损耗金额/消耗金额" status="bad" />
          <MetricCard title="门店数" value={turnover.length} format="number" description="有库存数据的门店数" />
          <MetricCard title="损耗品类数" value={wasteTop.length} format="number" description="有损耗记录的品类数" />
        </div>
      </CollapsibleSection>

      {/* 图表 */}
      <div className="grid gap-4 lg:grid-cols-2">
        <CollapsibleSection title="门店周转天数" subtitle="TOP15门店库存周转天数与期末库存">
          <ResponsiveContainer width="100%" height={300}>
            <BarChart data={turnoverChartData} margin={{ top: 20, right: 20, bottom: 20, left: 20 }}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="name" tick={{ fontSize: 10 }} angle={-20} textAnchor="end" height={60} />
              <YAxis yAxisId="left" tick={{ fontSize: 10 }} />
              <YAxis yAxisId="right" orientation="right" tickFormatter={(v) => v >= 10000 ? `${(v / 10000).toFixed(0)}万` : v} tick={{ fontSize: 10 }} />
              <Tooltip formatter={(v: any, name: any) => name === '期末库存' ? formatCurrency(v) : `${v}天`} />
              <Legend />
              <Bar yAxisId="left" dataKey="周转天数" fill="#3b82f6" />
              <Bar yAxisId="right" dataKey="期末库存" fill="#eab308" />
            </BarChart>
          </ResponsiveContainer>
        </CollapsibleSection>

        <CollapsibleSection title="损耗金额TOP10" subtitle="损耗金额最高的品类">
          <ResponsiveContainer width="100%" height={300}>
            <BarChart data={wasteChartData} margin={{ top: 20, right: 20, bottom: 20, left: 20 }} layout="vertical">
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis type="number" tickFormatter={(v) => v >= 10000 ? `${(v / 10000).toFixed(0)}万` : v} tick={{ fontSize: 10 }} />
              <YAxis type="category" dataKey="name" tick={{ fontSize: 10 }} width={100} />
              <Tooltip formatter={(v: any) => formatCurrency(v)} />
              <Legend />
              <Bar dataKey="损耗金额" fill="#ef4444" />
            </BarChart>
          </ResponsiveContainer>
        </CollapsibleSection>
      </div>

      {/* 门店周转明细 */}
      <CollapsibleSection title="门店库存周转明细" subtitle="按周转天数升序（天数越少越好）">
        <FilterableTable
          data={turnover}
          filterKey="store_name"
          filterLabel="全部门店"
          sortOptions={[
            { key: 'turnover_days', label: '周转天数' },
            { key: 'ending_value', label: '期末库存' },
            { key: 'consumption_value', label: '消耗金额' },
            { key: 'waste_value', label: '损耗金额' },
          ]}
          defaultSort="turnover_days"
          defaultOrder="asc"
          columns={[
            { key: 'store_code', label: '门店编码' },
            { key: 'store_name', label: '门店名称' },
            { key: 'opening_value', label: '期初库存', align: 'right', render: (r) => formatCurrency(r.opening_value) },
            { key: 'purchase_value', label: '采购金额', align: 'right', render: (r) => formatCurrency(r.purchase_value) },
            { key: 'consumption_value', label: '消耗金额', align: 'right', render: (r) => formatCurrency(r.consumption_value) },
            { key: 'ending_value', label: '期末库存', align: 'right', render: (r) => formatCurrency(r.ending_value) },
            { key: 'waste_value', label: '损耗金额', align: 'right', render: (r) => {
              const v = Number(r.waste_value || 0)
              return <span className={v > 1000 ? 'text-red-600 font-medium' : ''}>{formatCurrency(v)}</span>
            }},
            { key: 'turnover_days', label: '周转天数', align: 'right', render: (r) => {
              const v = Number(r.turnover_days || 0)
              return <span className={v <= 7 ? 'text-green-600' : v <= 14 ? 'text-yellow-600' : 'text-red-600'}>{v.toFixed(1)}天</span>
            }},
          ]}
        />
      </CollapsibleSection>

      {/* 损耗TOP明细 */}
      <CollapsibleSection title="损耗品类TOP20" subtitle="按损耗金额降序">
        <FilterableTable
          data={wasteTop}
          filterKey="material_name"
          filterLabel="全部品类"
          sortOptions={[
            { key: 'waste_value', label: '损耗金额' },
            { key: 'waste_qty', label: '损耗数量' },
            { key: 'affected_stores', label: '影响门店数' },
          ]}
          defaultSort="waste_value"
          defaultOrder="desc"
          columns={[
            { key: 'material_name', label: '物料名称' },
            { key: 'waste_qty', label: '损耗数量', align: 'right', render: (r) => formatNumber(r.waste_qty) },
            { key: 'waste_value', label: '损耗金额', align: 'right', render: (r) => formatCurrency(r.waste_value) },
            { key: 'affected_stores', label: '影响门店数', align: 'right', render: (r) => formatNumber(r.affected_stores) },
          ]}
        />
      </CollapsibleSection>
    </div>
  )
}
