import { useState } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { 
  Pen,
  Edit3,
  Sparkles,
  BookOpen
} from 'lucide-react';
import { GISDrawingTools, DrawGeometry } from './GISDrawingTools';
import { GISEditingTools } from './GISEditingTools';
import { FieldEditor } from './FieldEditor';
import { FieldEntryDialog } from './FieldEntryDialog';
import { toast } from 'sonner@2.0.3';

// 模拟地块数据
const mockFields = [
  {
    id: 'field-1',
    name: '地块A',
    points: [
      { x: 200, y: 150 },
      { x: 350, y: 150 },
      { x: 350, y: 280 },
      { x: 200, y: 280 }
    ],
    color: '#22c55e'
  },
  {
    id: 'field-2',
    name: '地块B',
    points: [
      { x: 380, y: 150 },
      { x: 520, y: 150 },
      { x: 520, y: 280 },
      { x: 380, y: 280 }
    ],
    color: '#3b82f6'
  },
  {
    id: 'field-3',
    name: '地块C',
    points: [
      { x: 200, y: 310 },
      { x: 350, y: 310 },
      { x: 350, y: 440 },
      { x: 200, y: 440 }
    ],
    color: '#f97316'
  }
];

export function FieldDrawEdit() {
  const [showAdvancedEditor, setShowAdvancedEditor] = useState(false);
  const [activeTab, setActiveTab] = useState('draw');
  const [fields, setFields] = useState(mockFields);
  
  // 保存对话框和几何数据
  const [showSaveDialog, setShowSaveDialog] = useState(false);
  const [pendingGeometry, setPendingGeometry] = useState<DrawGeometry | null>(null);

  // 高级编辑器
  if (showAdvancedEditor) {
    return <FieldEditor onCancel={() => setShowAdvancedEditor(false)} />;
  }

  // 处理几何数据保存请求（从绘制工具或编辑工具）
  const handleSaveRequest = (geometry: DrawGeometry) => {
    setPendingGeometry(geometry);
    setShowSaveDialog(true);
  };

  // 保存地块成功后的回调
  const handleFieldSaved = (fieldData: any) => {
    toast.success(`地块 ${fieldData.name} 已保存到地块档案`);
    setPendingGeometry(null);
    setShowSaveDialog(false);
  };

  // 处理地块更新
  const handleFieldsUpdate = (updatedFields: typeof fields) => {
    setFields(updatedFields);
    toast.success('地块已更新');
  };

  // 处理几何变化
  const handleGeometryChange = (fieldId: string, geometry: DrawGeometry) => {
    // 更新地块的几何属性
    const updatedFields = fields.map(field => {
      if (field.id === fieldId) {
        return {
          ...field,
          points: geometry.points,
          area: geometry.area || 0,
          perimeter: geometry.perimeter || 0
        };
      }
      return field;
    });
    
    setFields(updatedFields);
    
    toast.info(`面积：${geometry.area?.toFixed(2)}亩，周长：${geometry.perimeter?.toFixed(0)}米`);
  };

  return (
    <div className="space-y-6">
      {/* 高级编辑器推荐卡片 */}
      <Card className="p-4 bg-gradient-to-r from-green-50 to-blue-50 border-green-200">
        <div className="flex items-start gap-3">
          <Sparkles className="w-5 h-5 text-green-600 mt-0.5 flex-shrink-0" />
          <div className="flex-1">
            <h4 className="text-green-800 mb-1">💡 高级编辑器推荐</h4>
            <p className="text-sm text-muted-foreground mb-3">
              高级编辑器支持文件导入（KML/GeoJSON/SHP）、真实地图集成、版本管理等强大功能，适合专业GIS应用。
            </p>
            <Button 
              size="sm"
              onClick={() => setShowAdvancedEditor(true)}
              className="bg-green-600 hover:bg-green-700 text-white"
            >
              <Sparkles className="w-4 h-4 mr-2" />
              切换到高级编辑器
            </Button>
          </div>
        </div>
      </Card>

      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">数字化绘制与编辑</h2>
          <p className="text-muted-foreground">
            完整的在线GIS编辑工具，支持绘制、节点编辑、分割、合并
          </p>
        </div>
        <div className="flex gap-2">
          <Button 
            variant="outline"
            onClick={() => setShowAdvancedEditor(true)}
          >
            <Sparkles className="w-4 h-4 mr-2" />
            高级编辑器
          </Button>
        </div>
      </div>

      {/* 主内容区 - 标签页 */}
      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="draw" className="flex items-center gap-2">
            <Pen className="w-4 h-4" />
            绘制工具
          </TabsTrigger>
          <TabsTrigger value="edit" className="flex items-center gap-2">
            <Edit3 className="w-4 h-4" />
            编辑工具
          </TabsTrigger>
          <TabsTrigger value="guide" className="flex items-center gap-2">
            <BookOpen className="w-4 h-4" />
            使用指南
          </TabsTrigger>
        </TabsList>

        {/* 绘制工具标签页 */}
        <TabsContent value="draw" className="mt-6">
          <GISDrawingTools
            onSaveRequest={handleSaveRequest}
            enableSnapping={true}
            snapDistance={10}
            canvasWidth={800}
            canvasHeight={600}
          />
        </TabsContent>

        {/* 编辑工具标签页 */}
        <TabsContent value="edit" className="mt-6">
          <GISEditingTools
            fields={fields}
            onFieldsUpdate={handleFieldsUpdate}
            onGeometryChange={handleGeometryChange}
            onSaveRequest={handleSaveRequest}
            canvasWidth={800}
            canvasHeight={600}
          />
        </TabsContent>

        {/* 使用指南标签页 */}
        <TabsContent value="guide" className="mt-6">
          <div className="grid grid-cols-2 gap-6">
            {/* 绘制工具指南 */}
            <Card className="p-6">
              <div className="flex items-center gap-2 mb-4">
                <Pen className="w-5 h-5 text-green-600" />
                <h3 className="text-green-800">绘制工具</h3>
              </div>
              
              <div className="space-y-4 text-sm">
                <div>
                  <h4 className="mb-2">1. 多边形绘制</h4>
                  <ul className="space-y-1 text-muted-foreground ml-4">
                    <li>• 点击地图依次标记顶点</li>
                    <li>• 至少需要3个点</li>
                    <li>• 点击起点或"完成"按钮闭合</li>
                    <li>• 点击"保存"按钮保存到地块档案</li>
                  </ul>
                </div>

                <div>
                  <h4 className="mb-2">2. 保存流程</h4>
                  <ul className="space-y-1 text-muted-foreground ml-4">
                    <li>• 完成绘制后，点击左侧"保存"按钮</li>
                    <li>• 弹出"新增地块"对话框</li>
                    <li>• 填写地块信息（自动填充面积周长）</li>
                    <li>• 保存到地块档案管理</li>
                  </ul>
                </div>

                <div>
                  <h4 className="mb-2">3. 快捷操作</h4>
                  <ul className="space-y-1 text-muted-foreground ml-4">
                    <li>• Ctrl+Z：撤销</li>
                    <li>• Ctrl+Y：重做</li>
                    <li>• Enter：完成绘制</li>
                    <li>• Ctrl+S：保存到地块档案</li>
                  </ul>
                </div>
              </div>
            </Card>

            {/* 编辑工具指南 */}
            <Card className="p-6">
              <div className="flex items-center gap-2 mb-4">
                <Edit3 className="w-5 h-5 text-blue-600" />
                <h3 className="text-blue-800">编辑工具</h3>
              </div>
              
              <div className="space-y-4 text-sm">
                <div>
                  <h4 className="mb-2">1. 节点编辑</h4>
                  <ul className="space-y-1 text-muted-foreground ml-4">
                    <li>• 点击地块选中</li>
                    <li>• 拖动节点调整位置</li>
                    <li>• 点击"保存"保存到地块档案</li>
                  </ul>
                </div>

                <div>
                  <h4 className="mb-2">2. 地块分割</h4>
                  <ul className="space-y-1 text-muted-foreground ml-4">
                    <li>• 选择要分割的地块</li>
                    <li>• 绘制分割线</li>
                    <li>• 点击"保存"保存到地块档案</li>
                  </ul>
                </div>

                <div>
                  <h4 className="mb-2">3. 地块合并</h4>
                  <ul className="space-y-1 text-muted-foreground ml-4">
                    <li>• 选择多个地块</li>
                    <li>• 点击"合并"</li>
                    <li>• 点击"保存"保存到地块档案</li>
                  </ul>
                </div>
              </div>
            </Card>

            {/* 高级功能说明 */}
            <Card className="p-6 col-span-2 bg-green-50 border-green-200">
              <div className="flex items-center gap-2 mb-4">
                <Sparkles className="w-5 h-5 text-green-600" />
                <h3 className="text-green-800">高级功能（高级编辑器）</h3>
              </div>
              
              <div className="grid grid-cols-2 gap-x-8 gap-y-2 text-sm text-green-800">
                <div>• <strong>文件导入</strong>：支持KML、GeoJSON、Shapefile格式</div>
                <div>• <strong>真实地图</strong>：集成高德地图/Leaflet地图引擎</div>
                <div>• <strong>坐标转换</strong>：支持WGS84、GCJ02坐标系转换</div>
                <div>• <strong>版本管理</strong>：自动记录编辑历史，随时回滚</div>
                <div>• <strong>批量操作</strong>：批量导入导出地块数据</div>
                <div>• <strong>数据关联</strong>：关联土壤、种植等业务数据</div>
                <div>• <strong>精确测量</strong>：基于真实地理坐标的精确测量</div>
                <div>• <strong>图层管理</strong>：多图层叠加显示和管理</div>
              </div>

              <div className="mt-4 pt-4 border-t border-green-300">
                <Button
                  onClick={() => setShowAdvancedEditor(true)}
                  className="bg-green-600 hover:bg-green-700"
                >
                  <Sparkles className="w-4 h-4 mr-2" />
                  立即体验高级编辑器
                </Button>
              </div>
            </Card>

            {/* 快捷键说明 */}
            <Card className="p-6 col-span-2">
              <h3 className="mb-4">⌨️ 快捷键</h3>
              <div className="grid grid-cols-3 gap-4 text-sm">
                <div className="flex items-center gap-2">
                  <kbd className="px-2 py-1 bg-gray-100 rounded text-xs">Ctrl + Z</kbd>
                  <span className="text-muted-foreground">撤销</span>
                </div>
                <div className="flex items-center gap-2">
                  <kbd className="px-2 py-1 bg-gray-100 rounded text-xs">Ctrl + Y</kbd>
                  <span className="text-muted-foreground">重做</span>
                </div>
                <div className="flex items-center gap-2">
                  <kbd className="px-2 py-1 bg-gray-100 rounded text-xs">Ctrl + S</kbd>
                  <span className="text-muted-foreground">保存到地块档案</span>
                </div>
                <div className="flex items-center gap-2">
                  <kbd className="px-2 py-1 bg-gray-100 rounded text-xs">Delete</kbd>
                  <span className="text-muted-foreground">清除</span>
                </div>
                <div className="flex items-center gap-2">
                  <kbd className="px-2 py-1 bg-gray-100 rounded text-xs">Esc</kbd>
                  <span className="text-muted-foreground">取消操作</span>
                </div>
                <div className="flex items-center gap-2">
                  <kbd className="px-2 py-1 bg-gray-100 rounded text-xs">Enter</kbd>
                  <span className="text-muted-foreground">完成绘制</span>
                </div>
              </div>
            </Card>
          </div>
        </TabsContent>
      </Tabs>

      {/* 新增地块对话框 */}
      {showSaveDialog && pendingGeometry && (
        <FieldEntryDialog
          open={showSaveDialog}
          onOpenChange={setShowSaveDialog}
          geometry={pendingGeometry}
          onSaved={handleFieldSaved}
        />
      )}
    </div>
  );
}
