import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
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 { Tabs } from '@/components/Tabs'
import { formatCurrency, formatNumber, formatPercent } from '@/lib/utils'
import { useState } from 'react'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts'

const GRADE_COLORS: Record<string, string> = { '战略': '#22c55e', '优选': '#3b82f6', '合格': '#eab308', '淘汰': '#ef4444' }

export function EnterprisePage() {
  const [tab, setTab] = useState('supplier')
  const queryClient = useQueryClient()

  const { data: supplierData, isLoading: supplierLoading } = useQuery({
    queryKey: ['enterprise/suppliers'],
    queryFn: () => api.get('/enterprise/suppliers'),
    enabled: tab === 'supplier',
  })

  const { data: poData, isLoading: poLoading } = useQuery({
    queryKey: ['enterprise/purchase-orders'],
    queryFn: () => api.get('/enterprise/purchase-orders'),
    enabled: tab === 'supplier',
  })

  const { data: approvalData, isLoading: approvalLoading } = useQuery({
    queryKey: ['enterprise/approvals'],
    queryFn: () => api.get('/enterprise/approvals'),
    enabled: tab === 'approval',
  })

  const { data: notificationData, isLoading: notifLoading } = useQuery({
    queryKey: ['enterprise/notifications'],
    queryFn: () => api.get('/enterprise/notifications'),
    enabled: tab === 'notification',
  })

  const { data: talentData, isLoading: talentLoading } = useQuery({
    queryKey: ['enterprise/hr/talent-matrix'],
    queryFn: () => api.get('/enterprise/hr/talent-matrix'),
    enabled: tab === 'hr',
  })

  const { data: courseData, isLoading: courseLoading } = useQuery({
    queryKey: ['enterprise/training/courses'],
    queryFn: () => api.get('/enterprise/training/courses'),
    enabled: tab === 'lms',
  })

  const { data: recordData, isLoading: recordLoading } = useQuery({
    queryKey: ['enterprise/training/records'],
    queryFn: () => api.get('/enterprise/training/records'),
    enabled: tab === 'lms',
  })

  const { data: campaignData, isLoading: campaignLoading } = useQuery({
    queryKey: ['enterprise/campaigns'],
    queryFn: () => api.get('/enterprise/campaigns'),
    enabled: tab === 'marketing',
  })

  const { data: couponData, isLoading: couponLoading } = useQuery({
    queryKey: ['enterprise/coupons'],
    queryFn: () => api.get('/enterprise/coupons'),
    enabled: tab === 'marketing',
  })

  const { data: budgetData, isLoading: budgetLoading } = useQuery({
    queryKey: ['enterprise/budgets'],
    queryFn: () => api.get('/enterprise/budgets'),
    enabled: tab === 'finance',
  })

  const { data: loopData, isLoading: loopLoading } = useQuery({
    queryKey: ['enterprise/loop-verification'],
    queryFn: () => api.get('/enterprise/loop-verification'),
    enabled: tab === 'loop',
  })

  const { data: auditData, isLoading: auditLoading } = useQuery({
    queryKey: ['enterprise/audit-logs'],
    queryFn: () => api.get('/enterprise/audit-logs'),
    enabled: tab === 'audit',
  })

  const approveMutation = useMutation({
    mutationFn: ({ id, result, comment }: { id: number; result: string; comment?: string }) =>
      api.post(`/enterprise/approvals/${id}/approve`, { result, comment }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['enterprise/approvals'] }),
  })

  const readMutation = useMutation({
    mutationFn: (id: number) => api.patch(`/enterprise/notifications/${id}/read`),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['enterprise/notifications'] }),
  })

  if ((tab === 'supplier' && supplierLoading) || (tab === 'approval' && approvalLoading) || (tab === 'notification' && notifLoading) || (tab === 'hr' && talentLoading) || (tab === 'lms' && courseLoading) || (tab === 'marketing' && campaignLoading) || (tab === 'finance' && budgetLoading) || (tab === 'loop' && loopLoading) || (tab === 'audit' && auditLoading)) {
    return <LoadingSpinner text="加载企业协同数据..." />
  }

  const suppliers = (supplierData as any)?.data || []
  const purchaseOrders = (poData as any)?.data || []
  const approvals = (approvalData as any)?.data || []
  const notifications = (notificationData as any)?.data || []
  const talents = (talentData as any)?.data || []
  const courses = (courseData as any)?.data || []
  const records = (recordData as any)?.data || []
  const campaigns = (campaignData as any)?.data || []
  const coupons = (couponData as any)?.data || []
  const budgets = (budgetData as any)?.data || []
  const loops = (loopData as any)?.data || []
  const auditLogs = (auditData as any)?.data || []

  const gradeDist = suppliers.reduce((acc: Record<string, number>, r: any) => {
    acc[r.grade] = (acc[r.grade] || 0) + 1
    return acc
  }, {})
  const gradePieData = Object.entries(gradeDist).map(([name, value]) => ({ name, value }))

  const quadrantDist = talents.reduce((acc: Record<string, number>, r: any) => {
    acc[r.quadrant] = (acc[r.quadrant] || 0) + 1
    return acc
  }, {})

  const pendingApprovals = approvals.filter((a: any) => a.status === 'pending').length
  const unreadNotifications = notifications.filter((n: any) => !n.is_read).length

  return (
    <div className="space-y-4">
      <div>
        <h1 className="text-xl font-bold">企业协同管理</h1>
        <p className="mt-0.5 text-xs text-muted-foreground">供应链 · 审批流 · 消息 · HR · 培训 · 营销 · 财务 · 闭环 · 审计</p>
      </div>

      <Tabs tabs={[
        { key: 'supplier', label: '供应链SRM' },
        { key: 'approval', label: '审批流' },
        { key: 'notification', label: '消息中心' },
        { key: 'hr', label: 'HR人才' },
        { key: 'lms', label: '培训LMS' },
        { key: 'marketing', label: '营销MA' },
        { key: 'finance', label: '财务ERP' },
        { key: 'loop', label: '闭环验证' },
        { key: 'audit', label: '审计日志' },
      ]} active={tab} onChange={setTab} />

      {tab === 'supplier' && (
        <>
          <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
            <MetricCard title="供应商总数" value={suppliers.length} format="number" />
            <MetricCard title="战略供应商" value={gradeDist['战略'] || 0} format="number" status="good" />
            <MetricCard title="采购订单" value={purchaseOrders.length} format="number" />
            <MetricCard title="淘汰供应商" value={gradeDist['淘汰'] || 0} format="number" status="bad" />
          </div>
          {gradePieData.length > 0 && (
            <CollapsibleSection title="供应商分级分布">
              <ResponsiveContainer width="100%" height={200}>
                <PieChart>
                  <Pie data={gradePieData} cx="50%" cy="50%" outerRadius={60} dataKey="value"
                    labelLine={false} label={({ name, value }: any) => <tspan fontSize={11}>{`${name}: ${value}`}</tspan>}>
                    {gradePieData.map((e, i) => <Cell key={i} fill={GRADE_COLORS[e.name] || '#999'} />)}
                  </Pie>
                  <Tooltip />
                  <Legend />
                </PieChart>
              </ResponsiveContainer>
            </CollapsibleSection>
          )}
          <CollapsibleSection title={`供应商列表 (${suppliers.length})`}>
            <FilterableTable
              data={suppliers}
              filterKey="grade"
              filterLabel="全部分级"
              sortOptions={[{ key: 'overall_score', label: '综合分' }, { key: 'supplier_name', label: '名称' }]}
              defaultSort="overall_score"
              defaultOrder="desc"
              columns={[
                { key: 'supplier_code', label: '编码' },
                { key: 'supplier_name', label: '名称' },
                { key: 'category', label: '品类' },
                { key: 'grade', label: '分级', align: 'center', render: (r) => {
                  const colors: Record<string, string> = { '战略': 'text-green-600', '优选': 'text-blue-600', '合格': 'text-yellow-600', '淘汰': 'text-red-600' }
                  return <span className={`font-bold ${colors[r.grade] || ''}`}>{r.grade}</span>
                }},
                { key: 'overall_score', label: '综合分', align: 'right', render: (r) => r.overall_score ? Number(r.overall_score).toFixed(1) : '-' },
                { key: 'delivery_on_time_rate', label: '准时率', align: 'right', render: (r) => r.delivery_on_time_rate ? formatPercent(r.delivery_on_time_rate) : '-' },
                { key: 'contact_person', label: '联系人' },
              ]}
            />
          </CollapsibleSection>
          <CollapsibleSection title={`采购订单 (${purchaseOrders.length})`}>
            <FilterableTable
              data={purchaseOrders}
              filterKey="status"
              filterLabel="全部状态"
              sortOptions={[{ key: 'created_at', label: '创建时间' }, { key: 'total_amount', label: '金额' }]}
              defaultSort="created_at"
              defaultOrder="desc"
              columns={[
                { key: 'po_number', label: 'PO编号' },
                { key: 'supplier_code', label: '供应商' },
                { key: 'store_code', label: '门店' },
                { key: 'order_date', label: '下单日期', render: (r) => (r.order_date || '').toString().substring(0, 10) },
                { key: 'total_amount', label: '金额', align: 'right', render: (r) => formatCurrency(r.total_amount) },
                { key: 'status', label: '状态', align: 'center' },
              ]}
            />
          </CollapsibleSection>
        </>
      )}

      {tab === 'approval' && (
        <>
          <div className="grid grid-cols-2 gap-3 md:grid-cols-3">
            <MetricCard title="审批总数" value={approvals.length} format="number" />
            <MetricCard title="待审批" value={pendingApprovals} format="number" status="warn" />
            <MetricCard title="已审批" value={approvals.length - pendingApprovals} format="number" status="good" />
          </div>
          <CollapsibleSection title={`审批列表 (${approvals.length})`}>
            <FilterableTable
              data={approvals}
              filterKey="status"
              filterLabel="全部状态"
              sortOptions={[{ key: 'created_at', label: '创建时间' }, { key: 'request_type', label: '类型' }]}
              defaultSort="created_at"
              defaultOrder="desc"
              columns={[
                { key: 'request_type', label: '类型' },
                { key: 'applicant_name', label: '申请人' },
                { key: 'store_code', label: '门店' },
                { key: 'current_step', label: '当前步骤', align: 'center', render: (r) => `${r.current_step}/${r.total_steps}` },
                { key: 'status', label: '状态', align: 'center', render: (r) => {
                  const colors: Record<string, string> = { approved: 'text-green-600', pending: 'text-yellow-600', rejected: 'text-red-600' }
                  return <span className={`font-bold ${colors[r.status] || ''}`}>{r.status}</span>
                }},
                { key: 'created_at', label: '创建时间', render: (r) => (r.created_at || '').substring(0, 19).replace('T', ' ') },
                { key: 'action', label: '操作', align: 'center', render: (r) => r.status === 'pending' ? (
                  <div className="flex gap-1">
                    <button onClick={() => approveMutation.mutate({ id: r.id, result: 'approved' })} className="rounded bg-green-600 px-2 py-0.5 text-xs text-white">通过</button>
                    <button onClick={() => approveMutation.mutate({ id: r.id, result: 'rejected' })} className="rounded bg-red-600 px-2 py-0.5 text-xs text-white">驳回</button>
                  </div>
                ) : '-' },
              ]}
            />
          </CollapsibleSection>
        </>
      )}

      {tab === 'notification' && (
        <>
          <div className="grid grid-cols-2 gap-3 md:grid-cols-3">
            <MetricCard title="消息总数" value={notifications.length} format="number" />
            <MetricCard title="未读" value={unreadNotifications} format="number" status="warn" />
            <MetricCard title="已读" value={notifications.length - unreadNotifications} format="number" status="good" />
          </div>
          <CollapsibleSection title={`消息列表 (${notifications.length})`}>
            <FilterableTable
              data={notifications}
              filterKey="notification_type"
              filterLabel="全部类型"
              sortOptions={[{ key: 'created_at', label: '时间' }]}
              defaultSort="created_at"
              defaultOrder="desc"
              columns={[
                { key: 'title', label: '标题', render: (r) => <span className={r.is_read ? '' : 'font-bold'}>{r.title}</span> },
                { key: 'notification_type', label: '类型', align: 'center' },
                { key: 'content', label: '内容' },
                { key: 'is_read', label: '状态', align: 'center', render: (r) => r.is_read ? '已读' : <span className="text-yellow-600 font-bold">未读</span> },
                { key: 'created_at', label: '时间', render: (r) => (r.created_at || '').substring(0, 19).replace('T', ' ') },
                { key: 'action', label: '操作', align: 'center', render: (r) => !r.is_read ? (
                  <button onClick={() => readMutation.mutate(r.id)} className="rounded bg-primary px-2 py-0.5 text-xs text-primary-foreground">标记已读</button>
                ) : '-' },
              ]}
            />
          </CollapsibleSection>
        </>
      )}

      {tab === 'hr' && (
        <>
          <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
            <MetricCard title="人才总数" value={talents.length} format="number" />
            <MetricCard title="明星员工" value={quadrantDist['star'] || 0} format="number" status="good" />
            <MetricCard title="核心员工" value={quadrantDist['core'] || 0} format="number" />
            <MetricCard title="潜力员工" value={quadrantDist['potential'] || 0} format="number" status="warn" />
          </div>
          <CollapsibleSection title="人才九宫格" subtitle="绩效×潜力">
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={Object.entries(quadrantDist).map(([k, v]) => ({ name: k, count: v }))} layout="vertical">
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis type="number" />
                <YAxis dataKey="name" type="category" />
                <Tooltip />
                <Bar dataKey="count" fill="#3b82f6" name="人数" />
              </BarChart>
            </ResponsiveContainer>
          </CollapsibleSection>
          <CollapsibleSection title={`人才列表 (${talents.length})`}>
            <FilterableTable
              data={talents}
              filterKey="quadrant"
              filterLabel="全部象限"
              sortOptions={[{ key: 'performance_score', label: '绩效' }, { key: 'potential_score', label: '潜力' }]}
              defaultSort="performance_score"
              defaultOrder="desc"
              columns={[
                { key: 'employee_name', label: '员工' },
                { key: 'store_name', label: '门店' },
                { key: 'performance_score', label: '绩效分', align: 'right', render: (r) => Number(r.performance_score || 0).toFixed(1) },
                { key: 'potential_score', label: '潜力分', align: 'right', render: (r) => Number(r.potential_score || 0).toFixed(1) },
                { key: 'quadrant', label: '象限', align: 'center', render: (r) => {
                  const labels: Record<string, string> = { star: '明星', core: '核心', potential: '潜力', ordinary: '普通' }
                  const colors: Record<string, string> = { star: 'text-green-600', core: 'text-blue-600', potential: 'text-yellow-600', ordinary: 'text-gray-600' }
                  return <span className={`font-bold ${colors[r.quadrant] || ''}`}>{labels[r.quadrant] || r.quadrant}</span>
                }},
              ]}
            />
          </CollapsibleSection>
        </>
      )}

      {tab === 'lms' && (
        <>
          <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
            <MetricCard title="课程总数" value={courses.length} format="number" />
            <MetricCard title="学习记录" value={records.length} format="number" />
            <MetricCard title="已完成" value={records.filter((r: any) => r.completion_status === '已完成').length} format="number" status="good" />
            <MetricCard title="未完成" value={records.filter((r: any) => r.completion_status !== '已完成').length} format="number" status="warn" />
          </div>
          <CollapsibleSection title={`课程列表 (${courses.length})`}>
            <FilterableTable
              data={courses}
              filterKey="course_type"
              filterLabel="全部类型"
              sortOptions={[{ key: 'course_name', label: '课程名' }, { key: 'created_at', label: '创建时间' }]}
              defaultSort="created_at"
              defaultOrder="desc"
              columns={[
                { key: 'course_name', label: '课程名称' },
                { key: 'course_type', label: '类型', align: 'center' },
                { key: 'exam_enabled', label: '考试', align: 'center', render: (r) => r.exam_enabled ? '是' : '否' },
                { key: 'pass_score', label: '及格分', align: 'right' },
                { key: 'created_at', label: '创建时间', render: (r) => (r.created_at || '').substring(0, 10) },
              ]}
            />
          </CollapsibleSection>
          <CollapsibleSection title={`学习记录 (${records.length})`}>
            <FilterableTable
              data={records}
              filterKey="completion_status"
              filterLabel="全部状态"
              sortOptions={[{ key: 'employee_name', label: '员工' }, { key: 'progress_pct', label: '进度' }]}
              defaultSort="progress_pct"
              defaultOrder="desc"
              columns={[
                { key: 'employee_name', label: '员工' },
                { key: 'store_code', label: '门店' },
                { key: 'progress_pct', label: '进度', align: 'right', render: (r) => formatPercent(r.progress_pct || 0) },
                { key: 'completion_status', label: '状态', align: 'center', render: (r) => {
                  const colors: Record<string, string> = { '已完成': 'text-green-600', '进行中': 'text-blue-600', '未开始': 'text-gray-600', '未通过': 'text-red-600' }
                  return <span className={colors[r.completion_status] || ''}>{r.completion_status}</span>
                }},
                { key: 'exam_score', label: '考试成绩', align: 'right', render: (r) => r.exam_score ?? '-' },
              ]}
            />
          </CollapsibleSection>
        </>
      )}

      {tab === 'marketing' && (
        <>
          <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
            <MetricCard title="活动总数" value={campaigns.length} format="number" />
            <MetricCard title="进行中" value={campaigns.filter((c: any) => c.status === 'active').length} format="number" status="good" />
            <MetricCard title="券码总数" value={coupons.length} format="number" />
            <MetricCard title="已核销" value={coupons.filter((c: any) => c.status === 'used').length} format="number" />
          </div>
          <CollapsibleSection title={`营销活动 (${campaigns.length})`}>
            <FilterableTable
              data={campaigns}
              filterKey="status"
              filterLabel="全部状态"
              sortOptions={[{ key: 'created_at', label: '创建时间' }, { key: 'budget', label: '预算' }]}
              defaultSort="created_at"
              defaultOrder="desc"
              columns={[
                { key: 'campaign_name', label: '活动名称' },
                { key: 'campaign_type', label: '类型' },
                { key: 'start_date', label: '开始', render: (r) => (r.start_date || '').substring(0, 10) },
                { key: 'end_date', label: '结束', render: (r) => (r.end_date || '').substring(0, 10) },
                { key: 'budget', label: '预算', align: 'right', render: (r) => formatCurrency(r.budget) },
                { key: 'roi', label: 'ROI', align: 'right', render: (r) => r.roi ? `${Number(r.roi).toFixed(2)}x` : '-' },
                { key: 'status', label: '状态', align: 'center' },
              ]}
            />
          </CollapsibleSection>
          <CollapsibleSection title={`券码管理 (${coupons.length})`}>
            <FilterableTable
              data={coupons}
              filterKey="status"
              filterLabel="全部状态"
              sortOptions={[{ key: 'created_at', label: '创建时间' }, { key: 'face_value', label: '面值' }]}
              defaultSort="created_at"
              defaultOrder="desc"
              columns={[
                { key: 'coupon_code', label: '券码' },
                { key: 'coupon_type', label: '类型' },
                { key: 'face_value', label: '面值', align: 'right', render: (r) => formatCurrency(r.face_value) },
                { key: 'min_spend', label: '门槛', align: 'right', render: (r) => formatCurrency(r.min_spend) },
                { key: 'expiry_date', label: '过期日期', render: (r) => (r.expiry_date || '').substring(0, 10) },
                { key: 'status', label: '状态', align: 'center', render: (r) => {
                  const colors: Record<string, string> = { unused: 'text-blue-600', used: 'text-green-600', expired: 'text-gray-600', refunded: 'text-red-600' }
                  return <span className={colors[r.status] || ''}>{r.status}</span>
                }},
              ]}
            />
          </CollapsibleSection>
        </>
      )}

      {tab === 'finance' && (
        <>
          <div className="grid grid-cols-2 gap-3 md:grid-cols-3">
            <MetricCard title="预算总数" value={budgets.length} format="number" />
            <MetricCard title="总预算" value={budgets.reduce((s: number, b: any) => s + Number(b.budget_amount || 0), 0)} format="currency" />
            <MetricCard title="总实际" value={budgets.reduce((s: number, b: any) => s + Number(b.actual_amount || 0), 0)} format="currency" />
          </div>
          <CollapsibleSection title={`预算管理 (${budgets.length})`}>
            <FilterableTable
              data={budgets}
              filterKey="budget_type"
              filterLabel="全部类型"
              sortOptions={[{ key: 'month', label: '月份' }, { key: 'budget_amount', label: '预算' }, { key: 'execution_rate', label: '执行率' }]}
              defaultSort="month"
              defaultOrder="desc"
              columns={[
                { key: 'year', label: '年度', align: 'center' },
                { key: 'month', label: '月份', render: (r) => r.month ? (r.month as string).substring(0, 10) : '-' },
                { key: 'store_code', label: '门店' },
                { key: 'department', label: '部门' },
                { key: 'budget_type', label: '类型', align: 'center' },
                { key: 'budget_amount', label: '预算', align: 'right', render: (r) => formatCurrency(r.budget_amount) },
                { key: 'actual_amount', label: '实际', align: 'right', render: (r) => formatCurrency(r.actual_amount) },
                { key: 'execution_rate', label: '执行率', align: 'right', render: (r) => formatPercent(r.execution_rate || 0) },
              ]}
            />
          </CollapsibleSection>
        </>
      )}

      {tab === 'loop' && (
        <>
          <div className="grid grid-cols-2 gap-3 md:grid-cols-3">
            <MetricCard title="验证总数" value={loops.length} format="number" />
            <MetricCard title="已完成" value={loops.filter((l: any) => l.status === 'completed').length} format="number" status="good" />
            <MetricCard title="需升级" value={loops.filter((l: any) => l.status === 'escalated').length} format="number" status="bad" />
          </div>
          <CollapsibleSection title={`闭环验证 (${loops.length})`}>
            <FilterableTable
              data={loops}
              filterKey="status"
              filterLabel="全部状态"
              sortOptions={[{ key: 'check_date', label: '检查日期' }, { key: 'completion_rate', label: '完成率' }]}
              defaultSort="check_date"
              defaultOrder="desc"
              columns={[
                { key: 'loop_name', label: '闭环名称' },
                { key: 'store_code', label: '门店' },
                { key: 'check_date', label: '检查日期', render: (r) => (r.check_date || '').substring(0, 10) },
                { key: 'status', label: '状态', align: 'center', render: (r) => {
                  const colors: Record<string, string> = { completed: 'text-green-600', open: 'text-yellow-600', escalated: 'text-red-600' }
                  return <span className={`font-bold ${colors[r.status] || ''}`}>{r.status}</span>
                }},
                { key: 'completion_rate', label: '完成率', align: 'right', render: (r) => formatPercent(r.completion_rate || 0) },
                { key: 'cycle_days', label: '周期(天)', align: 'right' },
                { key: 'bottleneck', label: '瓶颈环节' },
              ]}
            />
          </CollapsibleSection>
        </>
      )}

      {tab === 'audit' && (
        <CollapsibleSection title={`审计日志 (${auditLogs.length})`}>
          <FilterableTable
            data={auditLogs}
            filterKey="action"
            filterLabel="全部操作"
            sortOptions={[{ key: 'created_at', label: '时间' }, { key: 'user_name', label: '用户' }]}
            defaultSort="created_at"
            defaultOrder="desc"
            columns={[
              { key: 'user_name', label: '用户' },
              { key: 'user_role', label: '角色' },
              { key: 'action', label: '操作', align: 'center' },
              { key: 'resource_type', label: '资源类型' },
              { key: 'resource_id', label: '资源ID' },
              { key: 'created_at', label: '时间', render: (r) => (r.created_at || '').substring(0, 19).replace('T', ' ') },
            ]}
          />
        </CollapsibleSection>
      )}
    </div>
  )
}
