'use client';

import { useReducer, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Tag, Layers, BarChart3 } from 'lucide-react';
import { LandClassificationReducer, initialState } from './components/landClassificationReducer';
import { LandTagManagement } from './components/LandTagManagement';
import { LandClassificationManagement } from './components/LandClassificationManagement';
import { toast } from 'sonner';

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

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

  // 监听分类更新事件
  useEffect(() => {
    const handleClassificationUpdate = () => {
      loadData();
    };

    window.addEventListener('landClassificationUpdated', handleClassificationUpdate);

    return () => {
      window.removeEventListener('landClassificationUpdated', handleClassificationUpdate);
    };
  }, []);

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

  const loadData = () => {
    // 加载地块数据
    const fieldsData = localStorage.getItem('land_archive_data');
    if (fieldsData) {
      dispatch({ type: 'SET_FIELDS', payload: JSON.parse(fieldsData) });
    }

    // 加载土壤类型
    const soilTypesData = localStorage.getItem('land_soil_types');
    if (soilTypesData) {
      dispatch({ type: 'SET_SOIL_TYPES', payload: JSON.parse(soilTypesData) });
    } else {
      // 初始化默认土壤类型
      const defaultSoilTypes = [
        { id: '1', key: 'sandy', name: '沙质土', color: '#f59e0b' },
        { id: '2', key: 'clay', name: '黏质土', color: '#8b5cf6' },
        { id: '3', key: 'loam', name: '壤质土', color: '#22c55e' },
        { id: '4', key: 'peat', name: '泥炭土', color: '#06b6d4' },
        { id: '5', key: 'chalky', name: '石灰质土', color: '#ec4899' },
        { id: '6', key: 'silty', name: '粉质土', color: '#f97316' },
        { id: '7', key: 'rocky', name: '岩石土', color: '#6b7280' }
      ];
      dispatch({ type: 'SET_SOIL_TYPES', payload: defaultSoilTypes });
      localStorage.setItem('land_soil_types', JSON.stringify(defaultSoilTypes));
    }

    // 加载种植模式
    const plantingModesData = localStorage.getItem('land_planting_modes');
    if (plantingModesData) {
      dispatch({ type: 'SET_PLANTING_MODES', payload: JSON.parse(plantingModesData) });
    } else {
      // 初始化默认种植模式
      const defaultPlantingModes = [
        { id: '1', key: 'conventional', name: '传统种植', emoji: '🌾' },
        { id: '2', key: 'organic', name: '有机种植', emoji: '🌱' },
        { id: '3', key: 'greenhouse', name: '温室种植', emoji: '🏠' },
        { id: '4', key: 'hydroponic', name: '水培种植', emoji: '💧' },
        { id: '5', key: 'aeroponic', name: '气培种植', emoji: '☁️' }
      ];
      dispatch({ type: 'SET_PLANTING_MODES', payload: defaultPlantingModes });
      localStorage.setItem('land_planting_modes', JSON.stringify(defaultPlantingModes));
    }

    // 加载自定义标签
    const tagsData = localStorage.getItem('land_archive_custom_tags');
    if (tagsData) {
      dispatch({ type: 'SET_TAGS', payload: JSON.parse(tagsData) });
    } else {
      // 初始化默认标签
      const defaultTags = [
        { 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() },
        { id: '5', name: '生态种植', color: '#10b981', description: '采用生态循环种植模式', createdAt: new Date().toISOString() },
        { id: '6', name: '科技示范', color: '#ef4444', description: '农业科技示范地块', createdAt: new Date().toISOString() },
        { id: '7', name: '节水灌溉', color: '#06b6d4', description: '采用节水灌溉技术', createdAt: new Date().toISOString() },
        { id: '8', name: '绿色种植', color: '#84cc16', description: '绿色环保种植方式', createdAt: new Date().toISOString() },
      ];
      dispatch({ type: 'SET_TAGS', payload: defaultTags });
      localStorage.setItem('land_archive_custom_tags', JSON.stringify(defaultTags));
    }
  };

  const handleSaveTag = (tag: any) => {
    const existingTags = state.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('标签添加成功');
    }

    dispatch({ type: 'SET_TAGS', payload: updatedTags });
    localStorage.setItem('land_archive_custom_tags', JSON.stringify(updatedTags));
  };

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

    const updatedTags = state.tags.filter(t => t.id !== id);
    dispatch({ type: 'SET_TAGS', payload: updatedTags });
    localStorage.setItem('land_archive_custom_tags', JSON.stringify(updatedTags));
    toast.success('标签删除成功');
  };

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

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

  // 按标签统计 - 显示所有定义的标签
  const tagStats = state.tags.map(tag => ({
    tag,
    count: state.fields.filter((f: any) => 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 dark:text-green-400">地块分类与标签</h2>
          <p className="text-muted-foreground">
            按土壤类型、种植模式和标签进行分类统计和管理
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={() => dispatch({ type: 'SET_SHOW_TAG_MANAGEMENT', payload: true })}>
            <Tag className="w-4 h-4 mr-2" />
            标签管理
          </Button>
          <Button className="bg-green-600 hover:bg-green-700" onClick={() => dispatch({ type: 'SET_SHOW_CLASSIFICATION_MANAGEMENT', payload: true })}>
            <Layers className="w-4 h-4 mr-2" />
            分类管理
          </Button>
        </div>
      </div>

      {/* 土壤类型统计 */}
      <Card className="p-6 bg-card">
        <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:scale-105 hover:shadow-md hover:shadow-gray-300 dark:hover:shadow-gray-500 transition-all duration-300 ease-in-out bg-background">
              <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 dark:text-green-400">{stat.count}</div>
                <div className="text-sm text-muted-foreground">{stat.name}</div>
              </div>
            </Card>
          ))}
        </div>
        </Card>

      {/* 种植模式统计 */}
      <Card className="p-6 bg-card">
        <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:scale-105 hover:shadow-md hover:shadow-gray-300 dark:hover:shadow-gray-500 transition-all duration-300 ease-in-out bg-background">
              <div className="text-center">
                <div className="text-3xl mb-2">{stat.emoji}</div>
                <div className="text-2xl mb-1 text-blue-600 dark:text-blue-400">{stat.count}</div>
                <div className="text-sm text-muted-foreground">{stat.name}</div>
              </div>
            </Card>
          ))}
        </div>
        </Card>

      {/* 标签统计 */}
      <Card className="p-6 bg-card">
        <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:scale-105 hover:shadow-md hover:shadow-gray-300 dark:hover:shadow-gray-500 transition-all duration-300 ease-in-out bg-background">
              <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 dark:text-purple-400">{count}</div>
                  <div className="text-xs text-muted-foreground">个地块</div>
                </div>
              </div>
            </Card>
          ))}
        </div>
        </Card>

      {/* 综合统计 */}
      <Card className="p-6 bg-card">
        <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 dark:bg-green-950">
            <div className="text-sm text-muted-foreground mb-1">地块总数</div>
            <div className="text-2xl text-green-600 dark:text-green-400">{state.fields.length}</div>
          </Card>
          <Card className="p-4 bg-blue-50 dark:bg-blue-950">
            <div className="text-sm text-muted-foreground mb-1">总面积</div>
            <div className="text-2xl text-blue-600 dark:text-blue-400">
              {state.fields.reduce((sum, f) => sum + f.area, 0).toFixed(2)} 亩
            </div>
          </Card>
          <Card className="p-4 bg-purple-50 dark:bg-purple-950">
            <div className="text-sm text-muted-foreground mb-1">土壤类型</div>
            <div className="text-2xl text-purple-600 dark:text-purple-400">{Object.keys(soilTypeStats).length}</div>
          </Card>
          <Card className="p-4 bg-orange-50 dark:bg-orange-950">
            <div className="text-sm text-muted-foreground mb-1">种植模式</div>
            <div className="text-2xl text-orange-600 dark:text-orange-400">{Object.keys(plantingModeStats).length}</div>
          </Card>
        </div>
      </Card>

      {/* 标签管理对话框 */}
      <Dialog open={state.showTagManagement} onOpenChange={(open) => dispatch({ type: 'SET_SHOW_TAG_MANAGEMENT', payload: open })}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>标签管理</DialogTitle>
            <DialogDescription className="sr-only">
              管理地块标签
            </DialogDescription>
          </DialogHeader>
          <LandTagManagement
            tags={state.tags}
            onSave={handleSaveTag}
            onDelete={handleDeleteTag}
          />
        </DialogContent>
      </Dialog>

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