import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Textarea } from '../ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Badge } from '../ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../ui/dialog';
import { Field, GeoCoordinate, SoilType, LandUseType, PlantingMode, IrrigationType } from '../../types/field';
import { 
  Map, 
  Upload, 
  Save, 
  X, 
  Plus, 
  MapPin, 
  FileText, 
  Image as ImageIcon,
  Calendar,
  User,
  Tag,
  Layers,
  AlertCircle
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

export function FieldEntry() {
  const [formData, setFormData] = useState<Partial<Field>>({
    code: '',
    name: '',
    area: 0,
    perimeter: 0,
    location: '',
    coordinates: [],
    centerPoint: { lat: 0, lng: 0 },
    soilType: 'loamy',
    landUseType: 'farmland',
    plantingMode: 'open-field',
    irrigationType: 'drip',
    owner: '',
    tags: [],
    photos: [],
    documents: [],
    status: 'active',
  });

  const [showMapDrawer, setShowMapDrawer] = useState(false);
  const [showImportDialog, setShowImportDialog] = useState(false);
  const [customTags, setCustomTags] = useState<string[]>([]);
  const [tagInput, setTagInput] = useState('');

  // 土壤类型选项
  const soilTypes = [
    { value: 'sandy', label: '沙土', description: '透气性好，保水性差' },
    { value: 'loamy', label: '壤土', description: '肥力高，适合多种作物' },
    { value: 'clay', label: '粘土', description: '保水保肥，透气性差' },
    { value: 'silt', label: '淤泥土', description: '有机质丰富' },
    { value: 'peat', label: '泥炭土', description: '酸性，有机质含量高' },
    { value: 'saline', label: '盐碱土', description: '含盐量高，需改良' },
    { value: 'other', label: '其他', description: '' },
  ];

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

  // 灌溉方式选项
  const irrigationTypes = [
    { value: 'drip', label: '滴灌', efficiency: '高效节水' },
    { value: 'sprinkler', label: '喷灌', efficiency: '适中' },
    { value: 'flood', label: '漫灌', efficiency: '传统方式' },
    { value: 'micro-sprinkler', label: '微喷', efficiency: '精准灌溉' },
    { value: 'none', label: '无灌溉', efficiency: '靠天吃饭' },
  ];

  const handleDrawOnMap = () => {
    setShowMapDrawer(true);
  };

  const handleImportFile = () => {
    setShowImportDialog(true);
  };

  const handleFileImport = (fileType: string) => {
    // 模拟文件导入
    toast.success(`正在导入${fileType}文件...`);
    
    // 模拟解析后的数据
    const mockCoordinates: GeoCoordinate[] = [
      { lat: 39.9042, lng: 116.4074 },
      { lat: 39.9142, lng: 116.4074 },
      { lat: 39.9142, lng: 116.4274 },
      { lat: 39.9042, lng: 116.4274 },
    ];
    
    setFormData({
      ...formData,
      coordinates: mockCoordinates,
      area: 150.5, // 模拟计算的面积
      perimeter: 1800, // 模拟计算的周长
      centerPoint: { lat: 39.9092, lng: 116.4174 },
    });
    
    setShowImportDialog(false);
    toast.success('文件导入成功！地块边界已自动识别');
  };

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

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

  const handleSave = () => {
    if (!formData.code || !formData.name) {
      toast.error('请填写必填项');
      return;
    }

    if (!formData.coordinates || formData.coordinates.length < 3) {
      toast.error('请绘制或导入地块边界（至少3个点）');
      return;
    }

    // 保存到localStorage
    const fields = JSON.parse(localStorage.getItem('smart_agriculture_fields') || '[]');
    const newField: Field = {
      id: `field-${Date.now()}`,
      ...(formData as any),
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      createdBy: 'admin',
      currentVersion: 1,
    };

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

    toast.success('地块信息保存成功！');
    
    // 重置表单
    setFormData({
      code: '',
      name: '',
      area: 0,
      perimeter: 0,
      location: '',
      coordinates: [],
      centerPoint: { lat: 0, lng: 0 },
      soilType: 'loamy',
      landUseType: 'farmland',
      plantingMode: 'open-field',
      irrigationType: 'drip',
      owner: '',
      tags: [],
      photos: [],
      documents: [],
      status: 'active',
    });
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-success">地块信息录入</h2>
          <p className="text-muted-foreground">
            创建新地块档案，支持地图绘制、文件导入等多种方式
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={handleImportFile}>
            <Upload className="w-4 h-4 mr-2" />
            导入GIS文件
          </Button>
          <Button onClick={handleSave} className="bg-success hover:bg-success/90">
            <Save className="w-4 h-4 mr-2" />
            保存地块
          </Button>
        </div>
      </div>

      <Tabs defaultValue="basic" className="w-full">
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="basic">基本信息</TabsTrigger>
          <TabsTrigger value="boundary">边界绘制</TabsTrigger>
          <TabsTrigger value="attributes">地块属性</TabsTrigger>
          <TabsTrigger value="attachments">附件资料</TabsTrigger>
        </TabsList>

        {/* 基本信息 */}
        <TabsContent value="basic" className="space-y-4">
          <Card className="p-6">
            <div className="grid grid-cols-2 gap-6">
              <div>
                <Label htmlFor="code">地块编号 *</Label>
                <Input
                  id="code"
                  value={formData.code}
                  onChange={(e) => setFormData({ ...formData, code: e.target.value })}
                  placeholder="如：DB2024001"
                />
              </div>
              <div>
                <Label htmlFor="name">地块名称 *</Label>
                <Input
                  id="name"
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="如：东区1号地"
                />
              </div>
              <div>
                <Label htmlFor="location">所在位置</Label>
                <Input
                  id="location"
                  value={formData.location}
                  onChange={(e) => setFormData({ ...formData, location: e.target.value })}
                  placeholder="如：张家村东侧"
                />
              </div>
              <div>
                <Label htmlFor="owner">权属人 *</Label>
                <Input
                  id="owner"
                  value={formData.owner}
                  onChange={(e) => setFormData({ ...formData, owner: e.target.value })}
                  placeholder="输入权属人姓名"
                />
              </div>
              <div>
                <Label htmlFor="ownerPhone">联系电话</Label>
                <Input
                  id="ownerPhone"
                  value={formData.ownerPhone || ''}
                  onChange={(e) => setFormData({ ...formData, ownerPhone: e.target.value })}
                  placeholder="输入联系电话"
                />
              </div>
              <div>
                <Label htmlFor="certificateNumber">确权证号</Label>
                <Input
                  id="certificateNumber"
                  value={formData.certificateNumber || ''}
                  onChange={(e) => setFormData({ ...formData, certificateNumber: e.target.value })}
                  placeholder="输入确权证号"
                />
              </div>
              <div>
                <Label htmlFor="contractStartDate">承包开始日期</Label>
                <Input
                  id="contractStartDate"
                  type="date"
                  value={formData.contractStartDate || ''}
                  onChange={(e) => setFormData({ ...formData, contractStartDate: e.target.value })}
                />
              </div>
              <div>
                <Label htmlFor="contractEndDate">承包结束日期</Label>
                <Input
                  id="contractEndDate"
                  type="date"
                  value={formData.contractEndDate || ''}
                  onChange={(e) => setFormData({ ...formData, contractEndDate: e.target.value })}
                />
              </div>
            </div>

            <div className="mt-6">
              <Label htmlFor="remarks">备注说明</Label>
              <Textarea
                id="remarks"
                value={formData.remarks || ''}
                onChange={(e) => setFormData({ ...formData, remarks: e.target.value })}
                placeholder="输入备注信息..."
                rows={3}
              />
            </div>
          </Card>
        </TabsContent>

        {/* 边界绘制 */}
        <TabsContent value="boundary" className="space-y-4">
          <Card className="p-6">
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div>
                  <h3 className="text-success">地块边界设置</h3>
                  <p className="text-sm text-muted-foreground mt-1">
                    通过地图绘制或导入GIS文件来定义地块边界
                  </p>
                </div>
                <Button onClick={handleDrawOnMap} className="bg-success hover:bg-success/90">
                  <Map className="w-4 h-4 mr-2" />
                  在地图上绘制
                </Button>
              </div>

              {/* 边界信息展示 */}
              <div className="grid grid-cols-3 gap-4 p-4 bg-info-muted border border-info rounded-lg">
                <div>
                  <Label className="text-xs">边界点数</Label>
                  <div className="mt-1 text-lg text-info">
                    {formData.coordinates?.length || 0} 个
                  </div>
                </div>
                <div>
                  <Label className="text-xs">地块面积</Label>
                  <div className="mt-1 text-lg text-info">
                    {formData.area?.toFixed(2) || 0} 亩
                  </div>
                </div>
                <div>
                  <Label className="text-xs">边界周长</Label>
                  <div className="mt-1 text-lg text-info">
                    {formData.perimeter?.toFixed(0) || 0} 米
                  </div>
                </div>
              </div>

              {/* 导入方式说明 */}
              <Card className="p-4 bg-muted">
                <h4 className="mb-3">支持的导入方式</h4>
                <div className="grid grid-cols-2 gap-3">
                  <div className="flex items-start gap-2">
                    <MapPin className="w-5 h-5 text-success mt-0.5" />
                    <div>
                      <div className="text-sm">手动绘制</div>
                      <p className="text-xs text-muted-foreground">
                        在卫星图或电子图上描点绘制
                      </p>
                    </div>
                  </div>
                  <div className="flex items-start gap-2">
                    <Upload className="w-5 h-5 text-blue-600 mt-0.5" />
                    <div>
                      <div className="text-sm">文件导入</div>
                      <p className="text-xs text-muted-foreground">
                        支持KML, SHP, GeoJSON格式
                      </p>
                    </div>
                  </div>
                </div>
              </Card>

              {/* 坐标列表 */}
              {formData.coordinates && formData.coordinates.length > 0 && (
                <div>
                  <Label>边界坐标点</Label>
                  <div className="mt-2 max-h-40 overflow-y-auto border rounded-lg p-2">
                    {formData.coordinates.map((coord, index) => (
                      <div key={index} className="flex items-center gap-2 text-sm py-1">
                        <Badge variant="outline">{index + 1}</Badge>
                        <span className="text-muted-foreground">
                          纬度: {coord.lat.toFixed(6)}, 经度: {coord.lng.toFixed(6)}
                        </span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </Card>
        </TabsContent>

        {/* 地块属性 */}
        <TabsContent value="attributes" className="space-y-4">
          <Card className="p-6">
            <div className="space-y-6">
              {/* 土壤类型 */}
              <div>
                <Label htmlFor="soilType">土壤类型 *</Label>
                <Select
                  value={formData.soilType}
                  onValueChange={(value: SoilType) => setFormData({ ...formData, soilType: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {soilTypes.map(soil => (
                      <SelectItem key={soil.value} value={soil.value}>
                        <div>
                          <div>{soil.label}</div>
                          {soil.description && (
                            <p className="text-xs text-muted-foreground">{soil.description}</p>
                          )}
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* 土地利用类型 */}
              <div>
                <Label htmlFor="landUseType">土地利用类型</Label>
                <Select
                  value={formData.landUseType}
                  onValueChange={(value: LandUseType) => setFormData({ ...formData, landUseType: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="farmland">耕地</SelectItem>
                    <SelectItem value="garden">园地</SelectItem>
                    <SelectItem value="forestland">林地</SelectItem>
                    <SelectItem value="grassland">草地</SelectItem>
                    <SelectItem value="other">其他</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {/* 种植模式 */}
              <div>
                <Label>种植模式 *</Label>
                <div className="mt-2 grid grid-cols-5 gap-2">
                  {plantingModes.map(mode => (
                    <Button
                      key={mode.value}
                      variant={formData.plantingMode === mode.value ? 'default' : 'outline'}
                      className="h-auto flex flex-col items-center py-3"
                      onClick={() => setFormData({ ...formData, plantingMode: mode.value as PlantingMode })}
                    >
                      <span className="text-2xl mb-1">{mode.icon}</span>
                      <span className="text-xs">{mode.label}</span>
                    </Button>
                  ))}
                </div>
              </div>

              {/* 灌溉方式 */}
              <div>
                <Label htmlFor="irrigationType">灌溉方式</Label>
                <Select
                  value={formData.irrigationType}
                  onValueChange={(value: IrrigationType) => setFormData({ ...formData, irrigationType: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {irrigationTypes.map(irrigation => (
                      <SelectItem key={irrigation.value} value={irrigation.value}>
                        <div className="flex items-center justify-between w-full gap-4">
                          <span>{irrigation.label}</span>
                          <Badge variant="outline" className="text-xs">
                            {irrigation.efficiency}
                          </Badge>
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* 地形数据 */}
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <Label htmlFor="elevation">海拔（米）</Label>
                  <Input
                    id="elevation"
                    type="number"
                    value={formData.elevation || ''}
                    onChange={(e) => setFormData({ ...formData, elevation: Number(e.target.value) })}
                    placeholder="0"
                  />
                </div>
                <div>
                  <Label htmlFor="slope">坡度（度）</Label>
                  <Input
                    id="slope"
                    type="number"
                    value={formData.slope || ''}
                    onChange={(e) => setFormData({ ...formData, slope: Number(e.target.value) })}
                    placeholder="0"
                  />
                </div>
                <div>
                  <Label htmlFor="aspect">坡向</Label>
                  <Select
                    value={formData.aspect || ''}
                    onValueChange={(value) => setFormData({ ...formData, aspect: value })}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择坡向" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="north">北坡</SelectItem>
                      <SelectItem value="south">南坡</SelectItem>
                      <SelectItem value="east">东坡</SelectItem>
                      <SelectItem value="west">西坡</SelectItem>
                      <SelectItem value="flat">平地</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              {/* 标签管理 */}
              <div>
                <Label>地块标签</Label>
                <div className="mt-2 space-y-2">
                  <div className="flex gap-2">
                    <Input
                      value={tagInput}
                      onChange={(e) => setTagInput(e.target.value)}
                      onKeyPress={(e) => e.key === 'Enter' && handleAddTag()}
                      placeholder="输入标签名称"
                    />
                    <Button onClick={handleAddTag} variant="outline">
                      <Plus className="w-4 h-4 mr-2" />
                      添加
                    </Button>
                  </div>
                  {formData.tags && formData.tags.length > 0 && (
                    <div className="flex flex-wrap gap-2 p-3 bg-gray-50 rounded-lg">
                      {formData.tags.map(tag => (
                        <Badge key={tag} className="px-3 py-1">
                          {tag}
                          <button
                            onClick={() => handleRemoveTag(tag)}
                            className="ml-2 hover:text-destructive"
                          >
                            <X className="w-3 h-3" />
                          </button>
                        </Badge>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>
          </Card>
        </TabsContent>

        {/* 附件资料 */}
        <TabsContent value="attachments" className="space-y-4">
          <Card className="p-6">
            <div className="space-y-6">
              {/* 照片上传 */}
              <div>
                <Label>地块照片</Label>
                <div className="mt-2">
                  <Button variant="outline" className="w-full">
                    <ImageIcon className="w-4 h-4 mr-2" />
                    上传照片
                  </Button>
                  <p className="text-xs text-muted-foreground mt-2">
                    支持JPG、PNG格式，单个文件不超过5MB
                  </p>
                </div>
              </div>

              {/* 文档上传 */}
              <div>
                <Label>相关文档</Label>
                <div className="mt-2">
                  <Button variant="outline" className="w-full">
                    <FileText className="w-4 h-4 mr-2" />
                    上传文档
                  </Button>
                  <p className="text-xs text-muted-foreground mt-2">
                    如承包合同、确权证书等，支持PDF、Word、图片格式
                  </p>
                </div>
              </div>

              <Card className="p-4 bg-yellow-50 border-yellow-200">
                <div className="flex gap-2">
                  <AlertCircle className="w-5 h-5 text-yellow-600 flex-shrink-0" />
                  <div className="text-sm text-yellow-800">
                    <p className="mb-1">附件上传说明：</p>
                    <ul className="space-y-1 text-xs">
                      <li>• 建议上传地块现场照片，便于后续查看识别</li>
                      <li>• 承包合同、确权证书等重要文档请扫描上传保存</li>
                      <li>• 所有附件将加密存储，确保数据安全</li>
                    </ul>
                  </div>
                </div>
              </Card>
            </div>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 导入文件对话框 */}
      <Dialog open={showImportDialog} onOpenChange={setShowImportDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>导入GIS文件</DialogTitle>
            <DialogDescription className="sr-only">
              选择GIS文件格式导入地块边界
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <p className="text-sm text-muted-foreground">
              选择要导入的GIS文件格式，系统将自动解析边界坐标
            </p>
            <div className="grid grid-cols-2 gap-3">
              <Button
                variant="outline"
                className="h-auto flex flex-col items-center py-4"
                onClick={() => handleFileImport('KML')}
              >
                <FileText className="w-8 h-8 text-blue-600 mb-2" />
                <span>KML文件</span>
                <span className="text-xs text-muted-foreground">Google Earth</span>
              </Button>
              <Button
                variant="outline"
                className="h-auto flex flex-col items-center py-4"
                onClick={() => handleFileImport('SHP')}
              >
                <Layers className="w-8 h-8 text-green-600 mb-2" />
                <span>SHP文件</span>
                <span className="text-xs text-muted-foreground">Shapefile</span>
              </Button>
              <Button
                variant="outline"
                className="h-auto flex flex-col items-center py-4"
                onClick={() => handleFileImport('GeoJSON')}
              >
                <FileText className="w-8 h-8 text-purple-600 mb-2" />
                <span>GeoJSON</span>
                <span className="text-xs text-muted-foreground">标准格式</span>
              </Button>
              <Button
                variant="outline"
                className="h-auto flex flex-col items-center py-4"
                onClick={() => handleFileImport('GPX')}
              >
                <MapPin className="w-8 h-8 text-orange-600 mb-2" />
                <span>GPX文件</span>
                <span className="text-xs text-muted-foreground">GPS轨迹</span>
              </Button>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowImportDialog(false)}>
              取消
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
