import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Badge } from '../ui/badge';
import { RefreshCw, FileText, TrendingUp } from 'lucide-react';
import { machineryStorage } from '../../lib/machineryStorage';
import { initializeChangeHistoryMockData, getChangeHistoryStatistics, clearChangeHistory } from '../../lib/changeHistoryMockData';
import { ChangeHistoryList } from './ChangeHistoryList';
import { MachineryRecord } from '../../types/machinery';

/**
 * 变更历史示例展示组件
 * 展示各个农机的变更历史记录
 */
export function ChangeHistoryExamples() {
  const [machinery, setMachinery] = useState<MachineryRecord[]>([]);
  const [selectedMachineryId, setSelectedMachineryId] = useState<string>('');
  const [stats, setStats] = useState<any>(null);

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

  const loadData = () => {
    // 初始化示例数据
    initializeChangeHistoryMockData();
    
    // 加载所有农机
    const allMachinery = machineryStorage.getAllMachinery();
    setMachinery(allMachinery);
    
    // 默认选择第一台农机
    if (allMachinery.length > 0 && !selectedMachineryId) {
      setSelectedMachineryId(allMachinery[0].id);
    }
    
    // 加载统计信息
    const statistics = getChangeHistoryStatistics();
    setStats(statistics);
  };

  const handleRefresh = () => {
    loadData();
  };

  const handleReset = () => {
    if (confirm('确定要清除所有变更历史示例数据吗？')) {
      clearChangeHistory();
      loadData();
    }
  };

  const selectedMachinery = machinery.find(m => m.id === selectedMachineryId);
  const changeHistory = selectedMachinery 
    ? machineryStorage.getChangeHistory(selectedMachinery.id) 
    : [];

  return (
    <div className="space-y-6 p-6">
      {/* 页面标题 */}
      <div className="flex items-start justify-between">
        <div>
          <h2 className="text-primary mb-2">变更历史示例数据</h2>
          <p className="text-muted-foreground">
            展示农机全生命周期档案的变更历史记录，追踪所有信息修改
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm" onClick={handleRefresh}>
            <RefreshCw className="w-4 h-4 mr-1" />
            刷新
          </Button>
          <Button variant="outline" size="sm" onClick={handleReset}>
            重置数据
          </Button>
        </div>
      </div>

      {/* 统计信息 */}
      {stats && (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <Card className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs text-muted-foreground">总变更次数</p>
                <p className="mt-2 text-2xl text-info">{stats.totalChanges}</p>
              </div>
              <TrendingUp className="w-12 h-12 text-info opacity-50" />
            </div>
          </Card>

          <Card className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs text-muted-foreground">涉及设备数</p>
                <p className="mt-2 text-2xl text-success">{stats.totalMachinery}</p>
              </div>
              <FileText className="w-12 h-12 text-success opacity-50" />
            </div>
          </Card>

          <Card className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs text-muted-foreground">平均变更次数</p>
                <p className="mt-2 text-2xl text-info">
                  {stats.avgChangesPerMachinery.toFixed(1)}
                </p>
              </div>
              <TrendingUp className="w-12 h-12 text-info opacity-50" />
            </div>
          </Card>
        </div>
      )}

      {/* 农机选择和变更历史 */}
      <Card className="p-6">
        <Tabs value={selectedMachineryId} onValueChange={setSelectedMachineryId}>
          <div className="mb-4">
            <h3 className="text-primary mb-3">选择设备查看变更历史</h3>
            <TabsList className="w-full justify-start overflow-x-auto flex-wrap h-auto">
              {machinery.map(m => {
                const changeCount = machineryStorage.getChangeHistory(m.id).length;
                return (
                  <TabsTrigger 
                    key={m.id} 
                    value={m.id}
                    className="relative"
                  >
                    <span>{m.name}</span>
                    {changeCount > 0 && (
                      <Badge variant="secondary" className="ml-2 text-xs">
                        {changeCount}
                      </Badge>
                    )}
                  </TabsTrigger>
                );
              })}
            </TabsList>
          </div>

          {machinery.map(m => (
            <TabsContent key={m.id} value={m.id} className="mt-0">
              <ChangeHistoryList history={machineryStorage.getChangeHistory(m.id)} />
            </TabsContent>
          ))}
        </Tabs>
      </Card>

      {/* 变更字段统计 */}
      {stats && stats.changesByField && Object.keys(stats.changesByField).length > 0 && (
        <Card className="p-6">
          <h3 className="text-primary mb-4">变更字段统计</h3>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
            {Object.entries(stats.changesByField)
              .sort((a, b) => (b[1] as number) - (a[1] as number))
              .map(([field, count]) => (
                <div key={field} className="bg-muted/50 rounded-lg p-3 text-center">
                  <p className="text-sm mb-1">{field}</p>
                  <p className="text-2xl text-primary">{count as number}</p>
                  <p className="text-xs text-muted-foreground">次变更</p>
                </div>
              ))}
          </div>
        </Card>
      )}

      {/* 操作人员统计 */}
      {stats && stats.changesByOperator && Object.keys(stats.changesByOperator).length > 0 && (
        <Card className="p-6">
          <h3 className="text-primary mb-4">操作人员统计</h3>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
            {Object.entries(stats.changesByOperator)
              .sort((a, b) => (b[1] as number) - (a[1] as number))
              .map(([operator, count]) => (
                <div key={operator} className="bg-muted/50 rounded-lg p-3">
                  <div className="flex items-center justify-between">
                    <p className="text-sm">{operator}</p>
                    <Badge variant="outline">{count as number}次</Badge>
                  </div>
                </div>
              ))}
          </div>
        </Card>
      )}

      {/* 说明文档 */}
      <Card className="p-6 bg-info-muted border-info">
        <h4 className="text-muted-foreground mb-3">📖 变更历史说明</h4>
        <div className="space-y-2 text-sm text-muted-foreground">
          <p>
            <strong>示例数据覆盖场景：</strong>
          </p>
          <ul className="list-disc list-inside space-y-1 ml-2">
            <li><strong>设备状态变更</strong>：正常 ↔ 待维护，记录设备运行状态变化</li>
            <li><strong>位置信息更新</strong>：地块调动、作业位置变更、归库记录</li>
            <li><strong>人员调整</strong>：操作人员变更、部门调整</li>
            <li><strong>财务信息</strong>：价格调整、保险金额更新</li>
            <li><strong>设备信息</strong>：名称规范化、标签管理、备注更新</li>
          </ul>
          <p className="mt-3">
            <strong>记录要点：</strong>
          </p>
          <ul className="list-disc list-inside space-y-1 ml-2">
            <li>每次修改自动记录操作人、操作时间</li>
            <li>完整保存修改前后的值，便于追溯</li>
            <li>字段名称自动转换为中文，易于理解</li>
            <li>支持多种数据类型：文本、数字、日期、数组</li>
            <li>按时间倒序显示，最新变更在最上方</li>
          </ul>
        </div>
      </Card>
    </div>
  );
}
