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, formatPercent } from '@/lib/utils'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts'

const PIE_COLORS = ['#3b82f6', '#22c55e', '#eab308', '#ef4444', '#a855f7', '#64748b']

export function MemberLTVPage() {
  const [statusFilter, setStatusFilter] = useState('')
  const [levelFilter, setLevelFilter] = useState('')
  const [page, setPage] = useState(1)

  const { data, isLoading } = useQuery({
    queryKey: ['analytics-enhanced/member/ltv', statusFilter, levelFilter, page],
    queryFn: () => api.get('/analytics-enhanced/member/ltv', {
      params: { status: statusFilter, level: levelFilter, page, page_size: 50 },
    }),
  })

  if (isLoading) {
    return <LoadingSpinner text="加载会员LTV数据..." />
  }

  const summary = (data as any)?.data?.summary || {}
  const levelDist = (data as any)?.data?.level_distribution || []
  const members = (data as any)?.data?.members || []
  const meta = (data as any)?.meta || {}

  const levelChartData = levelDist.map((r: any) => ({
    name: r.member_level,
    人数: Number(r.count),
    平均消费: Number(r.avg_revenue),
  }))

  const levelPieData = levelDist.map((r: any) => ({
    name: r.member_level,
    value: Number(r.count),
  }))

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold">会员LTV与分层运营</h1>
          <p className="mt-0.5 text-xs text-muted-foreground">生命周期价值 · 等级分布 · 活跃度分析</p>
        </div>
      </div>

      {/* 概览指标 */}
      <CollapsibleSection title="会员总览" subtitle="全量会员LTV与活跃度">
        <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
          <MetricCard title="总会员数" value={Number(summary.total_members || 0)} format="number" description="已识别的独立会员总数" />
          <MetricCard title="平均LTV" value={Number(summary.avg_ltv || 0)} format="currency" description="会员生命周期平均消费金额" />
          <MetricCard title="平均消费次数" value={Number(summary.avg_orders || 0)} format="number" description="会员平均到店消费次数" />
          <MetricCard title="会员总收入" value={Number(summary.total_revenue || 0)} format="currency" description="全部会员累计消费金额" />
        </div>
        <div className="mt-3 grid grid-cols-2 gap-3 md:grid-cols-4">
          <MetricCard title="活跃会员" value={Number(summary.active_count || 0)} format="number" description="30天内有消费" status="good" />
          <MetricCard title="沉睡会员" value={Number(summary.dormant_count || 0)} format="number" description="30-90天未消费" status="warn" />
          <MetricCard title="流失会员" value={Number(summary.churned_count || 0)} format="number" description="90天以上未消费" status="bad" />
          <MetricCard title="活跃率" value={Number(summary.active_count || 0) / Number(summary.total_members || 1) * 100} format="percent" description="活跃会员占总会员比例" />
        </div>
      </CollapsibleSection>

      {/* 等级分布图 */}
      <div className="grid gap-4 lg:grid-cols-2">
        <CollapsibleSection title="会员等级分布" subtitle="各等级人数与平均消费">
          <ResponsiveContainer width="100%" height={250}>
            <BarChart data={levelChartData} margin={{ top: 20, right: 20, bottom: 20, left: 20 }}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="name" tick={{ fontSize: 12 }} />
              <YAxis yAxisId="left" tickFormatter={(v) => v >= 10000 ? `${(v / 10000).toFixed(0)}万` : v} 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) : formatNumber(v)} />
              <Legend />
              <Bar yAxisId="left" dataKey="人数" fill="#3b82f6" />
              <Bar yAxisId="right" dataKey="平均消费" fill="#eab308" />
            </BarChart>
          </ResponsiveContainer>
        </CollapsibleSection>

        <CollapsibleSection title="等级占比" subtitle="各等级会员占比">
          <ResponsiveContainer width="100%" height={250}>
            <PieChart>
              <Pie data={levelPieData} cx="50%" cy="50%" outerRadius={80} dataKey="value"
                labelLine={false} label={({ name, value }: any) => <tspan fontSize={11}>{`${name}: ${formatNumber(value)}`}</tspan>}>
                {levelPieData.map((_: any, i: number) => <Cell key={i} fill={PIE_COLORS[i % PIE_COLORS.length]} />)}
              </Pie>
              <Tooltip formatter={(v: any) => [formatNumber(v), '人数']} />
              <Legend />
            </PieChart>
          </ResponsiveContainer>
        </CollapsibleSection>
      </div>

      {/* 筛选器 */}
      <div className="flex items-center gap-3">
        <select
          value={statusFilter}
          onChange={(e) => { setStatusFilter(e.target.value); setPage(1) }}
          className="rounded-md border px-3 py-1.5 text-sm"
        >
          <option value="">全部状态</option>
          <option value="活跃">活跃</option>
          <option value="沉睡">沉睡</option>
          <option value="流失">流失</option>
        </select>
        <select
          value={levelFilter}
          onChange={(e) => { setLevelFilter(e.target.value); setPage(1) }}
          className="rounded-md border px-3 py-1.5 text-sm"
        >
          <option value="">全部等级</option>
          <option value="钻石">钻石</option>
          <option value="金卡">金卡</option>
          <option value="银卡">银卡</option>
          <option value="普通">普通</option>
        </select>
        <span className="text-xs text-muted-foreground">共 {meta.total || 0} 条</span>
      </div>

      {/* 会员明细 */}
      <CollapsibleSection title="会员明细" subtitle="按总消费降序">
        <FilterableTable
          data={members}
          filterKey="member_id"
          filterLabel="全部分员"
          sortOptions={[
            { key: 'total_revenue', label: '总消费' },
            { key: 'total_orders', label: '消费次数' },
            { key: 'register_date', label: '注册日期' },
            { key: 'last_order_date', label: '最近消费' },
          ]}
          defaultSort="total_revenue"
          defaultOrder="desc"
          columns={[
            { key: 'member_id', label: '会员ID' },
            { key: 'member_level', label: '等级', render: (r) => {
              const color = r.member_level === '钻石' ? 'text-purple-600' : r.member_level === '金卡' ? 'text-yellow-600' : r.member_level === '银卡' ? 'text-blue-600' : 'text-gray-500'
              return <span className={color}>{r.member_level}</span>
            }},
            { key: 'status', label: '状态', render: (r) => {
              const color = r.status === '活跃' ? 'text-green-600' : r.status === '沉睡' ? 'text-yellow-600' : 'text-red-600'
              return <span className={color}>{r.status}</span>
            }},
            { key: 'total_orders', label: '消费次数', align: 'right', render: (r) => formatNumber(r.total_orders) },
            { key: 'total_revenue', label: '总消费', align: 'right', render: (r) => formatCurrency(r.total_revenue) },
            { key: 'register_date', label: '注册日期', render: (r) => r.register_date ? String(r.register_date).slice(0, 10) : '' },
            { key: 'last_order_date', label: '最近消费', render: (r) => r.last_order_date ? String(r.last_order_date).slice(0, 10) : '' },
            { key: 'register_store_name', label: '注册门店' },
            { key: 'register_channel', label: '注册渠道' },
          ]}
        />
      </CollapsibleSection>

      {/* 分页 */}
      {meta.total > 50 && (
        <div className="flex items-center justify-center gap-2">
          <button
            onClick={() => setPage(p => Math.max(1, p - 1))}
            disabled={page <= 1}
            className="rounded-md border px-3 py-1 text-sm disabled:opacity-50"
          >上一页</button>
          <span className="text-sm text-muted-foreground">第 {page} 页 / 共 {Math.ceil(meta.total / 50)} 页</span>
          <button
            onClick={() => setPage(p => p + 1)}
            disabled={page >= Math.ceil(meta.total / 50)}
            className="rounded-md border px-3 py-1 text-sm disabled:opacity-50"
          >下一页</button>
        </div>
      )}
    </div>
  )
}
