'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 { Switch } from '@/components/ui/switch';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { Textarea } from '@/components/ui/textarea';
import { Checkbox } from '@/components/ui/checkbox';
import {
  AlertTriangle,
  Bell,
  CheckCircle2,
  Eye,
  MessageSquare,
  Phone,
  Mail,
  Send,
  AlertCircle,
  Activity,
  Clock,
  CloudRain,
  Sun,
  Snowflake,
  Bug,
  Wind,
} from 'lucide-react';
import { toast } from 'sonner';

type RiskLevel = '无风险' | '轻度风险' | '中度风险' | '高度风险';
type RiskType = '干旱' | '涝渍' | '低温' | '高温' | '病虫害' | '强风';
type DisposalStatus = '未查看' | '已查看' | '处理中' | '已完成';

interface PushRule {
  id: string;
  name: string;
  riskLevel: RiskLevel;
  condition: string;
  pushDelay: string;
  recipients: string[];
  channels: ('消息中心' | '短信' | '邮件')[];
  enabled: boolean;
}

interface WarningRecord {
  id: string;
  fieldId: string;
  fieldName: string;
  riskType: RiskType;
  riskLevel: RiskLevel;
  warningTime: string;
  recipients: string[];
  channels: ('消息中心' | '短信' | '邮件')[];
  status: DisposalStatus;
  viewTime?: string;
  disposalPlan?: string;
  disposalPlanSubmitTime?: string;
  disposalResult?: string;
  completedTime?: string;
  responsible: string;
}

