import { useState, useEffect } from 'react';
import { Card } from '../../ui/card';
import { Button } from '../../ui/button';
import { Badge } from '../../ui/badge';
import { Plus, Circle, Pentagon, AlertTriangle, Edit } from 'lucide-react';
import { GeoFence as GeoFenceType, GeoFenceAlert } from '../../../types/equipment';
import { MachineryRecord } from '../../../types/machinery';
import { machineryStorage } from '../../../lib/machineryStorage';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../../ui/table';
import { GeoFenceForm } from './GeoFenceForm';
import { toast } from 'sonner@2.0.3';

export function GeoFence() {
  const [fences, setFences] = useState<GeoFenceType[]>([]);
  const [alerts, setAlerts] = useState<GeoFenceAlert[]>([]);
  const [machinery, setMachinery] = useState<MachineryRecord[]>([]);
  const [showForm, setShowForm] = useState(false);
  const [editingFence, setEditingFence] = useState<GeoFenceType | null>(null);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = () => {
    const machineryData = machineryStorage.getAllMachinery();
    setMachinery(machineryData);

    // 加载围栏数据
    const fencesData = localStorage.getItem('smart_agriculture_geofences');
    if (fencesData) {
      setFences(JSON.parse(fencesData));
    } else {
      // 初始化示例围栏数据
      const mockFences: GeoFenceType[] = [
      {
        id: 'fence-1',
        name: '1号作业区',
        type: 'polygon',
        points: [
          { latitude: 36.6512, longitude: 117.1201 },
          { latitude: 36.6532, longitude: 117.1201 },
          { latitude: 36.6532, longitude: 117.1251 },
          { latitude: 36.6512, longitude: 117.1251 },
        ],
        machineryIds: [machineryData[0]?.id || ''],
        alertOnExit: true,
        alertOnEnter: false,
        countWorkHours: true,
        enabled: true,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        createdBy: '系统管理员',
      },
      {
        id: 'fence-2',
        name: '禁入区域',
        type: 'circle',
        center: { latitude: 36.6500, longitude: 117.1200 },
        radius: 500,
        machineryIds: machineryData.map(m => m.id),
        alertOnExit: false,
        alertOnEnter: true,
        countWorkHours: false,
        enabled: true,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        createdBy: '系统管理员',
      },
    ];
      localStorage.setItem('smart_agriculture_geofences', JSON.stringify(mockFences));
      setFences(mockFences);
    }

    // 加载报警记录
    const alertsData = localStorage.getItem('smart_agriculture_geofence_alerts');
    if (alertsData) {
      setAlerts(JSON.parse(alertsData));
    } else {
      // 初始化示例报警记录
      const mockAlerts: GeoFenceAlert[] = [
      {
        id: 'alert-1',
        fenceId: 'fence-1',
        fenceName: '1号作业区',
        machineryId: machineryData[0]?.id || '',
        machineryName: machineryData[0]?.name,
        alertType: 'exit',
        location: { latitude: 36.6510, longitude: 117.1252 },
        alertedAt: '2024-10-12T14:30:00',
        acknowledged: false,
      },
    ];
      localStorage.setItem('smart_agriculture_geofence_alerts', JSON.stringify(mockAlerts));
      setAlerts(mockAlerts);
    }
  };

  const handleSaveFence = (fenceData: Partial<GeoFenceType>) => {
    if (editingFence) {
      // 更新现有围栏
      const updated: GeoFenceType = {
        ...editingFence,
        ...fenceData,
        updatedAt: new Date().toISOString(),
        updatedBy: '系统管理员',
      };
      const newFences = fences.map(f => f.id === updated.id ? updated : f);
      setFences(newFences);
      localStorage.setItem('smart_agriculture_geofences', JSON.stringify(newFences));
      toast.success('围栏更新成功');
    } else {
      // 创建新围栏
      const newFence: GeoFenceType = {
        id: `fence-${Date.now()}`,
        ...fenceData as GeoFenceType,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        createdBy: '系统管理员',
        updatedBy: '系统管理员',
      };
      const newFences = [...fences, newFence];
      setFences(newFences);
      localStorage.setItem('smart_agriculture_geofences', JSON.stringify(newFences));
      toast.success('围栏创建成功');
    }
    setShowForm(false);
    setEditingFence(null);
  };

  const handleEdit = (fence: GeoFenceType) => {
    setEditingFence(fence);
    setShowForm(true);
  };

  const handleDelete = (fenceId: string) => {
    if (confirm('确定要删除此围栏吗？')) {
      const newFences = fences.filter(f => f.id !== fenceId);
      setFences(newFences);
      localStorage.setItem('smart_agriculture_geofences', JSON.stringify(newFences));
      toast.success('围栏删除成功');
    }
  };

  const toggleFenceEnabled = (fenceId: string) => {
    const newFences = fences.map(f => 
      f.id === fenceId
        ? { ...f, enabled: !f.enabled, updatedAt: new Date().toISOString() }
        : f
    );
    setFences(newFences);
    localStorage.setItem('smart_agriculture_geofences', JSON.stringify(newFences));
    const fence = newFences.find(f => f.id === fenceId);
    toast.success(`围栏已${fence?.enabled ? '启用' : '禁用'}`);
  };

  const handleAcknowledge = (alertId: string) => {
    const newAlerts = alerts.map(alert => 
      alert.id === alertId
        ? { ...alert, acknowledged: true, acknowledgedBy: '系统管理员', acknowledgedAt: new Date().toISOString() }
        : alert
    );
    setAlerts(newAlerts);
    localStorage.setItem('smart_agriculture_geofence_alerts', JSON.stringify(newAlerts));
    toast.success('报警已确认');
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-primary">电子围栏</h2>
          <p className="text-muted-foreground">地理围栏管理和越界报警</p>
        </div>
        <Button onClick={() => {
          setEditingFence(null);
          setShowForm(true);
        }}>
          <Plus className="w-4 h-4 mr-2" />
          新建围栏
        </Button>
      </div>

      {/* 统计 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">总围栏数</div>
          <div className="mt-1">{fences.length}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">已启用</div>
          <div className="mt-1 text-success">
            {fences.filter(f => f.enabled).length}
          </div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">待确认报警</div>
          <div className="mt-1 text-warning">
            {alerts.filter(a => !a.acknowledged).length}
          </div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">监控设备</div>
          <div className="mt-1">{machinery.length}</div>
        </Card>
      </div>

      {/* 地图显示 */}
      <Card className="p-6">
        <h3 className="mb-4">围栏地图</h3>
        <div className="aspect-video bg-gradient-to-br from-green-50 to-blue-50 rounded-lg flex items-center justify-center border-2 border-dashed relative">
          <div className="absolute inset-0 p-6">
            {fences.map((fence, index) => (
              <div
                key={fence.id}
                className="absolute border-2 border-blue-500 rounded"
                style={{
                  left: `${15 + index * 30}%`,
                  top: '30%',
                  width: fence.type === 'circle' ? '120px' : '150px',
                  height: fence.type === 'circle' ? '120px' : '100px',
                  borderRadius: fence.type === 'circle' ? '50%' : '8px',
                  borderColor: fence.alertOnEnter ? '#ef4444' : '#3b82f6',
                }}
              >
                <div className="absolute -top-6 left-1/2 -translate-x-1/2 whitespace-nowrap bg-white px-2 py-1 rounded shadow-sm text-xs">
                  {fence.name}
                </div>
              </div>
            ))}
          </div>
          <div className="text-center z-10">
            <Pentagon className="w-12 h-12 mx-auto mb-3 text-info" />
            <p className="text-sm text-muted-foreground">电子围栏可视化</p>
          </div>
        </div>
      </Card>

      {/* 围栏列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>围栏名称</TableHead>
              <TableHead>类型</TableHead>
              <TableHead>关联农机</TableHead>
              <TableHead>越界报警</TableHead>
              <TableHead>工时核算</TableHead>
              <TableHead>状态</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {fences.map(fence => (
              <TableRow key={fence.id}>
                <TableCell>{fence.name}</TableCell>
                <TableCell>
                  <div className="flex items-center gap-2">
                    {fence.type === 'circle' ? (
                      <Circle className="w-4 h-4" />
                    ) : (
                      <Pentagon className="w-4 h-4" />
                    )}
                    {fence.type === 'circle' ? '圆形' : '多边形'}
                  </div>
                </TableCell>
                <TableCell>{fence.machineryIds.length} 台</TableCell>
                <TableCell>
                  <div className="text-sm">
                    {fence.alertOnEnter && <div>进入报警</div>}
                    {fence.alertOnExit && <div>离开报警</div>}
                  </div>
                </TableCell>
                <TableCell>
                  {fence.countWorkHours ? (
                    <Badge variant="secondary" className="bg-success-muted text-success">
                      启用
                    </Badge>
                  ) : (
                    <span className="text-muted-foreground">-</span>
                  )}
                </TableCell>
                <TableCell>
                  <Badge variant="secondary" className={fence.enabled ? 'bg-success-muted text-success' : 'bg-muted text-muted-foreground'}>
                    {fence.enabled ? '已启用' : '已禁用'}
                  </Badge>
                </TableCell>
                <TableCell>
                  <div className="flex gap-2">
                    <Button 
                      variant="ghost" 
                      size="sm"
                      onClick={() => handleEdit(fence)}
                    >
                      <Edit className="w-4 h-4" />
                    </Button>
                    <Button 
                      variant="ghost" 
                      size="sm"
                      onClick={() => toggleFenceEnabled(fence.id)}
                    >
                      {fence.enabled ? '禁用' : '启用'}
                    </Button>
                    <Button 
                      variant="ghost" 
                      size="sm"
                      className="text-destructive"
                      onClick={() => handleDelete(fence.id)}
                    >
                      删除
                    </Button>
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </Card>

      {/* 报警记录 */}
      <Card className="p-6">
        <h3 className="mb-4">报警记录</h3>
        {alerts.length === 0 ? (
          <div className="text-center text-muted-foreground py-8">
            暂无报警记录
          </div>
        ) : (
          <div className="space-y-3">
            {alerts.map(alert => (
              <div
                key={alert.id}
                className={`p-4 border rounded-lg ${
                  alert.acknowledged ? 'bg-muted' : 'bg-warning-muted border-warning'
                }`}
              >
                <div className="flex items-start justify-between">
                  <div className="flex items-start gap-3">
                    <AlertTriangle className={`w-5 h-5 ${alert.acknowledged ? 'text-muted-foreground' : 'text-warning'} mt-0.5`} />
                    <div>
                      <h4 className="mb-1">
                        {alert.machineryName} {alert.alertType === 'exit' ? '离开' : '进入'} {alert.fenceName}
                      </h4>
                      <div className="text-sm text-muted-foreground">
                        时间: {new Date(alert.alertedAt).toLocaleString('zh-CN')}
                      </div>
                      {alert.acknowledged && (
                        <div className="text-xs text-muted-foreground mt-1">
                          已由 {alert.acknowledgedBy} 确认
                        </div>
                      )}
                    </div>
                  </div>
                  {!alert.acknowledged && (
                    <Button
                      size="sm"
                      onClick={() => handleAcknowledge(alert.id)}
                    >
                      确认
                    </Button>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </Card>

      {/* 功能说明 */}
      <Card className="p-6 bg-info-muted border-info">
        <h4 className="mb-3 text-muted-foreground">围栏功能</h4>
        <ul className="space-y-2 text-sm text-muted-foreground">
          <li>• 支持圆形和多边形围栏绘制</li>
          <li>• 实时判断农机位置与围栏关系</li>
          <li>• 越界立即触发报警（平台消息、短信）</li>
          <li>• 可用于工时核算（仅计算围栏内作业时间）</li>
          <li>• 支持围栏启用/禁用管理</li>
        </ul>
      </Card>

      {/* 新增/编辑围栏对话框 */}
      <GeoFenceForm
        open={showForm}
        onClose={() => {
          setShowForm(false);
          setEditingFence(null);
        }}
        onSave={handleSaveFence}
        editingFence={editingFence}
        machinery={machinery}
      />
    </div>
  );
}
