'use client';

import * as React from 'react';
import { Table, TableBody, TableCell, TableRow } from '@/components/ui/table';
import { UnknownRecord } from '@/types';
import { BE_UPLOADS } from '@/config/site-config';
import {
  VC_APPLICABLE_COURSE_TYPES,
  VC_BONUS_TYPE,
  VC_COMMISSION_TYPE,
  VC_HAS_BONUS,
  VC_STUDENTS_DURATION,
} from '@/constants';
import CommonImage from '@/components/common/CommonImage';

export function HistorySetTable({
  sets,
  selector,
}: {
  sets: any;
  selector: string;
}) {
  const instancesKey =
    selector === 'current' ? 'instances' : 'vcm_commission_contract_instances';

  const getFileExtension = (fileUrl: string): string | null => {
    const match = fileUrl.match(/\.(\w+)(?:\?|#|$)/);
    return match ? match[1].toLowerCase() : null;
  };

  const renderAttachmentIcon = (fileUrl: string) => {
    const ext = getFileExtension(fileUrl);
    let iconSrc = '/main/file-icon.webp';
    let size = 50;

    if (['png', 'webp'].includes(ext || '')) {
      iconSrc = `${BE_UPLOADS}${fileUrl}`;
      size = 200;
    } else if (ext === 'pdf') {
      iconSrc = '/main/pdf-icon.webp';
    } else if (['xlsx', 'csv'].includes(ext || '')) {
      iconSrc = '/main/excel-icon.webp';
    } else if (['docx', 'doc'].includes(ext || '')) {
      iconSrc = '/main/word-icon.webp';
    }

    return (
      <button
        onClick={(e) => {
          e.preventDefault();
          e.stopPropagation();
        }}
      >
        <CommonImage
          src={iconSrc}
          width={size}
          height={size}
          alt="attachment"
          classname="view-icon"
        />
      </button>
    );
  };

  return (
    <div className="w-full">
      {sets.map((set: UnknownRecord, setIndex: number) => (
        <div
          className="overflow-hidden rounded-md border mb-6"
          key={`${selector}-${setIndex}`}
        >
          <Table>
            <TableBody>
              {[
                { label: 'Set Name:', value: set.set_name },
                { label: 'Min Number of Students:', value: set.min_students },
                { label: 'Max Number of Students:', value: set.max_students },
                {
                  label: 'Has Bonus:',
                  value:
                    VC_HAS_BONUS.find(
                      (item) => String(item.id) === String(set.has_bonus),
                    )?.name || 'N/A',
                },
                {
                  label: 'Bonus Type:',
                  value:
                    VC_BONUS_TYPE.find(
                      (item) => String(item.id) === String(set.bonus_type),
                    )?.name || 'N/A',
                },
                { label: 'Bonus Amount:', value: set.bonus_amount },
              ].map((row, index) => (
                <TableRow key={`${selector}-${index}`}>
                  <TableCell>{row.label}</TableCell>
                  <TableCell>{row.value as React.ReactNode}</TableCell>
                </TableRow>
              ))}

              {/* <TableRow>
                <TableCell>Specific Contract:</TableCell>
                <TableCell>
                  <div className="list-add-widget">
                    <ul className="list-disc list-inside">
                      {Array.isArray(set?.attachment_file) &&
                      set.attachment_file.length > 0 ? (
                        set.attachment_file.map(
                          (fileUrl: string, index: number) => (
                            <li
                              className="update-successfully"
                              key={`${selector}-${index}`}
                            >
                              <div className="img-cont cursor-pointer">
                                {renderAttachmentIcon(fileUrl)}
                              </div>
                            </li>
                          ),
                        )
                      ) : (
                        <li className="text-gray-500 italic">No attachments</li>
                      )}
                    </ul>
                  </div>
                </TableCell>
              </TableRow> */}

              <TableRow>
                <TableCell>Commission Instances:</TableCell>
                <TableCell>
                  {Array.isArray(set[instancesKey]) &&
                    set[instancesKey].length > 0 &&
                    set[instancesKey].map(
                      (instance: UnknownRecord, instanceIndex: number) => (
                        <div
                          className="overflow-hidden rounded-md border mb-4"
                          key={instanceIndex}
                        >
                          <Table>
                            <TableBody>
                              <TableRow>
                                <TableCell>
                                  Commission Instance {instanceIndex + 1}
                                </TableCell>
                                <TableCell>
                                  Type:{' '}
                                  {VC_COMMISSION_TYPE.find(
                                    (item) =>
                                      String(item.id) ===
                                      String(instance.commission_type),
                                  )?.name || 'N/A'}
                                </TableCell>
                                <TableCell>
                                  Amount:{' '}
                                  {
                                    instance.commission_amount as React.ReactNode
                                  }
                                </TableCell>
                              </TableRow>
                            </TableBody>
                          </Table>
                        </div>
                      ),
                    )}
                </TableCell>
              </TableRow>
            </TableBody>
          </Table>
        </div>
      ))}
    </div>
  );
}
