import { useState, useEffect } from 'react';
import { Button } from '../ui/button';
import { Card } from '../ui/card';
import { Badge } from '../ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '../ui/dialog';
import { Field, FieldTag } from '../../types/field';
import { FieldTagManagement } from './FieldTags';
import { FieldClassificationManagement } from './FieldClassificationManagement';
import { Tag, Layers, BarChart3 } from 'lucide-react';
import { toast } from 'sonner@2.0.3';

interface SoilType {
  id: string;
  name: string;
  key: string;
  color: string;
}

interface PlantingMode {
  id: string;
  name: string;
  key: string;
  emoji: string;
}

// 地块分类与标签管理 - 与农机管理风格一致
export function FieldClassification() {
  const [fields, setFields] = useState<Field[]>([]);
  const [tags, setTags] = useState<FieldTag[]>([]);
  const [soilTypes, setSoilTypes] = useState<SoilType[]>([]);
  const [plantingModes, setPlantingModes] = useState<PlantingMode[]>([]);
  const [showTagManagement, setShowTagManagement] = useState(false);
  const [showClassificationManagement, setShowClassificationManagement] = useState(false);

  useEffect(() => {
    loadData();
  }, []);

  // 监听分类更新事件
  useEffect(() => {
    const handleClassificationUpdate = () => {
      loadData();
    };
    
    window.addEventListener('fieldClassificationUpdated', handleClassificationUpdate);
    
    return () => {
      window.removeEventListener('fieldClassificationUpdated', handleClassificationUpdate);
    };
  }, []);

  // 当分类管理对话框关闭时重新加载数据
  const handleCloseClassificationDialog = (open: boolean) => {
    setShowClassificationManagement(open);
    // 对话框关闭时重新加载数据
    if (!open) {
      loadData();
    }
  };

  const loadData = () => {
    // 加载地块数据
    const fieldsData = localStorage.getItem('smart_agriculture_fields');
    if (fieldsData) {
      setFields(JSON.parse(fieldsData));
    }

    // 加载土壤类型
    const soilTypesData = localStorage.getItem('field_soil_types');
    if (soilTypesData) {
      setSoilTypes(JSON.parse(soilTypesData));
    }

    // 加载种植模式
    const plantingModesData = localStorage.getItem('field_planting_modes');
    if (plantingModesData) {
      setPlantingModes(JSON.parse(plantingModesData));
    }

    // 加载自定义标签
    const tagsData = localStorage.getItem('smart_agriculture_custom_tags');
    if (tagsData) {
      setTags(JSON.parse(tagsData));
    } else {
      // 初始化默认标签
      const defaultTags: FieldTag[] = [
        { id: '1', name: '有机种植', color: '#22c55e', description: '符合有机种植标准的地块', createdAt: new Date().toISOString() },
        { id: '2', name: '高产示范', color: '#3b82f6', description: '高产示范田', createdAt: new Date().toISOString() },
        { id: '3', name: '滴灌设施', color: '#f97316', description: '配备滴灌系统的地块', createdAt: new Date().toISOString() },
        { id: '4', name: '智能监测', color: '#a855f7', description: '安装了智能监测设备的地块', createdAt: new Date().toISOString() },
      ];
      setTags(defaultTags);
      localStorage.setItem('smart_agriculture_custom_tags', JSON.stringify(defaultTags));
    }
  };

  const handleSaveTag = (tag: FieldTag) => {
    const existingTags = tags;
    const existingIndex = existingTags.findIndex(t => t.id === tag.id);
    
    let updatedTags;
    if (existingIndex >= 0) {
      // 更新现有标签
      updatedTags = [...existingTags];
      updatedTags[existingIndex] = tag;
      toast.success('标签更新成功');
    } else {
      // 添加新标签
      updatedTags = [...existingTags, tag];
      toast.success('标签添加成功');
    }
    
    setTags(updatedTags);
    localStorage.setItem('smart_agriculture_custom_tags', JSON.stringify(updatedTags));
  };

  const handleDeleteTag = (id: string) => {
    const tag = tags.find(t => t.id === id);
    if (tag) {
      // 从所有地块中移除该标签
      const updatedFields = fields.map(f => ({
        ...f,
        tags: f.tags.filter(t => t !== tag.name)
      }));
      setFields(updatedFields);
      localStorage.setItem('smart_agriculture_fields', JSON.stringify(updatedFields));
    }

    const updatedTags = tags.filter(t => t.id !== id);
    setTags(updatedTags);
    localStorage.setItem('smart_agriculture_custom_tags', JSON.stringify(updatedTags));
    toast.success('标签删除成功');
  };

  // 按土壤类型统计 - 显示所有定义的类型
  const soilTypeStats = soilTypes.map(type => ({
    key: type.key,
    name: type.name,
    color: type.color,
    count: fields.filter(f => f.soilType === type.key).length,
  }));

  // 按种植模式统计 - 显示所有定义的模式
  const plantingModeStats = plantingModes.map(mode => ({
    key: mode.key,
    name: mode.name,
    emoji: mode.emoji,
    count: fields.filter(f => f.plantingMode === mode.key).length,
  }));

  // 按标签统计
  const tagStats = tags.map(tag => ({
    tag,
    count: fields.filter(f => f.tags.includes(tag.name)).length,
  }));

  return (
    <div className="space-y-6">
      <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 variant="outline" onClick={() => setShowTagManagement(true)}>
            <Tag className="w-4 h-4 mr-2" />
            标签管理
          </Button>
          <Button className="bg-green-600 hover:bg-green-700" onClick={() => setShowClassificationManagement(true)}>
            <Layers className="w-4 h-4 mr-2" />
            分类管理
          </Button>
        </div>
      </div>

      {/* 土壤类型统计 */}
      <Card className="p-6">
        <div className="flex items-center gap-2 mb-4">
          <Layers className="w-5 h-5 text-green-600" />
          <h3>土壤类型统计</h3>
        </div>
        <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4">
          {soilTypeStats.map((stat) => (
            <Card key={stat.key} className="p-4 hover:shadow-md transition-shadow">
              <div className="text-center">
                <div
                  className="w-3 h-3 rounded-full mx-auto mb-2"
                  style={{ backgroundColor: stat.color }}
                />
                <div className="text-2xl mb-2 text-green-600">{stat.count}</div>
                <div className="text-sm text-muted-foreground">{stat.name}</div>
              </div>
            </Card>
          ))}
        </div>
        {soilTypeStats.length === 0 && (
          <div className="text-center text-muted-foreground py-8">
            暂无土壤类型，请前往分类管理添加
          </div>
        )}
      </Card>

      {/* 种植模式统计 */}
      <Card className="p-6">
        <div className="flex items-center gap-2 mb-4">
          <Layers className="w-5 h-5 text-blue-600" />
          <h3>种植模式统计</h3>
        </div>
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4">
          {plantingModeStats.map((stat) => (
            <Card key={stat.key} className="p-4 hover:shadow-md transition-shadow">
              <div className="text-center">
                <div className="text-3xl mb-2">{stat.emoji}</div>
                <div className="text-2xl mb-1 text-blue-600">{stat.count}</div>
                <div className="text-sm text-muted-foreground">{stat.name}</div>
              </div>
            </Card>
          ))}
        </div>
        {plantingModeStats.length === 0 && (
          <div className="text-center text-muted-foreground py-8">
            暂无种植模式，请前往分类管理添加
          </div>
        )}
      </Card>

      {/* 标签统计 */}
      <Card className="p-6">
        <div className="flex items-center gap-2 mb-4">
          <Tag className="w-5 h-5 text-purple-600" />
          <h3>标签统计</h3>
        </div>
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
          {tagStats.map(({ tag, count }) => (
            <Card key={tag.id} className="p-4 hover:shadow-md transition-shadow">
              <div className="space-y-2">
                <Badge style={{ backgroundColor: tag.color, color: 'white' }} className="w-full justify-center">
                  {tag.name}
                </Badge>
                <div className="text-center">
                  <div className="text-2xl text-purple-600">{count}</div>
                  <div className="text-xs text-muted-foreground">个地块</div>
                </div>
              </div>
            </Card>
          ))}
        </div>
        {tagStats.length === 0 && (
          <div className="text-center text-muted-foreground py-8">
            暂无标签，点击右上角"标签管理"创建标签
          </div>
        )}
      </Card>

      {/* 综合统计 */}
      <Card className="p-6">
        <div className="flex items-center gap-2 mb-4">
          <BarChart3 className="w-5 h-5 text-orange-600" />
          <h3>综合统计</h3>
        </div>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <Card className="p-4 bg-green-50">
            <div className="text-sm text-muted-foreground mb-1">地块总数</div>
            <div className="text-2xl text-green-600">{fields.length}</div>
          </Card>
          <Card className="p-4 bg-blue-50">
            <div className="text-sm text-muted-foreground mb-1">总面积</div>
            <div className="text-2xl text-blue-600">
              {fields.reduce((sum, f) => sum + f.area, 0).toFixed(2)} 亩
            </div>
          </Card>
          <Card className="p-4 bg-purple-50">
            <div className="text-sm text-muted-foreground mb-1">土壤类型</div>
            <div className="text-2xl text-purple-600">{Object.keys(soilTypeStats).length}</div>
          </Card>
          <Card className="p-4 bg-orange-50">
            <div className="text-sm text-muted-foreground mb-1">种植模式</div>
            <div className="text-2xl text-orange-600">{Object.keys(plantingModeStats).length}</div>
          </Card>
        </div>
      </Card>

      {/* 标签管理对话框 */}
      <Dialog open={showTagManagement} onOpenChange={setShowTagManagement}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>标签管理</DialogTitle>
            <DialogDescription className="sr-only">
              管理地块标签
            </DialogDescription>
          </DialogHeader>
          <FieldTagManagement
            tags={tags}
            onSave={handleSaveTag}
            onDelete={handleDeleteTag}
          />
        </DialogContent>
      </Dialog>

      {/* 分类管理对话框 */}
      <Dialog open={showClassificationManagement} onOpenChange={handleCloseClassificationDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>分类管理</DialogTitle>
            <DialogDescription className="sr-only">
              管理地块分类
            </DialogDescription>
          </DialogHeader>
          <FieldClassificationManagement />
        </DialogContent>
      </Dialog>
    </div>
  );
}
