import { useState } from 'react';
import { Button } from '../ui/button';
import { Plus, Download } from 'lucide-react';
import { FieldEditor } from './FieldEditor';
import { FieldList } from './FieldList';
import { Field } from '../../types/field';
import { toast } from 'sonner@2.0.3';

export function FieldEntryMaintenance() {
  const [view, setView] = useState<'list' | 'create' | 'edit'>('list');
  const [editingFieldId, setEditingFieldId] = useState<string | undefined>();

  const handleCreateNew = () => {
    setEditingFieldId(undefined);
    setView('create');
  };

  const handleEdit = (fieldId: string) => {
    setEditingFieldId(fieldId);
    setView('edit');
  };

  const handleSave = (field: Field) => {
    toast.success('地块保存成功');
    setView('list');
    setEditingFieldId(undefined);
  };

  const handleCancel = () => {
    setView('list');
    setEditingFieldId(undefined);
  };

  const handleExportData = () => {
    const fields = JSON.parse(localStorage.getItem('smart_agriculture_fields') || '[]');
    const dataStr = JSON.stringify(fields, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `地块数据_${new Date().toLocaleDateString()}.json`;
    link.click();
    URL.revokeObjectURL(url);
    toast.success('数据导出成功');
  };

  return (
    <div className="space-y-6">
      {view === 'list' ? (
        <>
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-green-800">地块档案管理</h2>
              <p className="text-muted-foreground">
                完整的地块信息管理，包含录入、查询、编辑和版本历史
              </p>
            </div>
            <div className="flex gap-2">
              <Button onClick={handleCreateNew}>
                <Plus className="w-4 h-4 mr-2" />
                新建地块
              </Button>
              <Button variant="outline" onClick={handleExportData}>
                <Download className="w-4 h-4 mr-2" />
                导出数据
              </Button>
            </div>
          </div>

          <FieldList onEdit={handleEdit} />
        </>
      ) : (
        <FieldEditor
          fieldId={editingFieldId}
          onSave={handleSave}
          onCancel={handleCancel}
        />
      )}
    </div>
  );
}
