'use client'
import Link from 'next/link'
import { Server, Wifi, CheckCircle, PackageCheck, Wrench, Target, Clock, Upload } from 'lucide-react'
import { useMemo } from 'react'
import { useApi } from '@/lib/hooks'

interface DashboardData {
  devices: { total: number; assembling: number; activated: number; shipped: number }
  materials: { total: number; inStock: number; assembled: number; faulty: number }
  repair: { total: number; pending: number; processing: number; done: number }
  scrap: { total: number; pendingApproval: number }
  firmware: { total: number }
  licenses: { total: number }
  recentRepairs: { id: string; sn: string; fault_type: string; status: string; priority: string; create_date: string }[]
  recentScraps: { id: number; sn: string; model: string; status: string; date: string }[]
}

const defaultData: DashboardData = {
  devices: { total: 0, assembling: 0, activated: 0, shipped: 0 },
  materials: { total: 0, inStock: 0, assembled: 0, faulty: 0 },
  repair: { total: 0, pending: 0, processing: 0, done: 0 },
  scrap: { total: 0, pendingApproval: 0 },
  firmware: { total: 0 },
  licenses: { total: 0 },
  recentRepairs: [],
  recentScraps: [],
}

export default function DashboardPage() {
  const { data, loading } = useApi<DashboardData>('/api/dashboard', defaultData)

  const metrics = [
    { label: '设备总数', value: data.devices.total, color: '#4a7c59', icon: Server, link: '/devices' },
    { label: '装配中', value: data.devices.assembling, color: '#52C41A', icon: Wifi, link: '/devices' },
    { label: '已激活', value: data.devices.activated, color: '#4a7c59', icon: CheckCircle, link: '/devices' },
    { label: '固件版本', value: data.firmware.total, color: '#722ED1', icon: PackageCheck, link: '/firmware' },
    { label: '维修中', value: data.repair.processing, color: '#FF4D4F', icon: Wrench, link: '/repair' },
    { label: '报废', value: data.scrap.total, color: '#FA8C16', icon: Target, link: '/scrap' },
    { label: '授权配置', value: data.licenses.total, color: '#FAAD14', icon: Clock, link: '/licenses' },
    { label: '物料总数', value: data.materials.total, color: '#13C2C2', icon: Upload, link: '/materials' },
  ]

  const deviceStatusData = [
    { name: '装配中', value: data.devices.assembling, color: '#FAAD14' },
    { name: '已出厂', value: data.devices.shipped, color: '#597EF7' },
    { name: '已激活', value: data.devices.activated, color: '#52C41A' },
  ]
  const maxStatusValue = useMemo(() => Math.max(...deviceStatusData.map(d => d.value), 1), [data])

  if (loading) return <div className="p-6">加载中...</div>

  return (
    <div className="p-6">
      <div className="mb-6">
        <h2 className="text-2xl font-semibold mb-1">首页</h2>
        <p className="text-sm" style={{ color: 'rgba(0,0,0,0.45)' }}>生产管理数据总览</p>
      </div>
      <div className="grid grid-cols-4 gap-6 mb-6">
        {metrics.map((m, i) => {
          const Icon = m.icon
          return (
            <Link key={i} href={m.link} className="bg-white p-6 rounded-lg block hover:shadow-md transition-shadow" style={{ boxShadow: '0 1px 2px rgba(0,0,0,0.05)' }}>
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <div className="text-sm mb-2" style={{ color: 'rgba(0,0,0,0.65)' }}>{m.label}</div>
                  <div className="text-3xl font-semibold mb-2">{m.value}</div>
                </div>
                <div className="w-12 h-12 rounded-lg flex items-center justify-center" style={{ backgroundColor: m.color + '15' }}>
                  <Icon size={24} style={{ color: m.color }} />
                </div>
              </div>
            </Link>
          )
        })}
      </div>

      {/* 设备状态分布 */}
      <div className="bg-white p-6 rounded-lg mb-6" style={{ boxShadow: '0 1px 2px rgba(0,0,0,0.05)' }}>
        <h3 className="text-lg font-semibold mb-6">设备状态分布</h3>
        {data.devices.total === 0 ? (
          <div className="text-center py-8" style={{ color: 'rgba(0,0,0,0.25)', fontSize: 14 }}>暂无设备数据</div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            {deviceStatusData.map(item => (
              <div key={item.name} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{ width: 60, textAlign: 'right', fontSize: 14, color: 'rgba(0,0,0,0.65)', flexShrink: 0 }}>{item.name}</div>
                <div style={{ flex: 1, backgroundColor: '#F5F5F5', borderRadius: 4, height: 24, overflow: 'hidden' }}>
                  <div style={{ width: `${(item.value / maxStatusValue) * 100}%`, height: '100%', backgroundColor: item.color, borderRadius: '0 4px 4px 0', transition: 'width 0.3s ease', minWidth: item.value > 0 ? 2 : 0 }} />
                </div>
                <div style={{ width: 40, fontSize: 14, color: 'rgba(0,0,0,0.85)' }}>{item.value}</div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* 待处理任务 */}
      <div className="bg-white p-6 rounded-lg" style={{ boxShadow: '0 1px 2px rgba(0,0,0,0.05)' }}>
        <h3 className="text-lg font-semibold mb-6">待处理任务</h3>
        <div className="grid grid-cols-2 gap-6">
          {/* 维修工单 */}
          <div>
            <div className="flex items-center justify-between mb-4">
              <h4 className="text-base font-medium">维修工单</h4>
              <span className="px-2 py-1 rounded text-xs" style={{ backgroundColor: '#F0F2F5', color: 'rgba(0,0,0,0.65)' }}>{data.repair.pending + data.repair.processing}</span>
            </div>
            {data.recentRepairs.length === 0 ? (
              <div className="text-center py-6" style={{ color: 'rgba(0,0,0,0.25)', fontSize: 13 }}>暂无待处理工单</div>
            ) : (
              <>
                {data.recentRepairs.map(r => (
                  <div key={r.id} className="flex items-start justify-between py-3" style={{ borderBottom: '1px solid #F0F0F0' }}>
                    <div className="flex-1">
                      <div className="text-sm mb-1">{r.sn}</div>
                      <div className="text-sm" style={{ color: 'rgba(0,0,0,0.45)' }}>{r.fault_type} · {r.status}</div>
                    </div>
                    <div className="flex items-center gap-3">
                      <span className="text-xs" style={{ color: 'rgba(0,0,0,0.45)' }}>{r.create_date}</span>
                      <Link href="/repair" className="text-sm" style={{ color: '#4a7c59' }}>处理</Link>
                    </div>
                  </div>
                ))}
                <Link href="/repair" className="block w-full mt-3 text-center text-sm" style={{ color: '#4a7c59' }}>查看全部</Link>
              </>
            )}
          </div>
          {/* 报废审批 */}
          <div>
            <div className="flex items-center justify-between mb-4">
              <h4 className="text-base font-medium">报废审批</h4>
              <span className="px-2 py-1 rounded text-xs" style={{ backgroundColor: '#F0F2F5', color: 'rgba(0,0,0,0.65)' }}>{data.scrap.pendingApproval}</span>
            </div>
            {data.recentScraps.length === 0 ? (
              <div className="text-center py-6" style={{ color: 'rgba(0,0,0,0.25)', fontSize: 13 }}>暂无待审批记录</div>
            ) : (
              <>
                {data.recentScraps.map(s => (
                  <div key={s.id} className="flex items-start justify-between py-3" style={{ borderBottom: '1px solid #F0F0F0' }}>
                    <div className="flex-1">
                      <div className="text-sm mb-1">{s.sn}</div>
                      <div className="text-sm" style={{ color: 'rgba(0,0,0,0.45)' }}>{s.model} · {s.status}</div>
                    </div>
                    <div className="flex items-center gap-3">
                      <span className="text-xs" style={{ color: 'rgba(0,0,0,0.45)' }}>{s.date}</span>
                      <Link href="/scrap" className="text-sm" style={{ color: '#4a7c59' }}>查看</Link>
                    </div>
                  </div>
                ))}
                <Link href="/scrap" className="block w-full mt-3 text-center text-sm" style={{ color: '#4a7c59' }}>查看全部</Link>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}
