import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { AlertTriangle, VolumeX, CheckCircle, Bell, TestTube } from "lucide-react"
import { useBedPressureStore } from "@/stores/bedPressureStore"
import { useEffect, useState } from "react"

export function AlarmDashboard() {
  const { 
    activeAlarms, 
    isConnected,
    acknowledgeAlarm, 
    silenceAllAlarms 
  } = useBedPressureStore()

  const [unsilencedAlarms, setUnsilencedAlarms] = useState(0)
  const [testScenario, setTestScenario] = useState<string>('')

  // Update alarm counts
  useEffect(() => {
    const unsilenced = activeAlarms.filter(alarm => !alarm.silenced).length
    setUnsilencedAlarms(unsilenced)
  }, [activeAlarms])

  const handleTestScenario = async (scenario: string) => {
    try {
      setTestScenario(scenario)
      const response = await fetch('/api/test-scenarios', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ scenario })
      })
      
      if (response.ok) {
        console.log(`Applied ${scenario} test scenario`)
      }
    } catch (error) {
      console.error('Failed to apply test scenario:', error)
    } finally {
      setTimeout(() => setTestScenario(''), 2000)
    }
  }

  const getSystemStatus = () => {
    const alarmCount = activeAlarms.filter(a => a.type === 'alarm' && !a.silenced).length
    const warningCount = activeAlarms.filter(a => a.type === 'warning' && !a.silenced).length
    
    if (alarmCount > 0) return { status: 'ALARM', color: 'text-red-600 bg-red-50 border-red-200', count: alarmCount }
    if (warningCount > 0) return { status: 'WARNING', color: 'text-yellow-600 bg-yellow-50 border-yellow-200', count: warningCount }
    return { status: 'NORMAL', color: 'text-green-600 bg-green-50 border-green-200', count: 0 }
  }

  const systemStatus = getSystemStatus()

  return (
    <div className="space-y-4">
      {/* System Status Overview */}
      <Card className={`border-2 ${systemStatus.color}`}>
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className={`p-2 rounded-full ${systemStatus.color}`}>
                {systemStatus.status === 'ALARM' ? (
                  <AlertTriangle className="w-6 h-6 animate-pulse" />
                ) : systemStatus.status === 'WARNING' ? (
                  <AlertTriangle className="w-6 h-6" />
                ) : (
                  <CheckCircle className="w-6 h-6" />
                )}
              </div>
              <div>
                <CardTitle className={`text-lg ${systemStatus.status === 'ALARM' ? 'text-red-700' : systemStatus.status === 'WARNING' ? 'text-yellow-700' : 'text-green-700'}`}>
                  SYSTEM STATUS: {systemStatus.status}
                </CardTitle>
                <p className="text-sm text-gray-600">
                  {isConnected ? 'Hardware Connected' : 'Using Mock Data'} • 
                  {activeAlarms.length} Active Alarms • 
                  {unsilencedAlarms} Unsilenced
                </p>
              </div>
            </div>
            
            <div className="flex items-center gap-2">
              {systemStatus.count > 0 && (
                <Badge variant="destructive" className="text-lg px-3 py-1">
                  {systemStatus.count}
                </Badge>
              )}
              {unsilencedAlarms > 0 && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => silenceAllAlarms(300000)}
                  className="text-orange-600 hover:text-orange-700"
                >
                  <VolumeX className="w-4 h-4 mr-1" />
                  Silence All (5m)
                </Button>
              )}
            </div>
          </div>
        </CardHeader>
      </Card>

      {/* Active Alarms Summary */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardContent className="p-4 text-center">
            <div className="flex items-center justify-center gap-2 mb-2">
              <AlertTriangle className="w-5 h-5 text-red-600" />
              <span className="text-sm font-medium text-gray-600">Critical Alarms</span>
            </div>
            <p className="text-2xl font-bold text-red-600">
              {activeAlarms.filter(a => a.type === 'alarm' && !a.silenced).length}
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-4 text-center">
            <div className="flex items-center justify-center gap-2 mb-2">
              <AlertTriangle className="w-5 h-5 text-yellow-600" />
              <span className="text-sm font-medium text-gray-600">Warnings</span>
            </div>
            <p className="text-2xl font-bold text-yellow-600">
              {activeAlarms.filter(a => a.type === 'warning' && !a.silenced).length}
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-4 text-center">
            <div className="flex items-center justify-center gap-2 mb-2">
              <VolumeX className="w-5 h-5 text-gray-600" />
              <span className="text-sm font-medium text-gray-600">Silenced</span>
            </div>
            <p className="text-2xl font-bold text-gray-600">
              {activeAlarms.filter(a => a.silenced).length}
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-4 text-center">
            <div className="flex items-center justify-center gap-2 mb-2">
              <CheckCircle className="w-5 h-5 text-green-600" />
              <span className="text-sm font-medium text-gray-600">Acknowledged</span>
            </div>
            <p className="text-2xl font-bold text-green-600">
              {activeAlarms.filter(a => a.acknowledged).length}
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Test Scenarios */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <TestTube className="w-5 h-5" />
            Test Scenarios
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-5 gap-2">
            {[
              { name: 'normal', label: 'Normal', color: 'bg-green-100 text-green-700 hover:bg-green-200' },
              { name: 'warning', label: 'Warning', color: 'bg-yellow-100 text-yellow-700 hover:bg-yellow-200' },
              { name: 'alarm', label: 'Alarm', color: 'bg-red-100 text-red-700 hover:bg-red-200' },
              { name: 'escalation', label: 'Escalation', color: 'bg-orange-100 text-orange-700 hover:bg-orange-200' },
              { name: 'mixed', label: 'Mixed', color: 'bg-purple-100 text-purple-700 hover:bg-purple-200' }
            ].map(scenario => (
              <Button
                key={scenario.name}
                variant="outline"
                size="sm"
                onClick={() => handleTestScenario(scenario.name)}
                disabled={testScenario === scenario.name}
                className={`${scenario.color} border-0`}
              >
                {testScenario === scenario.name ? 'Applied!' : scenario.label}
              </Button>
            ))}
          </div>
          <p className="text-xs text-gray-500 mt-2">
            Click to simulate different alarm scenarios for testing
          </p>
        </CardContent>
      </Card>

      {/* Recent Alarm Activity */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Bell className="w-5 h-5" />
            Recent Alarm Activity
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-2 max-h-48 overflow-y-auto">
            {activeAlarms.length === 0 ? (
              <div className="text-center py-4">
                <CheckCircle className="w-8 h-8 text-green-500 mx-auto mb-2" />
                <p className="text-sm text-gray-500">No active alarms</p>
              </div>
            ) : (
              activeAlarms.slice(0, 5).map((alarm) => (
                <div
                  key={alarm.id}
                  className="flex items-center justify-between p-2 bg-gray-50 rounded border"
                >
                  <div className="flex items-center gap-2">
                    <AlertTriangle className={`w-4 h-4 ${
                      alarm.type === 'alarm' ? 'text-red-600' : 'text-yellow-600'
                    }`} />
                    <div>
                      <p className="text-sm font-medium">{alarm.sensorLabel}</p>
                      <p className="text-xs text-gray-600">
                        {alarm.type.toUpperCase()} • Value: {alarm.value.toFixed(0)} • {alarm.time}
                      </p>
                    </div>
                  </div>
                  
                  <div className="flex items-center gap-1">
                    {alarm.silenced && (
                      <Badge variant="secondary" className="text-xs">
                        <VolumeX className="w-3 h-3 mr-1" />
                        Silenced
                      </Badge>
                    )}
                    {alarm.acknowledged && (
                      <Badge variant="outline" className="text-xs">
                        <CheckCircle className="w-3 h-3 mr-1" />
                        ACK
                      </Badge>
                    )}
                    {!alarm.acknowledged && (
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => acknowledgeAlarm(alarm.id)}
                        className="text-xs h-6 px-2"
                      >
                        ACK
                      </Button>
                    )}
                  </div>
                </div>
              ))
            )}
          </div>
        </CardContent>
      </Card>
    </div>
  )
}