'use client';

import { useState } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Switch } from '@/components/ui/switch';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import {
  AlertTriangle,
  CheckCircle2,
  Clock,
  CloudRain,
  RefreshCw,
  Snowflake,
  Sun,
  ThermometerSnowflake,
  TrendingUp,
  Wifi,
  WifiOff,
  Zap,
  Bug,
  Wind,
  Activity,
  MapPin,
  AlertCircle,
} from 'lucide-react';
import { toast } from 'sonner';
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  Area,
  AreaChart,
} from 'recharts';

type RiskLevel = '无风险' | '轻度风险' | '中度风险' | '高度风险';
type RiskType = '干旱' | '涝渍' | '低温' | '高温' | '病虫害' | '强风';

interface RiskData {
  id: string;
  fieldId: string;
  fieldName: string;
  riskType: RiskType;
  riskLevel: RiskLevel;
  riskScore: number;
  indexValue: number;
  threshold: number;
  updateTime: string;
  sensorStatus: 'online' | 'offline';
  location: string;
  expectedImpact: string;
  suggestedActions: string[];
}

export default function RiskMonitoringPage() {
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [selectedField, setSelectedField] = useState('all');

  // 模拟实时风险数据
  const [riskData, setRiskData] = useState<RiskData[]>([
    {
      id: 'risk-1',
      fieldId: 'field-1',
      fieldName: '东区1号地',
      riskType: '干旱',
      riskLevel: '中度风险',
      riskScore: 65,
      indexValue: 0.35,
      threshold: 0.50,
      updateTime: '2024-10-15 14:35',
      sensorStatus: 'online',
      location: '东经120.15°, 北纬30.25°',
      expectedImpact: '预计未来3天无降雨，土壤湿度将持续下降，可能影响水稻生长',
      suggestedActions: ['启动喷灌系统', '增加灌溉频次', '监测土壤湿度'],
    },
    {
      id: 'risk-2',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      riskLevel: '高度风险',
      riskType: '涝渍',
      riskScore: 85,
      indexValue: 0.82,
      threshold: 0.70,
      updateTime: '2024-10-15 14:33',
      sensorStatus: 'online',
      location: '东经120.12°, 北纬30.28°',
      expectedImpact: '连续强降雨导致积水严重，可能造成玉米根系缺氧',
      suggestedActions: ['开启排水系统', '清理排水沟渠', '加强巡查'],
    },
    {
      id: 'risk-3',
      fieldId: 'field-3',
      fieldName: '南区3号地',
      riskType: '低温',
      riskLevel: '轻度风险',
      riskScore: 45,
      indexValue: 8.5,
      threshold: 10.0,
      updateTime: '2024-10-15 14:30',
      sensorStatus: 'online',
      location: '东经120.18°, 北纬30.22°',
      expectedImpact: '夜间温度可能降至8℃以下，需注意作物保温',
      suggestedActions: ['准备保温材料', '关注天气预报', '适当延迟灌溉'],
    },
    {
      id: 'risk-4',
      fieldId: 'field-4',
      fieldName: '北区4号地',
      riskType: '病虫害',
      riskLevel: '中度风险',
      riskScore: 70,
      indexValue: 68,
      threshold: 50,
      updateTime: '2024-10-15 14:28',
      sensorStatus: 'offline',
      location: '东经120.20°, 北纬30.30°',
      expectedImpact: '温湿度适宜病虫害发生，需加强监测和防治',
      suggestedActions: ['喷洒预防性农药', '设置诱虫灯', '加强田间巡查'],
    },
  ]);

  // 历史风险趋势数据
  const riskTrendData = [
    { time: '10:00', 干旱指数: 0.25, 涝渍指数: 0.15, 温度: 22 },
    { time: '11:00', 干旱指数: 0.28, 涝渍指数: 0.20, 温度: 24 },
    { time: '12:00', 干旱指数: 0.30, 涝渍指数: 0.35, 温度: 26 },
    { time: '13:00', 干旱指数: 0.32, 涝渍指数: 0.55, 温度: 27 },
    { time: '14:00', 干旱指数: 0.35, 涝渍指数: 0.82, 温度: 25 },
  ];

  const getRiskLevelColor = (level: RiskLevel) => {
    switch (level) {
      case '无风险': return 'bg-gray-500 text-white';
      case '轻度风险': return 'bg-yellow-500 text-white';
      case '中度风险': return 'bg-orange-500 text-white';
      case '高度风险': return 'bg-red-500 text-white';
      default: return 'bg-gray-500 text-white';
    }
  };

  const getRiskTypeIcon = (type: RiskType) => {
    switch (type) {
      case '干旱': return <Sun className="w-5 h-5" />;
      case '涝渍': return <CloudRain className="w-5 h-5" />;
      case '低温': return <Snowflake className="w-5 h-5" />;
      case '高温': return <ThermometerSnowflake className="w-5 h-5" />;
      case '病虫害': return <Bug className="w-5 h-5" />;
      case '强风': return <Wind className="w-5 h-5" />;
      default: return <AlertTriangle className="w-5 h-5" />;
    }
  };

  const handleRefresh = () => {
    toast.success('风险数据已刷新');
  };

  const filteredRiskData = selectedField === 'all'
    ? riskData
    : riskData.filter(r => r.fieldId === selectedField);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">实时风险预测</h2>
          <p className="text-muted-foreground">
            实时监测地块风险，智能预警推送与处置跟踪
          </p>
        </div>
        <div className="flex gap-2">
          <div className="flex items-center gap-2 px-4 py-2 bg-card rounded-lg border">
            <RefreshCw className="w-4 h-4 text-muted-foreground" />
            <span className="text-sm text-muted-foreground">自动刷新</span>
            <Switch checked={autoRefresh} onCheckedChange={setAutoRefresh} />
          </div>
          <Button variant="outline" onClick={handleRefresh}>
            <RefreshCw className="w-4 h-4 mr-2" />
            刷新数据
          </Button>
        </div>
      </div>

      {/* 地块筛选 */}
      <Card className="p-4">
        <div className="flex items-center gap-4">
          <label className="text-sm font-medium">筛选地块:</label>
          <Select value={selectedField} onValueChange={setSelectedField}>
            <SelectTrigger className="w-64">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部地块</SelectItem>
              <SelectItem value="field-1">东区1号地</SelectItem>
              <SelectItem value="field-2">西区2号地</SelectItem>
              <SelectItem value="field-3">南区3号地</SelectItem>
              <SelectItem value="field-4">北区4号地</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </Card>

      {/* 风险统计 */}
      <div className="grid grid-cols-4 gap-4">
        <Card className="p-6 bg-gradient-to-br from-red-50 to-red-100 dark:from-red-950 dark:to-red-900">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">高度风险</p>
              <p className="mt-2 text-3xl text-red-600 dark:text-red-400">
                {filteredRiskData.filter(r => r.riskLevel === '高度风险').length}
              </p>
            </div>
            <AlertTriangle className="w-12 h-12 text-red-600 dark:text-red-400 opacity-50" />
          </div>
        </Card>

        <Card className="p-6 bg-gradient-to-br from-orange-50 to-orange-100 dark:from-orange-950 dark:to-orange-900">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">中度风险</p>
              <p className="mt-2 text-3xl text-orange-600 dark:text-orange-400">
                {filteredRiskData.filter(r => r.riskLevel === '中度风险').length}
              </p>
            </div>
            <AlertCircle className="w-12 h-12 text-orange-600 dark:text-orange-400 opacity-50" />
          </div>
        </Card>

        <Card className="p-6 bg-gradient-to-br from-yellow-50 to-yellow-100 dark:from-yellow-950 dark:to-yellow-900">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">轻度风险</p>
              <p className="mt-2 text-3xl text-yellow-600 dark:text-yellow-400">
                {filteredRiskData.filter(r => r.riskLevel === '轻度风险').length}
              </p>
            </div>
            <AlertTriangle className="w-12 h-12 text-yellow-600 dark:text-yellow-400 opacity-50" />
          </div>
        </Card>

        <Card className="p-6 bg-gradient-to-br from-green-50 to-green-100 dark:from-green-950 dark:to-green-900">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">在线传感器</p>
              <p className="mt-2 text-3xl text-green-600 dark:text-green-400">
                {filteredRiskData.filter(r => r.sensorStatus === 'online').length}/{filteredRiskData.length}
              </p>
            </div>
            <Wifi className="w-12 h-12 text-green-600 dark:text-green-400 opacity-50" />
          </div>
        </Card>
      </div>

      {/* 风险监测列表 */}
      <Card className="p-6">
        <h3 className="mb-4 flex items-center gap-2">
          <Activity className="w-5 h-5 text-blue-600" />
          实时风险监测
        </h3>
        <div className="space-y-4">
          {filteredRiskData.map(risk => (
            <Card key={risk.id} className="p-4 border-l-4 hover:shadow-md transition-shadow" style={{
              borderLeftColor:
                risk.riskLevel === '高度风险' ? '#ef4444' :
                risk.riskLevel === '中度风险' ? '#f97316' :
                risk.riskLevel === '轻度风险' ? '#eab308' : '#6b7280'
            }}>
              <div className="flex items-start justify-between mb-3">
                <div className="flex items-start gap-3">
                  <div className={`p-2 rounded-lg ${
                    risk.riskType === '干旱' ? 'bg-orange-100 text-orange-600 dark:bg-orange-900 dark:text-orange-400' :
                    risk.riskType === '涝渍' ? 'bg-blue-100 text-blue-600 dark:bg-blue-900 dark:text-blue-400' :
                    risk.riskType === '低温' ? 'bg-cyan-100 text-cyan-600 dark:bg-cyan-900 dark:text-cyan-400' :
                    risk.riskType === '病虫害' ? 'bg-green-100 text-green-600 dark:bg-green-900 dark:text-green-400' :
                    'bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400'
                  }`}>
                    {getRiskTypeIcon(risk.riskType)}
                  </div>
                  <div>
                    <div className="flex items-center gap-2 mb-1">
                      <h4>{risk.fieldName}</h4>
                      <Badge className={getRiskLevelColor(risk.riskLevel)}>
                        {risk.riskLevel}
                      </Badge>
                      <Badge variant="outline" className="text-xs">
                        {risk.riskType}
                      </Badge>
                      {risk.sensorStatus === 'online' ? (
                        <Wifi className="w-4 h-4 text-green-500" />
                      ) : (
                        <WifiOff className="w-4 h-4 text-red-500" />
                      )}
                    </div>
                    <p className="text-sm text-muted-foreground flex items-center gap-2">
                      <MapPin className="w-3 h-3" />
                      {risk.location}
                    </p>
                  </div>
                </div>
                <div className="text-right">
                  <p className="text-xs text-muted-foreground">风险评分</p>
                  <p className="text-2xl font-medium text-red-600">{risk.riskScore}</p>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4 mb-3">
                <div className="p-3 bg-muted rounded-lg">
                  <p className="text-xs text-muted-foreground mb-1">指标值</p>
                  <div className="flex items-center gap-2">
                    <Progress value={(risk.indexValue / risk.threshold) * 100} className="flex-1" />
                    <span className="text-sm font-medium">
                      {risk.indexValue.toFixed(2)}
                    </span>
                  </div>
                  <p className="text-xs text-muted-foreground mt-1">
                    阈值: {risk.threshold.toFixed(2)}
                  </p>
                </div>
                <div className="p-3 bg-muted rounded-lg">
                  <p className="text-xs text-muted-foreground mb-1">更新时间</p>
                  <p className="text-sm font-medium flex items-center gap-1">
                    <Clock className="w-3 h-3" />
                    {risk.updateTime}
                  </p>
                </div>
              </div>

              <div className="p-3 bg-orange-50 dark:bg-orange-950 border border-orange-200 dark:border-orange-800 rounded-lg mb-3">
                <p className="text-xs text-orange-900 dark:text-orange-200 mb-1 flex items-center gap-1">
                  <AlertTriangle className="w-3 h-3" />
                  预期影响
                </p>
                <p className="text-sm text-orange-800 dark:text-orange-300">{risk.expectedImpact}</p>
              </div>

              <div className="p-3 bg-green-50 dark:bg-green-950 border border-green-200 dark:border-green-800 rounded-lg">
                <p className="text-xs text-green-900 dark:text-green-200 mb-2 flex items-center gap-1">
                  <Zap className="w-3 h-3" />
                  建议措施
                </p>
                <ul className="space-y-1">
                  {risk.suggestedActions.map((action, index) => (
                    <li key={index} className="text-sm text-green-800 dark:text-green-300 flex items-start gap-2">
                      <CheckCircle2 className="w-4 h-4 mt-0.5 flex-shrink-0" />
                      <span>{action}</span>
                    </li>
                  ))}
                </ul>
              </div>
            </Card>
          ))}
        </div>
      </Card>

      {/* 风险趋势图 */}
      <Card className="p-6">
        <h3 className="mb-4 flex items-center gap-2">
          <TrendingUp className="w-5 h-5 text-purple-600" />
          风险指数趋势
        </h3>
        <div className="h-80">
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart data={riskTrendData}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="time" />
              <YAxis />
              <Tooltip />
              <Legend />
              <Area type="monotone" dataKey="干旱指数" stroke="#f97316" fill="#fed7aa" />
              <Area type="monotone" dataKey="涝渍指数" stroke="#3b82f6" fill="#bfdbfe" />
            </AreaChart>
          </ResponsiveContainer>
        </div>
      </Card>

      {/* 算法说明 */}
      <Card className="p-4 bg-blue-50 dark:bg-blue-950 border-blue-200 dark:border-blue-800">
        <div className="flex items-start gap-2">
          <Zap className="w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" />
          <div className="text-sm text-blue-900 dark:text-blue-200">
            <p className="mb-2">风险计算算法：</p>
            <ul className="space-y-1 text-xs">
              <li>• <strong>干旱指数</strong>: 基于土壤湿度、降雨量、蒸发量计算，指数&lt;0.5触发预警</li>
              <li>• <strong>涝渍指数</strong>: 基于降雨强度、土壤排水性、地表积水深度，指数&gt;0.7触发预警</li>
              <li>• <strong>低温强度</strong>: 基于气温、持续时长、作物耐寒性，温度&lt;10°C触发预警</li>
              <li>• <strong>病虫害风险</strong>: 基于温湿度、历史数据、作物生长期，综合评分&gt;50触发预警</li>
              <li>• <strong>风险等级</strong>: 根据指数偏离阈值程度自动分级（轻度/中度/高度）</li>
            </ul>
          </div>
        </div>
      </Card>
    </div>
  );
}