import React from 'react';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/client/components/ui/dialog';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/client/components/ui/table';
import { Button } from '@/client/components/ui/button';
import type { SubmissionRecordsItem } from '@/client/admin/types/submission';

interface SubmissionComparisonDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  selectedRecords: SubmissionRecordsItem[];
}

export const SubmissionComparisonDialog: React.FC<SubmissionComparisonDialogProps> = ({
  open,
  onOpenChange,
  selectedRecords
}) => {
  // 生成对比数据
  const comparisonData = React.useMemo(() => {
    if (selectedRecords.length < 2) return { data: [], classrooms: [] };

    // 按教室号分组
    const groupedByClassroom: Record<string, SubmissionRecordsItem[]> = {};
    selectedRecords.forEach(record => {
      const classroom = record.classroomNo || '未知教室';
      if (!groupedByClassroom[classroom]) {
        groupedByClassroom[classroom] = [];
      }
      groupedByClassroom[classroom].push(record);
    });

    // 获取所有教室
    const classrooms = Object.keys(groupedByClassroom);
    if (classrooms.length < 2) return { data: [], classrooms };

    // 获取所有用户（按昵称或用户名）
    const allUsers = new Set<string>();
    selectedRecords.forEach(record => {
      const userName = record.user?.nickname || record.user?.username || `用户${record.userId}`;
      allUsers.add(userName);
    });

    // 生成对比表格数据
    const result: Array<{
      user: string;
      [classroom: string]: string | number | undefined;
    }> = [];

    // 为每个用户在每个教室中查找对应的记录
    allUsers.forEach(userName => {
      const row: { user: string; [classroom: string]: string | number | undefined } = { user: userName };
      
      classrooms.forEach(classroom => {
        const record = groupedByClassroom[classroom].find(
          r => (r.user?.nickname || r.user?.username || `用户${r.userId}`) === userName
        );
        
        if (record) {
          row[classroom] = record.totalProfitPercent !== null && record.totalProfitPercent !== undefined 
            ? `${record.totalProfitPercent}%`
            : '-';
        } else {
          row[classroom] = '-';
        }
      });
      
      result.push(row);
    });

    return { data: result, classrooms };
  }, [selectedRecords]);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[800px] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>提交记录对比</DialogTitle>
          <DialogDescription>
            对比选中的提交记录数据
          </DialogDescription>
        </DialogHeader>

        <div className="max-h-[60vh] overflow-auto">
          {comparisonData.data.length > 0 ? (
            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>用户</TableHead>
                    {comparisonData.classrooms.map(classroom => (
                      <TableHead key={classroom} className="text-center">
                        教室 {classroom}
                      </TableHead>
                    ))}
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {comparisonData.data.map((row, index) => (
                    <TableRow key={index}>
                      <TableCell className="font-medium">{row.user}</TableCell>
                      {comparisonData.classrooms.map(classroom => (
                        <TableCell key={classroom} className="text-center">
                          <span className={
                            (row[classroom] as string).startsWith('-')
                              ? 'text-green-500'
                              : row[classroom] !== '-' && row[classroom] !== '0%'
                                ? 'text-red-500'
                                : ''
                          }>
                            {row[classroom] || '-'}
                          </span>
                        </TableCell>
                      ))}
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          ) : (
            <div className="text-center py-8">
              <p className="text-muted-foreground">
                {selectedRecords.length < 2 
                  ? '请至少选择2条记录进行对比' 
                  : '无法生成对比数据，请选择不同教室的相同用户记录'}
              </p>
            </div>
          )}
        </div>

        <DialogFooter>
          <Button onClick={() => onOpenChange(false)}>
            关闭
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};