import React from 'react'
import { 
  Thermometer, 
  Play, 
  Pause, 
  Square, 
  AlertTriangle,
  CheckCircle,
  Clock,
  Gauge
} from 'lucide-react'
import { useQuery } from '@tanstack/react-query'
import { api } from '../services/api'
import { useSystemStore } from '../stores/systemStore'

const Dashboard: React.FC = () => {
  const { systemStatus } = useSystemStore()

  // Fetch real-time process status
  const { data: processStatus } = useQuery({
    queryKey: ['process-status'],
    queryFn: api.getProcessStatus,
    refetchInterval: 2000, // Refresh every 2 seconds
  })

  // Fetch hardware status
  const { data: hardwareStatus } = useQuery({
    queryKey: ['hardware-status'],
    queryFn: api.getHardwareStatus,
    refetchInterval: 5000, // Refresh every 5 seconds
  })

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'running':
        return <Play className="w-5 h-5 text-green-600" />
      case 'paused':
        return <Pause className="w-5 h-5 text-yellow-600" />
      case 'error':
        return <AlertTriangle className="w-5 h-5 text-red-600" />
      default:
        return <Square className="w-5 h-5 text-gray-400" />
    }
  }

  const formatDuration = (seconds: number | null) => {
    if (!seconds) return '00:00:00'
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    const secs = seconds % 60
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }

  return (
    <div className="space-y-6">
      {/* Page header */}
      <div className="flex items-center justify-between">
        <h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
        <div className="flex items-center space-x-2 text-sm text-gray-500">
          <Clock className="w-4 h-4" />
          <span>Last updated: {new Date().toLocaleTimeString()}</span>
        </div>
      </div>

      {/* Status cards grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {/* System Status Card */}
        <div className="card">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-600">System Status</p>
              <p className="text-2xl font-bold text-gray-900">
                {systemStatus?.system_status || 'Unknown'}
              </p>
            </div>
            <div className={`p-3 rounded-full ${
              systemStatus?.system_status === 'healthy' ? 'bg-green-100' :
              systemStatus?.system_status === 'warning' ? 'bg-yellow-100' : 
              'bg-red-100'
            }`}>
              <CheckCircle className={`w-6 h-6 ${
                systemStatus?.system_status === 'healthy' ? 'text-green-600' :
                systemStatus?.system_status === 'warning' ? 'text-yellow-600' : 
                'text-red-600'
              }`} />
            </div>
          </div>
        </div>

        {/* Process Status Card */}
        <div className="card">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-600">Process Status</p>
              <p className="text-2xl font-bold text-gray-900">
                {processStatus?.status || 'Idle'}
              </p>
            </div>
            <div className="p-3 rounded-full bg-blue-100">
              {getStatusIcon(processStatus?.status || 'idle')}
            </div>
          </div>
        </div>

        {/* Temperature Card */}
        <div className="card">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-600">Temperature</p>
              <p className="text-2xl font-bold text-gray-900">
                {processStatus?.current_temperature?.toFixed(1) || '--'}°C
              </p>
              {processStatus?.target_temperature && (
                <p className="text-sm text-gray-500">
                  Target: {processStatus.target_temperature.toFixed(1)}°C
                </p>
              )}
            </div>
            <div className="p-3 rounded-full bg-orange-100">
              <Thermometer className="w-6 h-6 text-orange-600" />
            </div>
          </div>
        </div>

        {/* Active Alarms Card */}
        <div className="card">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-600">Active Alarms</p>
              <p className="text-2xl font-bold text-gray-900">
                {systemStatus?.active_alarms || 0}
              </p>
            </div>
            <div className={`p-3 rounded-full ${
              (systemStatus?.active_alarms || 0) > 0 ? 'bg-red-100' : 'bg-green-100'
            }`}>
              <AlertTriangle className={`w-6 h-6 ${
                (systemStatus?.active_alarms || 0) > 0 ? 'text-red-600' : 'text-green-600'
              }`} />
            </div>
          </div>
        </div>
      </div>

      {/* Process Information */}
      {processStatus && processStatus.is_running && (
        <div className="card">
          <div className="card-header">
            <h3 className="card-title">Current Process</h3>
          </div>
          <div className="card-content">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              <div>
                <p className="text-sm font-medium text-gray-600">Recipe</p>
                <p className="text-lg font-semibold text-gray-900">
                  {processStatus.recipe_name || 'Unknown Recipe'}
                </p>
              </div>
              <div>
                <p className="text-sm font-medium text-gray-600">Phase</p>
                <p className="text-lg font-semibold text-gray-900">
                  {processStatus.current_phase || 'Unknown'}
                </p>
              </div>
              <div>
                <p className="text-sm font-medium text-gray-600">Duration</p>
                <p className="text-lg font-semibold text-gray-900">
                  {formatDuration(processStatus.duration_seconds)}
                </p>
              </div>
            </div>

            {processStatus.temperature_error && Math.abs(processStatus.temperature_error) > 1 && (
              <div className="mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-md">
                <div className="flex items-center">
                  <AlertTriangle className="w-4 h-4 text-yellow-600 mr-2" />
                  <span className="text-sm text-yellow-800">
                    Temperature error: {processStatus.temperature_error.toFixed(1)}°C
                  </span>
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Hardware Status */}
      {hardwareStatus && (
        <div className="card">
          <div className="card-header">
            <h3 className="card-title">Hardware Status</h3>
          </div>
          <div className="card-content">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {/* Connection Status */}
              <div className="flex items-center space-x-3">
                <div className={`w-3 h-3 rounded-full ${
                  hardwareStatus.connection_status === 'connected' ? 'bg-green-500' : 'bg-red-500'
                }`} />
                <div>
                  <p className="text-sm font-medium text-gray-600">Connection</p>
                  <p className="text-sm text-gray-900">{hardwareStatus.connection_status}</p>
                </div>
              </div>

              {/* Modbus Status */}
              <div className="flex items-center space-x-3">
                <div className={`w-3 h-3 rounded-full ${
                  hardwareStatus.modbus_status === 'online' ? 'bg-green-500' : 'bg-red-500'
                }`} />
                <div>
                  <p className="text-sm font-medium text-gray-600">Modbus</p>
                  <p className="text-sm text-gray-900">{hardwareStatus.modbus_status}</p>
                </div>
              </div>

              {/* Last Communication */}
              <div className="flex items-center space-x-3">
                <Gauge className="w-4 h-4 text-gray-400" />
                <div>
                  <p className="text-sm font-medium text-gray-600">Last Comm</p>
                  <p className="text-sm text-gray-900">
                    {new Date(hardwareStatus.last_communication).toLocaleTimeString()}
                  </p>
                </div>
              </div>
            </div>

            {/* Temperature Sensors */}
            {hardwareStatus.temperature_sensors && hardwareStatus.temperature_sensors.length > 0 && (
              <div className="mt-4">
                <h4 className="text-sm font-medium text-gray-600 mb-2">Temperature Sensors</h4>
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
                  {hardwareStatus.temperature_sensors.map((sensor) => (
                    <div key={sensor.id} className="bg-gray-50 rounded-lg p-3">
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium text-gray-700">{sensor.name}</span>
                        <div className={`w-2 h-2 rounded-full ${
                          sensor.status === 'normal' ? 'bg-green-500' :
                          sensor.status === 'warning' ? 'bg-yellow-500' : 'bg-red-500'
                        }`} />
                      </div>
                      <p className="text-lg font-bold text-gray-900">
                        {sensor.current_temp_c.toFixed(1)}°C
                      </p>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Quick Actions */}
      <div className="card">
        <div className="card-header">
          <h3 className="card-title">Quick Actions</h3>
        </div>
        <div className="card-content">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <button className="btn btn-primary btn-lg">
              Start Process
            </button>
            <button className="btn btn-warning btn-lg">
              Pause Process
            </button>
            <button className="btn btn-secondary btn-lg">
              View Recipes
            </button>
            <button className="btn btn-danger btn-lg">
              Emergency Stop
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}

export default Dashboard
