import { useQuery } from '@tanstack/react-query'
import { Link } from 'react-router-dom'
import { Package, Upload, CheckCircle, Clock, AlertCircle } from 'lucide-react'
import { listOrders } from '../../api/orders'
import { useAuthStore } from '../../store/auth'

export default function ClientDashboard() {
  const user = useAuthStore((s) => s.user)
  const { data: orders } = useQuery({ queryKey: ['orders'], queryFn: () => listOrders({ limit: 100 }) })

  const stats = {
    total: orders?.length ?? 0,
    draft: orders?.filter((o) => o.status === 'draft').length ?? 0,
    submitted: orders?.filter((o) => o.status === 'submitted').length ?? 0,
    completed: orders?.filter((o) => o.status === 'completed').length ?? 0,
  }

  return (
    <div className="p-8">
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-content">Welcome, {user?.full_name}</h1>
        <p className="text-content-muted mt-1">Schaeffler Media Creation Pipeline</p>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        <StatCard label="Total Orders" value={stats.total} icon={Package} color="blue" />
        <StatCard label="Drafts" value={stats.draft} icon={Clock} color="yellow" />
        <StatCard label="Submitted" value={stats.submitted} icon={AlertCircle} color="orange" />
        <StatCard label="Completed" value={stats.completed} icon={CheckCircle} color="green" />
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div className="card p-6">
          <h2 className="font-semibold text-content mb-4">Quick Actions</h2>
          <div className="space-y-3">
            <Link to="/upload" className="btn-primary w-full justify-center">
              <Upload size={16} />
              Upload Excel Order List
            </Link>
            <Link to="/orders" className="btn-secondary w-full justify-center">
              <Package size={16} />
              View All Orders
            </Link>
          </div>
        </div>

        <div className="card p-6">
          <h2 className="font-semibold text-content mb-4">Recent Orders</h2>
          {orders && orders.length > 0 ? (
            <div className="space-y-2">
              {orders.slice(0, 5).map((order) => (
                <Link
                  key={order.id}
                  to={`/orders/${order.id}`}
                  className="flex items-center justify-between p-2 rounded hover:bg-surface-hover transition-colors"
                >
                  <span className="text-sm font-medium text-content">{order.order_number}</span>
                  <div className="flex items-center gap-3">
                    {order.estimated_price != null && (
                      <span className="text-xs text-content-muted">
                        € {Number(order.estimated_price).toFixed(2)}
                      </span>
                    )}
                    <StatusBadge status={order.status} />
                  </div>
                </Link>
              ))}
            </div>
          ) : (
            <p className="text-sm text-content-muted">No orders yet. Upload an Excel file to get started.</p>
          )}
        </div>
      </div>
    </div>
  )
}

function StatCard({ label, value, icon: Icon, color }: { label: string; value: number; icon: any; color: string }) {
  const colors: Record<string, string> = {
    blue: 'text-status-info-text bg-status-info-bg',
    yellow: 'text-yellow-600 bg-yellow-50',
    orange: 'text-status-warning-text bg-status-warning-bg',
    green: 'text-status-success-text bg-status-success-bg',
  }
  return (
    <div className="card p-5">
      <div className={`w-10 h-10 rounded-lg flex items-center justify-center mb-3 ${colors[color]}`}>
        <Icon size={20} />
      </div>
      <p className="text-2xl font-bold text-content">{value}</p>
      <p className="text-sm text-content-muted mt-1">{label}</p>
    </div>
  )
}

function StatusBadge({ status }: { status: string }) {
  const map: Record<string, string> = {
    draft: 'badge-gray',
    submitted: 'badge-blue',
    processing: 'badge-yellow',
    completed: 'badge-green',
    rejected: 'badge-red',
  }
  return <span className={map[status] ?? 'badge-gray'}>{status}</span>
}