export default function PushPage() {
  const [showRuleDialog, setShowRuleDialog] = useState(false);
  const [showRecordDetail, setShowRecordDetail] = useState(false);
  const [editingRule, setEditingRule] = useState<PushRule | null>(null);
  const [selectedRecord, setSelectedRecord] = useState<WarningRecord | null>(null);
  const [disposalPlan, setDisposalPlan] = useState('');
  const [disposalResult, setDisposalResult] = useState('');

  // 推送规则
  const [pushRules, setPushRules] = useState<PushRule[]>([
    {
      id: 'rule-1',
      name: '高度风险规则',
      riskLevel: '高度风险',
      condition: '风险评分 ≥ 80',
      pushDelay: '立即推送',
      recipients: ['地块责任人', '系统管理员'],
      channels: ['消息中心', '短信', '邮件'],
      enabled: true,
    },
    {
      id: 'rule-2',
      name: '中度风险规则',
      riskLevel: '中度风险',
      condition: '风险评分 ≥ 60',
      pushDelay: '5分钟内推送',
      recipients: ['地块责任人'],
      channels: ['消息中心', '短信'],
      enabled: true,
    },
    {
      id: 'rule-3',
      name: '轻度风险规则',
      riskLevel: '轻度风险',
      condition: '风险评分 ≥ 40',
      pushDelay: '15分钟内推送',
      recipients: ['地块责任人'],
      channels: ['消息中心'],
      enabled: true,
    },
  ]);

  // 预警记录
  const [warningRecords] = useState<WarningRecord[]>([
    {
      id: 'warn-1',
      fieldId: 'field-2',
      fieldName: '西区2号地',
      riskType: '涝渍',
      riskLevel: '高度风险',
      warningTime: '2024-10-15 14:33',
      recipients: ['张三', '李四', '王五'],
      channels: ['消息中心', '短信', '邮件'],
      status: '处理中',
      viewTime: '2024-10-15 14:35',
      disposalPlan: '已启动排水系统，派遣工作组前往现场清理排水沟渠',
      disposalPlanSubmitTime: '2024-10-15 14:40',
      responsible: '张三',
    },
    {
      id: 'warn-2',
      fieldId: 'field-1',
      fieldName: '东区1号地',
      riskType: '干旱',
      riskLevel: '中度风险',
      warningTime: '2024-10-15 14:35',
      recipients: ['张三', '李四'],
      channels: ['消息中心', '短信'],
      status: '已查看',
      viewTime: '2024-10-15 14:36',
      responsible: '李四',
    },
    {
      id: 'warn-3',
      fieldId: 'field-3',
      fieldName: '南区3号地',
      riskType: '低温',
      riskLevel: '轻度风险',
      warningTime: '2024-10-15 14:30',
      recipients: ['王五'],
      channels: ['消息中心'],
      status: '已完成',
      viewTime: '2024-10-15 14:31',
      disposalPlan: '准备保温材料，延迟夜间灌溉',
      disposalPlanSubmitTime: '2024-10-15 14:33',
      disposalResult: '已完成保温材料准备，作物情况良好',
      completedTime: '2024-10-15 15:20',
      responsible: '王五',
    },
    {
      id: 'warn-4',
      fieldId: 'field-4',
      fieldName: '北区4号地',
      riskType: '病虫害',
      riskLevel: '中度风险',
      warningTime: '2024-10-15 14:28',
      recipients: ['张三', '赵六'],
      channels: ['消息中心', '短信', '邮件'],
      status: '未查看',
      responsible: '赵六',
    },
  ]);

  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 getStatusIcon = (status: DisposalStatus) => {
    switch (status) {
      case '未查看': return <AlertCircle className="w-4 h-4" />;
      case '已查看': return <Eye className="w-4 h-4" />;
      case '处理中': return <Activity className="w-4 h-4" />;
      case '已完成': return <CheckCircle2 className="w-4 h-4" />;
      default: return <Clock className="w-4 h-4" />;
    }
  };

  const getStatusColor = (status: DisposalStatus) => {
    switch (status) {
      case '未查看': return 'text-red-600 bg-red-50';
      case '已查看': return 'text-blue-600 bg-blue-50';
      case '处理中': return 'text-orange-600 bg-orange-50';
      case '已完成': return 'text-green-600 bg-green-50';
      default: return 'text-gray-600 bg-gray-50';
    }
  };

  // 推送规则管理
  const handleAddRule = () => {
    setEditingRule(null);
    setShowRuleDialog(true);
  };

  const handleEditRule = (rule: PushRule) => {
    setEditingRule(rule);
    setShowRuleDialog(true);
  };

  const handleDeleteRule = (ruleId: string) => {
    setPushRules(pushRules.filter(r => r.id !== ruleId));
    toast.success('推送规则已删除');
  };

  const handleSaveRule = () => {
    if (editingRule) {
      // 编辑
      setPushRules(pushRules.map(r => r.id === editingRule.id ? editingRule : r));
      toast.success('推送规则已更新');
    } else {
      // 新增
      const newRule: PushRule = {
        id: `rule-${Date.now()}`,
        name: '新规则',
        riskLevel: '中度风险',
        condition: '',
        pushDelay: '立即推送',
        recipients: [],
        channels: ['消息中心'],
        enabled: true,
      };
      setPushRules([...pushRules, newRule]);
      toast.success('推送规则已创建');
    }
    setShowRuleDialog(false);
  };

  // 推送记录操作
  const handleViewRecord = (record: WarningRecord) => {
    setSelectedRecord(record);
    setDisposalPlan(record.disposalPlan || '');
    setDisposalResult(record.disposalResult || '');
    setShowRecordDetail(true);
  };

  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>

      {/* 推送渠道配置 */}
      <Card className="p-6">
        <h3 className="mb-4 flex items-center gap-2">
          <Send className="w-5 h-5 text-green-600" />
          推送渠道配置
        </h3>
        <div className="grid grid-cols-3 gap-4">
          <div className="p-4 bg-blue-50 dark:bg-blue-950 rounded-lg">
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center gap-2">
                <MessageSquare className="w-5 h-5 text-blue-600 dark:text-blue-400" />
                <span className="font-medium">消息中心</span>
              </div>
              <Switch defaultChecked />
            </div>
            <p className="text-xs text-muted-foreground">实时推送至系统消息中心</p>
            <p className="text-xs text-blue-600 dark:text-blue-400 mt-2">✓ 已启用</p>
          </div>

          <div className="p-4 bg-green-50 dark:bg-green-950 rounded-lg">
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center gap-2">
                <Phone className="w-5 h-5 text-green-600 dark:text-green-400" />
                <span className="font-medium">短信通知</span>
              </div>
              <Switch defaultChecked />
            </div>
            <p className="text-xs text-muted-foreground">发送短信至责任人手机</p>
            <p className="text-xs text-green-600 dark:text-green-400 mt-2">✓ 已启用</p>
          </div>

          <div className="p-4 bg-purple-50 dark:bg-purple-950 rounded-lg">
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center gap-2">
                <Mail className="w-5 h-5 text-purple-600 dark:text-purple-400" />
                <span className="font-medium">邮件通知</span>
              </div>
              <Switch defaultChecked />
            </div>
            <p className="text-xs text-muted-foreground">发送邮件至责任人邮箱</p>
            <p className="text-xs text-purple-600 dark:text-purple-400 mt-2">✓ 已启用</p>
          </div>
        </div>
      </Card>

      {/* 推送规则 */}
      <Card className="p-6">
        <div className="flex items-center justify-between mb-4">
          <h3 className="flex items-center gap-2">
            <Bell className="w-5 h-5 text-orange-600" />
            预警推送规则
          </h3>
          <Button onClick={handleAddRule} className="bg-green-600 hover:bg-green-700">
            <Bell className="w-4 h-4 mr-2" />
            新增规则
          </Button>
        </div>
        <div className="space-y-4">
          {pushRules.map(rule => (
            <div key={rule.id} className="p-4 bg-muted rounded-lg">
              <div className="flex items-center justify-between mb-3">
                <div className="flex items-center gap-3">
                  <h4 className="flex items-center gap-2">
                    {rule.riskLevel === '高度风险' && <AlertTriangle className="w-4 h-4 text-red-500" />}
                    {rule.riskLevel === '中度风险' && <AlertCircle className="w-4 h-4 text-orange-500" />}
                    {rule.riskLevel === '轻度风险' && <AlertTriangle className="w-4 h-4 text-yellow-500" />}
                    {rule.name}
                  </h4>
                  <Badge className={getRiskLevelColor(rule.riskLevel)}>
                    {rule.riskLevel}
                  </Badge>
                  <Badge variant="outline" className="text-xs">
                    {rule.pushDelay}
                  </Badge>
                  {!rule.enabled && (
                    <Badge variant="outline" className="text-xs text-gray-500">
                      已禁用
                    </Badge>
                  )}
                </div>
                <div className="flex gap-2">
                  <Button size="sm" variant="outline" onClick={() => handleEditRule(rule)}>
                    编辑
                  </Button>
                  <Button
                    size="sm"
                    variant="outline"
                    className="text-red-600 hover:text-red-700"
                    onClick={() => handleDeleteRule(rule.id)}
                  >
                    删除
                  </Button>
                </div>
              </div>
              <p className="text-sm text-muted-foreground mb-2">
                触发条件: {rule.condition}
              </p>
              <div className="grid grid-cols-2 gap-4">
                <div className="text-sm">
                  <p className="text-xs text-muted-foreground mb-1">推送对象:</p>
                  <div className="flex gap-1 flex-wrap">
                    {rule.recipients.map((recipient, i) => (
                      <Badge key={i} variant="outline" className="text-xs">
                        {recipient}
                      </Badge>
                    ))}
                  </div>
                </div>
                <div className="text-sm">
                  <p className="text-xs text-muted-foreground mb-1">推送渠道:</p>
                  <div className="flex gap-1 flex-wrap">
                    {rule.channels.map((channel, i) => (
                      <Badge key={i} variant="outline" className="text-xs">
                        {channel}
                      </Badge>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </Card>

      {/* 最近推送记录 */}
      <Card className="p-6">
        <h3 className="mb-4 flex items-center gap-2">
          <CheckCircle2 className="w-5 h-5 text-blue-600" />
          最近推送记录
        </h3>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50 dark:bg-gray-800">
              <tr>
                <th className="px-4 py-3 text-left text-xs">推送时间</th>
                <th className="px-4 py-3 text-left text-xs">地块</th>
                <th className="px-4 py-3 text-left text-xs">风险类型</th>
                <th className="px-4 py-3 text-center text-xs">风险等级</th>
                <th className="px-4 py-3 text-left text-xs">推送渠道</th>
                <th className="px-4 py-3 text-left text-xs">责任人</th>
                <th className="px-4 py-3 text-center text-xs">状态</th>
                <th className="px-4 py-3 text-center text-xs">操作</th>
              </tr>
            </thead>
            <tbody>
              {warningRecords.slice(0, 10).map(record => (
                <tr key={record.id} className="border-t hover:bg-gray-50 dark:hover:bg-gray-800">
                  <td className="px-4 py-3 text-sm">{record.warningTime}</td>
                  <td className="px-4 py-3 text-sm">{record.fieldName}</td>
                  <td className="px-4 py-3 text-sm">
                    <div className="flex items-center gap-2">
                      {getRiskTypeIcon(record.riskType)}
                      {record.riskType}
                    </div>
                  </td>
                  <td className="px-4 py-3 text-center">
                    <Badge className={getRiskLevelColor(record.riskLevel)}>
                      {record.riskLevel}
                    </Badge>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex gap-1">
                      {record.channels.map((channel, i) => (
                        <Badge key={i} variant="outline" className="text-xs">
                          {channel}
                        </Badge>
                      ))}
                    </div>
                  </td>
                  <td className="px-4 py-3 text-sm">
                    {record.responsible}
                  </td>
                  <td className="px-4 py-3 text-center">
                    <div className={`inline-flex items-center gap-1 px-2 py-1 rounded-full ${getStatusColor(record.status)}`}>
                      {getStatusIcon(record.status)}
                      <span className="text-xs">{record.status}</span>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex gap-1 justify-center">
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => handleViewRecord(record)}
                      >
                        <Eye className="w-3 h-3 mr-1" />
                        查看
                      </Button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>

      {/* 推送规则编辑对话框 */}
      <Dialog open={showRuleDialog} onOpenChange={setShowRuleDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>{editingRule ? '编辑推送规则' : '新增推送规则'}</DialogTitle>
            <DialogDescription>配置预警推送规则参数</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <label className="text-sm font-medium">规则名称</label>
              <input
                type="text"
                className="mt-2 w-full px-3 py-2 border rounded-md bg-background"
                placeholder="请输入规则名称"
                defaultValue={editingRule?.name || ''}
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="text-sm font-medium">风险等级</label>
                <select
                  className="mt-2 w-full px-3 py-2 border rounded-md bg-background"
                  defaultValue={editingRule?.riskLevel || '中度风险'}
                >
                  <option value="高度风险">高度风险</option>
                  <option value="中度风险">中度风险</option>
                  <option value="轻度风险">轻度风险</option>
                </select>
              </div>

              <div>
                <label className="text-sm font-medium">推送延迟</label>
                <select
                  className="mt-2 w-full px-3 py-2 border rounded-md bg-background"
                  defaultValue={editingRule?.pushDelay || '立即推送'}
                >
                  <option value="立即推送">立即推送</option>
                  <option value="5分钟内推送">5分钟内推送</option>
                  <option value="15分钟内推送">15分钟内推送</option>
                  <option value="30分钟内推送">30分钟内推送</option>
                </select>
              </div>
            </div>

            <div>
              <label className="text-sm font-medium">触发条件</label>
              <select
                className="mt-2 w-full px-3 py-2 border rounded-md bg-background"
                defaultValue={editingRule?.condition || '风险评分 ≥ 60'}
              >
                <option value="风险评分 ≥ 80">风险评分 ≥ 80</option>
                <option value="风险评分 ≥ 70">风险评分 ≥ 70</option>
                <option value="风险评分 ≥ 60">风险评分 ≥ 60</option>
                <option value="风险评分 ≥ 50">风险评分 ≥ 50</option>
                <option value="风险评分 ≥ 40">风险评分 ≥ 40</option>
                <option value="指数超阈值 50%以上">指数超阈值 50%以上</option>
                <option value="指数超阈值 30%以上">指数超阈值 30%以上</option>
                <option value="指数超阈值 20%以上">指数超阈值 20%以上</option>
                <option value="指数超阈值 10%以上">指数超阈值 10%以上</option>
              </select>
            </div>

            <div>
              <label className="text-sm font-medium">推送对象</label>
              <div className="mt-2 space-y-2">
                <div className="flex items-center gap-2">
                  <Checkbox id="recipient-1" defaultChecked />
                  <label htmlFor="recipient-1" className="text-sm cursor-pointer">地块责任人</label>
                </div>
                <div className="flex items-center gap-2">
                  <Checkbox id="recipient-2" />
                  <label htmlFor="recipient-2" className="text-sm cursor-pointer">系统管理员</label>
                </div>
              </div>
            </div>

            <div>
              <label className="text-sm font-medium">推送渠道</label>
              <div className="mt-2 space-y-2">
                <div className="flex items-center gap-2">
                  <Checkbox id="channel-1" defaultChecked />
                  <label htmlFor="channel-1" className="text-sm cursor-pointer">消息中心</label>
                </div>
                <div className="flex items-center gap-2">
                  <Checkbox id="channel-2" defaultChecked />
                  <label htmlFor="channel-2" className="text-sm cursor-pointer">短信通知</label>
                </div>
                <div className="flex items-center gap-2">
                  <Checkbox id="channel-3" />
                  <label htmlFor="channel-3" className="text-sm cursor-pointer">邮件通知</label>
                </div>
              </div>
            </div>

            <div className="flex items-center gap-2">
              <Checkbox id="enabled" defaultChecked={editingRule?.enabled ?? true} />
              <label htmlFor="enabled" className="text-sm cursor-pointer">启用此规则</label>
            </div>

            <div className="flex gap-2 justify-end">
              <Button variant="outline" onClick={() => setShowRuleDialog(false)}>
                取消
              </Button>
              <Button
                className="bg-green-600 hover:bg-green-700"
                onClick={handleSaveRule}
              >
                <CheckCircle2 className="w-4 h-4 mr-2" />
                保存
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 推送记录详情对话框 */}
      <Dialog open={showRecordDetail} onOpenChange={setShowRecordDetail}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>推送记录详情</DialogTitle>
            <DialogDescription>查看和处理预警推送记录</DialogDescription>
          </DialogHeader>
          {selectedRecord && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-sm font-medium">地块名称</label>
                  <div className="mt-1 text-sm">{selectedRecord.fieldName}</div>
                </div>
                <div>
                  <label className="text-sm font-medium">风险类型</label>
                  <div className="mt-1 flex items-center gap-2 text-sm">
                    {getRiskTypeIcon(selectedRecord.riskType)}
                    {selectedRecord.riskType}
                  </div>
                </div>
                <div>
                  <label className="text-sm font-medium">风险等级</label>
                  <div className="mt-1">
                    <Badge className={getRiskLevelColor(selectedRecord.riskLevel)}>
                      {selectedRecord.riskLevel}
                    </Badge>
                  </div>
                </div>
                <div>
                  <label className="text-sm font-medium">推送时间</label>
                  <div className="mt-1 text-sm">{selectedRecord.warningTime}</div>
                </div>
                <div>
                  <label className="text-sm font-medium">责任人</label>
                  <div className="mt-1 text-sm">{selectedRecord.responsible}</div>
                </div>
                <div>
                  <label className="text-sm font-medium">当前状态</label>
                  <div className="mt-1">
                    <div className={`inline-flex items-center gap-1 px-2 py-1 rounded-full ${getStatusColor(selectedRecord.status)}`}>
                      {getStatusIcon(selectedRecord.status)}
                      <span className="text-xs">{selectedRecord.status}</span>
                    </div>
                  </div>
                </div>
              </div>

              <div>
                <label className="text-sm font-medium">推送渠道</label>
                <div className="mt-1 flex gap-2">
                  {selectedRecord.channels.map((channel, i) => (
                    <Badge key={i} variant="outline">
                      {channel}
                    </Badge>
                  ))}
                </div>
              </div>

              {selectedRecord.viewTime && (
                <div>
                  <label className="text-sm font-medium">查看时间</label>
                  <div className="mt-1 text-sm">{selectedRecord.viewTime}</div>
                </div>
              )}

              {selectedRecord.disposalPlan && (
                <div>
                  <label className="text-sm font-medium">处置方案</label>
                  <div className="mt-1 text-sm">{selectedRecord.disposalPlan}</div>
                </div>
              )}

              {selectedRecord.disposalResult && (
                <div>
                  <label className="text-sm font-medium">处置结果</label>
                  <div className="mt-1 text-sm">{selectedRecord.disposalResult}</div>
                </div>
              )}

              {selectedRecord.completedTime && (
                <div>
                  <label className="text-sm font-medium">完成时间</label>
                  <div className="mt-1 text-sm">{selectedRecord.completedTime}</div>
                </div>
              )}

              <div className="flex gap-2 justify-end">
                <Button variant="outline" onClick={() => setShowRecordDetail(false)}>
                  关闭
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}