import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Badge } from '../ui/badge';
import { Button } from '../ui/button';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { ScrollArea } from '../ui/scroll-area';
import { 
  Wrench, 
  Calendar, 
  Clock, 
  DollarSign, 
  User, 
  Package, 
  AlertCircle,
  CheckCircle,
  TrendingUp,
  FileText,
  BarChart3
} from 'lucide-react';
import { machineryStorage } from '../../lib/machineryStorage';
import { materialStorage } from '../../lib/materialStorage';
import { initializeMaintenanceMockData, getMaintenanceStatistics } from '../../lib/maintenanceMockData';
import { MaintenanceRecord, MaintenanceType } from '../../types/machinery';

/**
 * 维护记录示例展示组件
 * 用于展示和说明维护记录的各种使用场景
 */
export function MaintenanceExamples() {
  const [records, setRecords] = useState<MaintenanceRecord[]>([]);
  const [selectedType, setSelectedType] = useState<MaintenanceType | 'all'>('all');
  const [stats, setStats] = useState<any>(null);

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

  const loadData = () => {
    // 初始化示例数据（如果没有）
    initializeMaintenanceMockData();
    
    // 加载所有维护记录
    const allRecords = machineryStorage.getAllMaintenanceRecords();
    setRecords(allRecords);
    
    // 获取统计信息
    const statistics = getMaintenanceStatistics();
    setStats(statistics);
  };

  // 过滤记录
  const filteredRecords = selectedType === 'all' 
    ? records 
    : records.filter(r => r.type === selectedType);

  // 格式化日期
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  // 格式化金额
  const formatCurrency = (amount: number) => {
    return `¥${amount.toLocaleString()}`;
  };

  // 获取维护类型颜色
  const getTypeColor = (type: MaintenanceType) => {
    const colors: Record<MaintenanceType, string> = {
      '日常保养': 'bg-info-muted text-info',
      '定期维护': 'bg-success-muted text-success',
      '故障维修': 'bg-warning-muted text-warning',
      '年检': 'bg-info-muted text-info',
    };
    return colors[type];
  };

  // 获取维护类型图标
  const getTypeIcon = (type: MaintenanceType) => {
    const icons: Record<MaintenanceType, any> = {
      '日常保养': <Wrench className="w-4 h-4" />,
      '定期维护': <Calendar className="w-4 h-4" />,
      '故障维修': <AlertCircle className="w-4 h-4" />,
      '年检': <CheckCircle className="w-4 h-4" />,
    };
    return icons[type];
  };

  return (
    <div className="space-y-6 p-6">
      {/* 页面标题 */}
      <div>
        <h2 className="text-primary mb-2">维护记录示例数据</h2>
        <p className="text-muted-foreground">
          展示农机全生命周期档案中的各类维护记录示例，包括日常保养、定期维护、故障维修和年检等场景
        </p>
      </div>

      {/* 统计卡片 */}
      {stats && (
        <div className="grid grid-cols-1 md:grid-cols-4 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.total}</p>
              </div>
              <FileText 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">{formatCurrency(stats.totalCost)}</p>
              </div>
              <DollarSign 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.totalWorkHours}h</p>
              </div>
              <Clock 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-warning">
                  {formatCurrency(Math.round(stats.avgCostPerRecord))}
                </p>
              </div>
              <TrendingUp className="w-12 h-12 text-warning opacity-50" />
            </div>
          </Card>
        </div>
      )}

      {/* 维护类型分布 */}
      {stats && (
        <Card className="p-6">
          <div className="flex items-center gap-2 mb-4">
            <BarChart3 className="w-5 h-5 text-primary" />
            <h3 className="text-primary">维护类型分布</h3>
          </div>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {Object.entries(stats.byType).map(([type, count]) => (
              <div key={type} className="text-center p-4 bg-muted/50 rounded-lg">
                <div className="flex items-center justify-center gap-2 mb-2">
                  {getTypeIcon(type as MaintenanceType)}
                  <span className="text-sm">{type}</span>
                </div>
                <p className="text-2xl">{count as number}</p>
                <p className="text-xs text-muted-foreground mt-1">
                  {stats.total > 0 ? Math.round((count as number) / stats.total * 100) : 0}%
                </p>
              </div>
            ))}
          </div>
        </Card>
      )}

      {/* 维护记录列表 */}
      <Card className="p-6">
        <Tabs value={selectedType} onValueChange={(v) => setSelectedType(v as any)}>
          <TabsList className="grid w-full grid-cols-5 mb-4">
            <TabsTrigger value="all">全部 ({records.length})</TabsTrigger>
            <TabsTrigger value="日常保养">
              日常保养 ({records.filter(r => r.type === '日常保养').length})
            </TabsTrigger>
            <TabsTrigger value="定期维护">
              定期维护 ({records.filter(r => r.type === '定期维护').length})
            </TabsTrigger>
            <TabsTrigger value="故障维修">
              故障维修 ({records.filter(r => r.type === '故障维修').length})
            </TabsTrigger>
            <TabsTrigger value="年检">
              年检 ({records.filter(r => r.type === '年检').length})
            </TabsTrigger>
          </TabsList>

          <TabsContent value={selectedType} className="mt-0">
            {filteredRecords.length === 0 ? (
              <div className="text-center py-12 text-muted-foreground">
                <FileText className="w-16 h-16 mx-auto mb-4 opacity-20" />
                <p>暂无{selectedType === 'all' ? '' : selectedType}记录</p>
                <Button 
                  variant="outline" 
                  size="sm" 
                  className="mt-4"
                  onClick={loadData}
                >
                  重新加载示例数据
                </Button>
              </div>
            ) : (
              <ScrollArea className="h-[600px] pr-4">
                <div className="space-y-4">
                  {filteredRecords
                    .sort((a, b) => new Date(b.startTime).getTime() - new Date(a.startTime).getTime())
                    .map((record) => {
                      const machinery = machineryStorage.getMachinery(record.machineryId);
                      
                      return (
                        <Card key={record.id} className="p-5 hover:shadow-lg transition-shadow">
                          {/* 记录头部 */}
                          <div className="flex items-start justify-between mb-4">
                            <div className="flex-1">
                              <div className="flex items-center gap-2 mb-2">
                                <Badge className={getTypeColor(record.type)}>
                                  <span className="mr-1">{getTypeIcon(record.type)}</span>
                                  {record.type}
                                </Badge>
                                <span className="text-sm text-muted-foreground">
                                  {machinery?.name || '未知设备'}
                                </span>
                              </div>
                              <h4 className="text-primary mb-1">
                                {record.maintenanceItems.substring(0, 50)}
                                {record.maintenanceItems.length > 50 ? '...' : ''}
                              </h4>
                            </div>
                            <div className="text-right">
                              <p className="text-success">{formatCurrency(record.cost)}</p>
                              <p className="text-xs text-muted-foreground mt-1">
                                {record.workHours}小时
                              </p>
                            </div>
                          </div>

                          {/* 维护详情 */}
                          <div className="space-y-3">
                            {/* 维护项目 */}
                            <div>
                              <p className="text-xs text-muted-foreground mb-1">维护项目：</p>
                              <p className="text-sm">{record.maintenanceItems}</p>
                            </div>

                            {/* 使用配件 */}
                            {record.partsAndMaterials && record.partsAndMaterials.length > 0 && (
                              <div>
                                <p className="text-xs text-muted-foreground mb-2">使用配件与耗材：</p>
                                <div className="flex flex-wrap gap-2">
                                  {record.partsAndMaterials.map((usage, idx) => {
                                    const material = materialStorage.getMaterial(usage.materialId);
                                    return material ? (
                                      <Badge key={idx} variant="outline" className="text-xs">
                                        <Package className="w-3 h-3 mr-1" />
                                        {material.name} × {usage.quantity}{material.unit}
                                      </Badge>
                                    ) : null;
                                  })}
                                </div>
                              </div>
                            )}

                            {/* 备注 */}
                            {record.remarks && (
                              <div className="bg-muted/50 p-3 rounded-lg">
                                <p className="text-xs text-muted-foreground mb-1">备注：</p>
                                <p className="text-sm">{record.remarks}</p>
                              </div>
                            )}

                            {/* 底部信息 */}
                            <div className="flex items-center justify-between pt-3 border-t text-xs text-muted-foreground">
                              <div className="flex items-center gap-4">
                                <div className="flex items-center gap-1">
                                  <User className="w-3 h-3" />
                                  <span>{record.technician}</span>
                                </div>
                                <div className="flex items-center gap-1">
                                  <Clock className="w-3 h-3" />
                                  <span>{formatDate(record.startTime)}</span>
                                </div>
                              </div>
                              {record.nextMaintenanceTime && (
                                <div className="flex items-center gap-1 text-warning">
                                  <Calendar className="w-3 h-3" />
                                  <span>
                                    下次: {new Date(record.nextMaintenanceTime).toLocaleDateString('zh-CN')}
                                  </span>
                                </div>
                              )}
                            </div>
                          </div>
                        </Card>
                      );
                    })}
                </div>
              </ScrollArea>
            )}
          </TabsContent>
        </Tabs>
      </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>
          </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>
  );
}
