'use client';

import { useReducer } from 'react';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Pen, Edit3, BookOpen, Sparkles } from 'lucide-react';
import {
  drawEditReducer,
  initialState,
  DrawEditState,
  DrawGeometry,
  DrawField
} from './components/drawEditReducer';
import { AdvancedEditorPromo } from './components/AdvancedEditorPromo';
import { DrawingTools } from './components/DrawingTools';
import { EditingTools } from './components/EditingTools';
import { UsageGuide } from './components/UsageGuide';
import { FieldEntryDialog } from './components/FieldEntryDialog';
import { toast } from 'sonner';

export default function DrawPage() {
  const [state, dispatch] = useReducer(drawEditReducer, initialState);

  // 处理几何数据保存请求（从绘制工具或编辑工具）
  const handleSaveRequest = (geometry: DrawGeometry) => {
    dispatch({ type: 'SET_PENDING_GEOMETRY', payload: geometry });
    dispatch({ type: 'SET_SHOW_SAVE_DIALOG', payload: true });
  };

  // 保存地块成功后的回调
  const handleFieldSaved = (fieldData: any) => {
    toast.success(`地块 ${fieldData.name} 已保存到地块档案`);
    dispatch({ type: 'SET_PENDING_GEOMETRY', payload: null });
    dispatch({ type: 'SET_SHOW_SAVE_DIALOG', payload: false });
  };

  // 处理地块更新
  const handleFieldsUpdate = (updatedFields: DrawField[]) => {
    dispatch({ type: 'SET_FIELDS', payload: updatedFields });
    toast.success('地块已更新');
  };

  // 处理几何变化
  const handleGeometryChange = (fieldId: string, geometry: DrawGeometry) => {
    // 更新地块的几何属性
    const updatedFields = state.fields.map(field => {
      if (field.id === fieldId) {
        return {
          ...field,
          points: geometry.points,
          area: geometry.area || 0,
          perimeter: geometry.perimeter || 0
        };
      }
      return field;
    });

    dispatch({ type: 'SET_FIELDS', payload: updatedFields });

    toast.info(`面积：${geometry.area?.toFixed(2)}亩，周长：${geometry.perimeter?.toFixed(0)}米`);
  };

  // 切换到高级编辑器
  const handleSwitchToAdvanced = () => {
    dispatch({ type: 'SET_SHOW_ADVANCED_EDITOR', payload: true });
  };

  // 切换标签页
  const handleTabChange = (value: 'draw' | 'edit' | 'guide') => {
    dispatch({ type: 'SET_ACTIVE_TAB', payload: value });
  };

  // 高级编辑器
  if (state.showAdvancedEditor) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-green-800 dark:text-green-400">高级编辑器</h2>
            <p className="text-muted-foreground">
              专业GIS编辑工具，支持文件导入、真实地图、版本管理
            </p>
          </div>
          <Button
            variant="outline"
            onClick={() => dispatch({ type: 'SET_SHOW_ADVANCED_EDITOR', payload: false })}
          >
            返回基础编辑器
          </Button>
        </div>

        <Card className="p-6 bg-muted">
          <div className="text-center space-y-4">
            <Sparkles className="w-16 h-16 mx-auto text-green-600" />
            <h3>高级编辑器</h3>
            <p className="text-muted-foreground">
              此功能正在开发中，敬请期待！
            </p>
            <Button
              onClick={() => dispatch({ type: 'SET_SHOW_ADVANCED_EDITOR', payload: false })}
            >
              返回基础编辑器
            </Button>
          </div>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 高级编辑器推荐卡片 */}
      <AdvancedEditorPromo onSwitchToAdvanced={handleSwitchToAdvanced} />

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

      {/* 主内容区 - 标签页 */}
      <Tabs value={state.activeTab} onValueChange={handleTabChange}>
        <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">
          <DrawingTools
            onSaveRequest={handleSaveRequest}
            enableSnapping={true}
            snapDistance={10}
            canvasWidth={800}
            canvasHeight={600}
          />
        </TabsContent>

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

        {/* 使用指南标签页 */}
        <TabsContent value="guide" className="mt-6">
          <UsageGuide onSwitchToAdvanced={handleSwitchToAdvanced} />
        </TabsContent>
      </Tabs>

      {/* 新增地块对话框 */}
      {state.showSaveDialog && state.pendingGeometry && (
        <FieldEntryDialog
          open={state.showSaveDialog}
          onOpenChange={(open) => dispatch({ type: 'SET_SHOW_SAVE_DIALOG', payload: open })}
          geometry={state.pendingGeometry}
          onSaved={handleFieldSaved}
        />
      )}
    </div>
  );
}