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 { MachineryRecord, MachineryTag, MachineryCategory, MachineryUsage } from '../../../types/machinery';
import { machineryStorage } from '../../../lib/machineryStorage';
import { TagManagement } from '../TagManagement';
import { MachineryClassificationManagement } from '../MachineryClassificationManagement';
import { Tag, Layers, BarChart3 } from 'lucide-react';
import { toast } from 'sonner@2.0.3';

export function MachineryClassification() {
  const [machinery, setMachinery] = useState<MachineryRecord[]>([]);
  const [tags, setTags] = useState<MachineryTag[]>([]);
  const [showTagManagement, setShowTagManagement] = useState(false);
  const [showClassificationManagement, setShowClassificationManagement] = useState(false);

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

  const loadData = () => {
    setMachinery(machineryStorage.getAllMachinery());
    setTags(machineryStorage.getAllTags());
  };

  const handleSaveTag = (tag: MachineryTag) => {
    machineryStorage.saveTag(tag);
    loadData();
    toast.success(tag.id.includes('tag-') && !machineryStorage.getAllTags().find(t => t.id === tag.id) ? '标签添加成功' : '标签更新成功');
  };

  const handleDeleteTag = (id: string) => {
    machineryStorage.deleteTag(id);
    loadData();
    toast.success('标签删除成功');
  };

  // 按类型统计
  const categoryStats = machinery.reduce((acc, m) => {
    acc[m.category] = (acc[m.category] || 0) + 1;
    return acc;
  }, {} as Record<string, number>);

  // 按使用场景统计
  const usageStats = machinery.reduce((acc, m) => {
    acc[m.usage] = (acc[m.usage] || 0) + 1;
    return acc;
  }, {} as Record<string, number>);

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

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-primary">农机分类与标签管理</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-success hover:bg-success/90" 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-primary" />
          <h3>农机类型统计</h3>
        </div>
        <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4">
          {Object.entries(categoryStats).map(([category, count]) => (
            <Card key={category} className="p-4 hover:shadow-md transition-shadow">
              <div className="text-center">
                <div className="text-2xl mb-2">{count}</div>
                <div className="text-sm text-muted-foreground">{category}</div>
              </div>
            </Card>
          ))}
        </div>
        {Object.keys(categoryStats).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-primary" />
          <h3>使用场景统计</h3>
        </div>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {Object.entries(usageStats).map(([usage, count]) => (
            <Card key={usage} className="p-4 hover:shadow-md transition-shadow">
              <div className="text-center">
                <div className="text-2xl mb-2">{count}</div>
                <div className="text-sm text-muted-foreground">{usage}</div>
              </div>
            </Card>
          ))}
        </div>
        {Object.keys(usageStats).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-primary" />
          <h3>标签统计</h3>
        </div>
        {tagStats.length === 0 ? (
          <div className="text-center text-muted-foreground py-8">
            暂无标签，请先创建标签
          </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="flex items-center justify-between">
                  <Badge style={{ backgroundColor: tag.color, color: 'white' }}>
                    {tag.name}
                  </Badge>
                  <span className="text-lg">{count}</span>
                </div>
              </Card>
            ))}
          </div>
        )}
      </Card>

      {/* 详细分类列表 */}
      <Card className="p-6">
        <h3 className="mb-4">分类详情</h3>
        <div className="space-y-4">
          {/* 按类型分组 */}
          <div>
            <h4 className="mb-3 text-muted-foreground">按农机类型</h4>
            <div className="flex flex-wrap gap-2">
              {Object.entries(categoryStats).map(([category, count]) => (
                <Badge key={category} variant="outline" className="px-3 py-1">
                  {category} ({count})
                </Badge>
              ))}
            </div>
          </div>

          {/* 按使用场景分组 */}
          <div>
            <h4 className="mb-3 text-muted-foreground">按使用场景</h4>
            <div className="flex flex-wrap gap-2">
              {Object.entries(usageStats).map(([usage, count]) => (
                <Badge key={usage} variant="outline" className="px-3 py-1">
                  {usage} ({count})
                </Badge>
              ))}
            </div>
          </div>

          {/* 按标签分组 */}
          <div>
            <h4 className="mb-3 text-muted-foreground">按标签</h4>
            <div className="flex flex-wrap gap-2">
              {tagStats.map(({ tag, count }) => (
                <Badge 
                  key={tag.id} 
                  style={{ backgroundColor: tag.color, color: 'white' }}
                  className="px-3 py-1"
                >
                  {tag.name} ({count})
                </Badge>
              ))}
            </div>
          </div>
        </div>
      </Card>

      <TagManagement
        open={showTagManagement}
        onClose={() => setShowTagManagement(false)}
        tags={tags}
        onSave={handleSaveTag}
        onDelete={handleDeleteTag}
      />

      <Dialog open={showClassificationManagement} onOpenChange={setShowClassificationManagement}>
        <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>农机分类管理</DialogTitle>
            <DialogDescription className="sr-only">
              管理农机类型和使用场景分类
            </DialogDescription>
          </DialogHeader>
          <MachineryClassificationManagement />
        </DialogContent>
      </Dialog>
    </div>
  );
}
