import { useState } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../../ui/dialog';
import { Button } from '../../ui/button';
import { Input } from '../../ui/input';
import { Label } from '../../ui/label';
import { Checkbox } from '../../ui/checkbox';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../../ui/select';
import { Card } from '../../ui/card';
import { Badge } from '../../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../../ui/tabs';
import { GeoFence, GeoPoint } from '../../../types/equipment';
import { MachineryRecord } from '../../../types/machinery';
import { MapPin, Circle, Pentagon, Plus, Trash2 } from 'lucide-react';
import { useForm } from 'react-hook-form@7.55.0';

interface GeoFenceFormProps {
  open: boolean;
  onClose: () => void;
  onSave: (fence: Partial<GeoFence>) => void;
  editingFence?: GeoFence | null;
  machinery: MachineryRecord[];
}

export function GeoFenceForm({ open, onClose, onSave, editingFence, machinery }: GeoFenceFormProps) {
  const [fenceType, setFenceType] = useState<'circle' | 'polygon'>(editingFence?.type || 'polygon');
  const [selectedMachinery, setSelectedMachinery] = useState<string[]>(editingFence?.machineryIds || []);
  const [alertOnEnter, setAlertOnEnter] = useState(editingFence?.alertOnEnter || false);
  const [alertOnExit, setAlertOnExit] = useState(editingFence?.alertOnExit || false);
  const [countWorkHours, setCountWorkHours] = useState(editingFence?.countWorkHours || false);
  
  // 圆形围栏参数
  const [circleCenter, setCircleCenter] = useState<GeoPoint>(
    editingFence?.center || { latitude: 36.6512, longitude: 117.1201 }
  );
  const [circleRadius, setCircleRadius] = useState<number>(editingFence?.radius || 500);
  
  // 多边形围栏参数
  const [polygonPoints, setPolygonPoints] = useState<GeoPoint[]>(
    editingFence?.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 },
    ]
  );

  const { register, handleSubmit, formState: { errors } } = useForm({
    defaultValues: {
      name: editingFence?.name || '',
    }
  });

  const onSubmit = (data: any) => {
    const fence: Partial<GeoFence> = {
      name: data.name,
      type: fenceType,
      machineryIds: selectedMachinery,
      alertOnEnter,
      alertOnExit,
      countWorkHours,
      enabled: true,
    };

    if (fenceType === 'circle') {
      fence.center = circleCenter;
      fence.radius = circleRadius;
    } else {
      fence.points = polygonPoints;
    }

    onSave(fence);
  };

  const toggleMachinery = (machineryId: string) => {
    setSelectedMachinery(prev => 
      prev.includes(machineryId)
        ? prev.filter(id => id !== machineryId)
        : [...prev, machineryId]
    );
  };

  const addPolygonPoint = () => {
    const lastPoint = polygonPoints[polygonPoints.length - 1];
    setPolygonPoints([
      ...polygonPoints,
      {
        latitude: lastPoint.latitude + 0.001,
        longitude: lastPoint.longitude + 0.001,
      }
    ]);
  };

  const updatePolygonPoint = (index: number, field: 'latitude' | 'longitude', value: number) => {
    const newPoints = [...polygonPoints];
    newPoints[index][field] = value;
    setPolygonPoints(newPoints);
  };

  const removePolygonPoint = (index: number) => {
    if (polygonPoints.length > 3) {
      setPolygonPoints(polygonPoints.filter((_, i) => i !== index));
    }
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{editingFence ? '编辑电子围栏' : '新建电子围栏'}</DialogTitle>
          <DialogDescription className="sr-only">
            {editingFence ? '编辑电子围栏配置' : '新建电子围栏配置'}
          </DialogDescription>
        </DialogHeader>

        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="space-y-6">
            {/* 基本信息 */}
            <Card className="p-4">
              <h3 className="mb-4">基本信息</h3>
              <div className="space-y-4">
                <div>
                  <Label htmlFor="name">围栏名称 *</Label>
                  <Input
                    id="name"
                    {...register('name', { required: '请输入围栏名称' })}
                    placeholder="如：1号作业区"
                  />
                  {errors.name && (
                    <p className="text-sm text-destructive mt-1">{errors.name.message}</p>
                  )}
                </div>

                <div>
                  <Label>围栏类型</Label>
                  <Tabs value={fenceType} onValueChange={(v) => setFenceType(v as 'circle' | 'polygon')}>
                    <TabsList className="grid w-full grid-cols-2">
                      <TabsTrigger value="polygon">
                        <Pentagon className="w-4 h-4 mr-2" />
                        多边形
                      </TabsTrigger>
                      <TabsTrigger value="circle">
                        <Circle className="w-4 h-4 mr-2" />
                        圆形
                      </TabsTrigger>
                    </TabsList>
                  </Tabs>
                </div>
              </div>
            </Card>

            {/* 围栏坐标 */}
            <Card className="p-4">
              <h3 className="mb-4">围栏坐标</h3>
              
              {fenceType === 'circle' ? (
                <div className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label htmlFor="centerLat">中心点纬度 *</Label>
                      <Input
                        id="centerLat"
                        type="number"
                        step="0.000001"
                        value={circleCenter.latitude}
                        onChange={(e) => setCircleCenter({
                          ...circleCenter,
                          latitude: parseFloat(e.target.value)
                        })}
                        placeholder="36.6512"
                      />
                    </div>
                    <div>
                      <Label htmlFor="centerLng">中心点经度 *</Label>
                      <Input
                        id="centerLng"
                        type="number"
                        step="0.000001"
                        value={circleCenter.longitude}
                        onChange={(e) => setCircleCenter({
                          ...circleCenter,
                          longitude: parseFloat(e.target.value)
                        })}
                        placeholder="117.1201"
                      />
                    </div>
                  </div>
                  <div>
                    <Label htmlFor="radius">半径 (米) *</Label>
                    <Input
                      id="radius"
                      type="number"
                      value={circleRadius}
                      onChange={(e) => setCircleRadius(parseFloat(e.target.value))}
                      placeholder="500"
                    />
                  </div>

                  {/* 地图预览占位 */}
                  <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">
                    <div className="text-center">
                      <MapPin className="w-12 h-12 mx-auto mb-3 text-success" />
                      <p className="text-sm text-muted-foreground">
                        圆形围栏预览<br />
                        中心: {circleCenter.latitude.toFixed(6)}, {circleCenter.longitude.toFixed(6)}<br />
                        半径: {circleRadius} 米
                      </p>
                    </div>
                  </div>
                </div>
              ) : (
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <Label>多边形顶点 (至少3个点)</Label>
                    <Button
                      type="button"
                      size="sm"
                      variant="outline"
                      onClick={addPolygonPoint}
                    >
                      <Plus className="w-4 h-4 mr-2" />
                      添加顶点
                    </Button>
                  </div>

                  <div className="space-y-2 max-h-64 overflow-y-auto">
                    {polygonPoints.map((point, index) => (
                      <Card key={index} className="p-3">
                        <div className="flex items-center gap-3">
                          <Badge variant="outline">点 {index + 1}</Badge>
                          <div className="flex-1 grid grid-cols-2 gap-2">
                            <Input
                              type="number"
                              step="0.000001"
                              value={point.latitude}
                              onChange={(e) => updatePolygonPoint(index, 'latitude', parseFloat(e.target.value))}
                              placeholder="纬度"
                            />
                            <Input
                              type="number"
                              step="0.000001"
                              value={point.longitude}
                              onChange={(e) => updatePolygonPoint(index, 'longitude', parseFloat(e.target.value))}
                              placeholder="经度"
                            />
                          </div>
                          {polygonPoints.length > 3 && (
                            <Button
                              type="button"
                              variant="ghost"
                              size="sm"
                              onClick={() => removePolygonPoint(index)}
                            >
                              <Trash2 className="w-4 h-4 text-destructive" />
                            </Button>
                          )}
                        </div>
                      </Card>
                    ))}
                  </div>

                  {/* 地图预览占位 */}
                  <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">
                    <div className="text-center">
                      <Pentagon className="w-12 h-12 mx-auto mb-3 text-info" />
                      <p className="text-sm text-muted-foreground">
                        多边形围栏预览<br />
                        {polygonPoints.length} 个顶点
                      </p>
                    </div>
                  </div>
                </div>
              )}
            </Card>

            {/* 关联农机 */}
            <Card className="p-4">
              <h3 className="mb-4">关联农机</h3>
              <div className="space-y-2 max-h-48 overflow-y-auto">
                {machinery.map((m) => (
                  <div key={m.id} className="flex items-center space-x-2 p-2 hover:bg-gray-50 rounded">
                    <Checkbox
                      id={`machinery-${m.id}`}
                      checked={selectedMachinery.includes(m.id)}
                      onCheckedChange={() => toggleMachinery(m.id)}
                    />
                    <label
                      htmlFor={`machinery-${m.id}`}
                      className="flex-1 cursor-pointer text-sm"
                    >
                      {m.name} - {m.model}
                    </label>
                  </div>
                ))}
              </div>
              {selectedMachinery.length === 0 && (
                <p className="text-sm text-muted-foreground mt-2">请至少选择一台农机</p>
              )}
            </Card>

            {/* 报警设置 */}
            <Card className="p-4">
              <h3 className="mb-4">报警设置</h3>
              <div className="space-y-3">
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="alertOnEnter"
                    checked={alertOnEnter}
                    onCheckedChange={(checked) => setAlertOnEnter(checked as boolean)}
                  />
                  <label htmlFor="alertOnEnter" className="cursor-pointer text-sm">
                    进入围栏时报警
                  </label>
                </div>

                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="alertOnExit"
                    checked={alertOnExit}
                    onCheckedChange={(checked) => setAlertOnExit(checked as boolean)}
                  />
                  <label htmlFor="alertOnExit" className="cursor-pointer text-sm">
                    离开围栏时报警
                  </label>
                </div>

                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="countWorkHours"
                    checked={countWorkHours}
                    onCheckedChange={(checked) => setCountWorkHours(checked as boolean)}
                  />
                  <label htmlFor="countWorkHours" className="cursor-pointer text-sm">
                    启用工时核算（仅计算围栏内作业时间）
                  </label>
                </div>
              </div>
            </Card>

            {/* 使用说明 */}
            <Card className="p-4 bg-info-muted border-info">
              <h4 className="mb-2 text-muted-foreground">使用提示</h4>
              <ul className="space-y-1 text-sm text-muted-foreground">
                <li>• 可在地图上手动绘制围栏区域，或输入精确坐标</li>
                <li>• 多边形围栏至少需要3个顶点</li>
                <li>• 支持同时设置进入和离开报警</li>
                <li>• 工时核算功能可用于精确计算围栏内的作业时长</li>
              </ul>
            </Card>
          </div>

          <DialogFooter className="mt-6">
            <Button type="button" variant="outline" onClick={onClose}>
              取消
            </Button>
            <Button type="submit" disabled={selectedMachinery.length === 0}>
              {editingFence ? '保存修改' : '创建围栏'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
