/**
 * 地块信息录入对话框
 * 用于从绘制工具或编辑工具保存地块到地块档案
 */

import { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { DrawGeometry } from './drawEditReducer';
import { Save, X, Tag, MapPin } from 'lucide-react';
import { toast } from 'sonner';

interface FieldEntryDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  geometry: DrawGeometry;
  onSaved?: (field: any) => void;
}

export function FieldEntryDialog({
  open,
  onOpenChange,
  geometry,
  onSaved
}: FieldEntryDialogProps) {
  const [formData, setFormData] = useState({
    code: '',
    name: '',
    area: 0,
    perimeter: 0,
    location: '',
    owner: '',
    soilType: 'loamy',
    landUseType: 'farmland',
    plantingMode: 'open-field',
    irrigationType: 'drip',
    tags: [],
    status: 'active',
    description: '',
  });

  const [tagInput, setTagInput] = useState('');

  // 初始化表单数据
  useEffect(() => {
    if (geometry && open) {
      // 自动生成地块编号和名称
      const fields = JSON.parse(localStorage.getItem('smart_agriculture_fields') || '[]');
      const count = fields.length + 1;

      // 将绘制的点转换为地理坐标（这里使用模拟数据）
      const coordinates = geometry.points.map((p, index) => ({
        lat: 39.9042 + (p.y - 300) / 10000,
        lng: 116.4074 + (p.x - 400) / 10000
      }));

      // 计算中心点
      const centerLat = coordinates.reduce((sum, p) => sum + p.lat, 0) / coordinates.length;
      const centerLng = coordinates.reduce((sum, p) => sum + p.lng, 0) / coordinates.length;

      setFormData({
        code: `FIELD-${String(count).padStart(3, '0')}`,
        name: `地块${String.fromCharCode(64 + count)}`,
        area: geometry.area || 0,
        perimeter: geometry.perimeter || 0,
        location: `北京市XX区`,
        owner: '',
        soilType: 'loamy',
        landUseType: 'farmland',
        plantingMode: 'open-field',
        irrigationType: 'drip',
        tags: [],
        status: 'active',
        description: `通过GIS工具绘制的${geometry.type === 'polygon' ? '多边形' : geometry.type === 'rectangle' ? '矩形' : ''}地块`,
      });
    }
  }, [geometry, open]);

  const handleSave = () => {
    // 验证必填项
    if (!formData.code?.trim()) {
      toast.error('请输入地块编号');
      return;
    }

    if (!formData.name?.trim()) {
      toast.error('请输入地块名称');
      return;
    }

    if (geometry.points.length < 3) {
      toast.error('地块边界数据无效');
      return;
    }

    try {
      // 保存到localStorage（地块档案）
      const fields = JSON.parse(localStorage.getItem('smart_agriculture_fields') || '[]');

      const newField = {
        id: `field-${Date.now()}`,
        code: formData.code!,
        name: formData.name!,
        area: formData.area!,
        perimeter: formData.perimeter || 0,
        location: formData.location || '',
        owner: formData.owner || '',
        soilType: formData.soilType!,
        landUseType: formData.landUseType!,
        plantingMode: formData.plantingMode!,
        irrigationType: formData.irrigationType || 'drip',
        tags: formData.tags || [],
        photos: [],
        documents: [],
        status: formData.status || 'active',
        description: formData.description || '',
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        createdBy: 'admin',
        currentVersion: 1,
        geometry: geometry,
      };

      fields.push(newField);
      localStorage.setItem('smart_agriculture_fields', JSON.stringify(fields));

      toast.success(`地块 ${newField.name} 已保存到地块档案`);

      // 调用回调
      if (onSaved) {
        onSaved(newField);
      }

      // 关闭对话框
      onOpenChange(false);
    } catch (error) {
      console.error('保存地块失败:', error);
      toast.error('保存失败，请重试');
    }
  };

  const handleAddTag = () => {
    if (tagInput.trim() && !formData.tags.includes(tagInput.trim())) {
      setFormData({
        ...formData,
        tags: [...formData.tags, tagInput.trim()],
      });
      setTagInput('');
    }
  };

  const handleRemoveTag = (tag: string) => {
    setFormData({
      ...formData,
      tags: formData.tags.filter(t => t !== tag),
    });
  };

  // 土壤类型选项
  const soilTypes = [
    { value: 'sandy', label: '沙土' },
    { value: 'loamy', label: '壤土' },
    { value: 'clay', label: '粘土' },
    { value: 'silt', label: '淤泥土' },
    { value: 'peat', label: '泥炭土' },
    { value: 'saline', label: '盐碱土' },
  ];

  // 种植模式选项
  const plantingModes = [
    { value: 'open-field', label: '露地' },
    { value: 'greenhouse', label: '大棚' },
    { value: 'orchard', label: '果园' },
    { value: 'paddy', label: '水田' },
    { value: 'dryland', label: '旱地' },
  ];

  // 灌溉方式选项
  const irrigationTypes = [
    { value: 'drip', label: '滴灌' },
    { value: 'sprinkler', label: '喷灌' },
    { value: 'flood', label: '漫灌' },
    { value: 'micro-sprinkler', label: '微喷' },
    { value: 'none', label: '无灌溉' },
  ];

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>新增地块</DialogTitle>
          <DialogDescription>
            填写地块信息并保存到地块档案管理
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6 py-4">
          {/* 几何信息汇总 */}
          <div className="p-4 bg-green-50 dark:bg-green-950 border border-green-200 dark:border-green-800 rounded-lg">
            <div className="flex items-center gap-2 mb-3">
              <MapPin className="w-4 h-4 text-green-600 dark:text-green-400" />
              <span className="text-sm text-green-800 dark:text-green-200">几何信息</span>
            </div>
            <div className="grid grid-cols-4 gap-4 text-sm">
              <div>
                <span className="text-muted-foreground">类型</span>
                <div className="mt-1">
                  {geometry.type === 'polygon' && '多边形'}
                  {geometry.type === 'rectangle' && '矩形'}
                  {geometry.type === 'line' && '线'}
                  {geometry.type === 'point' && '点'}
                </div>
              </div>
              <div>
                <span className="text-muted-foreground">顶点数</span>
                <div className="mt-1">{geometry.points.length} 个</div>
              </div>
              {geometry.area && geometry.area > 0 && (
                <div>
                  <span className="text-muted-foreground">面积</span>
                  <div className="mt-1 text-green-600 dark:text-green-400">{geometry.area.toFixed(2)} 亩</div>
                </div>
              )}
              {geometry.perimeter && (
                <div>
                  <span className="text-muted-foreground">周长</span>
                  <div className="mt-1 text-blue-600 dark:text-blue-400">{geometry.perimeter.toFixed(0)} 米</div>
                </div>
              )}
            </div>
          </div>

          {/* 基本信息 */}
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>地块编号 *</Label>
              <Input
                value={formData.code}
                onChange={(e) => setFormData({ ...formData, code: e.target.value })}
                placeholder="例如：FIELD-001"
              />
            </div>

            <div className="space-y-2">
              <Label>地块名称 *</Label>
              <Input
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                placeholder="例如：地块A"
              />
            </div>

            <div className="space-y-2">
              <Label>地块位置</Label>
              <Input
                value={formData.location}
                onChange={(e) => setFormData({ ...formData, location: e.target.value })}
                placeholder="例如：北京市XX区"
              />
            </div>

            <div className="space-y-2">
              <Label>责任人</Label>
              <Input
                value={formData.owner}
                onChange={(e) => setFormData({ ...formData, owner: e.target.value })}
                placeholder="例如：张三"
              />
            </div>
          </div>

          {/* 地块属性 */}
          <div className="grid grid-cols-3 gap-4">
            <div className="space-y-2">
              <Label>土壤类型</Label>
              <Select
                value={formData.soilType}
                onValueChange={(value: any) => setFormData({ ...formData, soilType: value })}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {soilTypes.map(type => (
                    <SelectItem key={type.value} value={type.value}>
                      {type.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label>种植模式</Label>
              <Select
                value={formData.plantingMode}
                onValueChange={(value: any) => setFormData({ ...formData, plantingMode: value })}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {plantingModes.map(mode => (
                    <SelectItem key={mode.value} value={mode.value}>
                      {mode.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label>灌溉方式</Label>
              <Select
                value={formData.irrigationType}
                onValueChange={(value: any) => setFormData({ ...formData, irrigationType: value })}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {irrigationTypes.map(type => (
                    <SelectItem key={type.value} value={type.value}>
                      {type.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          {/* 标签 */}
          <div className="space-y-2">
            <Label>地块标签</Label>
            <div className="flex gap-2">
              <Input
                value={tagInput}
                onChange={(e) => setTagInput(e.target.value)}
                onKeyPress={(e) => {
                  if (e.key === 'Enter') {
                    e.preventDefault();
                    handleAddTag();
                  }
                }}
                placeholder="输入标签后按回车添加"
              />
              <Button type="button" onClick={handleAddTag} variant="outline">
                <Tag className="w-4 h-4" />
              </Button>
            </div>
            {formData.tags && formData.tags.length > 0 && (
              <div className="flex flex-wrap gap-2 mt-2">
                {formData.tags.map((tag) => (
                  <Badge key={tag} variant="secondary">
                    {tag}
                    <button
                      onClick={() => handleRemoveTag(tag)}
                      className="ml-2 hover:text-destructive"
                    >
                      <X className="w-3 h-3" />
                    </button>
                  </Badge>
                ))}
              </div>
            )}
          </div>

          {/* 备注 */}
          <div className="space-y-2">
            <Label>备注信息</Label>
            <Textarea
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              placeholder="输入地块相关的备注信息"
              rows={3}
            />
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button onClick={handleSave} className="bg-green-600 hover:bg-green-700">
            <Save className="w-4 h-4 mr-2" />
            保存到地块档案
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}