import { useState, useEffect } from 'react'
import { databases, DATABASE_ID, COLLECTIONS, Query } from '../lib/appwrite'
import { FaTicket, FaClipboardList, FaClock, FaCircleCheck } from 'react-icons/fa6'

export default function DashboardPage() {
  const [stats, setStats] = useState({
    totalTickets: 0,
    openTickets: 0,
    closedTickets: 0,
    pendingTickets: 0
  })
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    async function fetchStats() {
      try {
        const [total, open, closed, pending] = await Promise.all([
          databases.listDocuments(DATABASE_ID, COLLECTIONS.WORKORDERS, [Query.limit(1)]),
          databases.listDocuments(DATABASE_ID, COLLECTIONS.WORKORDERS, [Query.equal('status', 'Open'), Query.limit(1)]),
          databases.listDocuments(DATABASE_ID, COLLECTIONS.WORKORDERS, [Query.equal('status', 'Closed'), Query.limit(1)]),
          databases.listDocuments(DATABASE_ID, COLLECTIONS.WORKORDERS, [Query.equal('status', 'Awaiting'), Query.limit(1)])
        ])
        
        setStats({
          totalTickets: total.total,
          openTickets: open.total,
          closedTickets: closed.total,
          pendingTickets: pending.total
        })
      } catch (err) {
        console.error('Error fetching stats:', err)
      } finally {
        setLoading(false)
      }
    }
    fetchStats()
  }, [])

  const StatCard = ({ icon: Icon, label, value, color }) => (
    <div className="stat-card" style={{ borderLeft: `4px solid ${color}` }}>
      <div className="stat-icon" style={{ color }}>
        <Icon size={32} />
      </div>
      <div className="stat-info">
        <span className="stat-value">{loading ? '...' : value}</span>
        <span className="stat-label">{label}</span>
      </div>
    </div>
  )

  return (
    <div className="main-content">
      <header className="text-center mb-2">
        <h2>Dashboard</h2>
      </header>

      <div className="stats-grid">
        <StatCard icon={FaTicket} label="Total Tickets" value={stats.totalTickets} color="#2196F3" />
        <StatCard icon={FaClipboardList} label="Open Tickets" value={stats.openTickets} color="#4CAF50" />
        <StatCard icon={FaClock} label="Pending" value={stats.pendingTickets} color="#FF9800" />
        <StatCard icon={FaCircleCheck} label="Closed" value={stats.closedTickets} color="#9E9E9E" />
      </div>

      <div className="dashboard-section mt-4">
        <h3>Quick Actions</h3>
        <div className="quick-actions">
          <a href="/tickets" className="btn btn-teal">View All Tickets</a>
          <a href="/reports" className="btn btn-dark">Generate Report</a>
        </div>
      </div>
    </div>
  )
}
