'use client';

import * as React from 'react';
import {
  Table,
  TableBody,
  TableCell,
  TableHeader,
  TableHead,
  TableRow,
} from '@/components/ui/table';
import { COMMON_DECORATORS } from '@/utils/decorators';
import { BE_UPLOADS } from '@/config/site-config';
import { HistoryApplicableOnSetTable } from './HistoryApplicableOnSetTable';
import CommonImage from '@/components/common/CommonImage';
import { CURRENCY_LIST } from '@/constants';

export function HistoryTable({ record }: { record: any }) {
  const { previous_content, current_content } = record;

  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', 'jpg', 'jpeg'].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>
    );
  };

  const renderAttachments = (files: string[] | undefined) => {
    if (!Array.isArray(files) || files.length === 0) {
      return null; // or return <p className="text-gray-500 italic">No attachments</p>;
    }

    return (
      <div className="list-add-widget">
        <ul className="list-disc list-inside">
          {files.map((fileUrl: string, index: number) => (
            <li className="update-successfully" key={index}>
              <div className="img-cont cursor-pointer">
                {renderAttachmentIcon(fileUrl)}
              </div>
            </li>
          ))}
        </ul>
      </div>
    );
  };

  return (
    <div className="w-full">
      <div className="overflow-hidden rounded-md border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Element</TableHead>
              <TableHead>Previous</TableHead>
              <TableHead>Current</TableHead>
            </TableRow>
          </TableHeader>

          {record.is_attachment ? (
            <TableBody>
              <TableRow key={'index'}>
                <TableCell>
                  {record?.current_content?.attachment_for === 'contract'
                    ? ' Contract'
                    : (` Set: ${record?.current_content?.record?.set_name}` as string)}{' '}
                  attachment(s) {record?.current_content?.action}{' '}
                </TableCell>
                <TableCell>
                  <div className="list-add-widget">
                    <ul className="list-disc list-inside">
                      {Array.isArray(record?.previous_content?.attachments) &&
                      record?.previous_content?.attachments.length > 0 ? (
                        record?.previous_content?.attachments.map(
                          (fileUrl: string, index: number) => (
                            <li
                              className="update-successfully"
                              key={`previous_content_${index}`}
                            >
                              <div className="img-cont cursor-pointer border-red-500">
                                {renderAttachmentIcon(fileUrl)}
                              </div>
                            </li>
                          ),
                        )
                      ) : (
                        <li className="text-gray-500 italic">No attachments</li>
                      )}
                    </ul>
                  </div>
                </TableCell>
                <TableCell>
                  <div className="list-add-widget">
                    <ul className="list-disc list-inside">
                      {Array.isArray(record?.current_content?.attachments) &&
                      record?.current_content?.attachments.length > 0 ? (
                        record?.current_content?.attachments.map(
                          (fileUrl: string, index: number) => (
                            <li
                              className="update-successfully"
                              key={`${index}`}
                            >
                              <div className="img-cont cursor-pointer">
                                {renderAttachmentIcon(fileUrl)}
                              </div>
                            </li>
                          ),
                        )
                      ) : (
                        <li className="text-gray-500 italic">No attachments</li>
                      )}
                    </ul>
                  </div>
                </TableCell>
              </TableRow>
            </TableBody>
          ) : (
            <TableBody>
              {[
                {
                  label: 'Client Country',
                  prev: previous_content?.client_from_countries,
                  curr: current_content?.client_from_countries,
                },
                {
                  label: 'Currency',
                  prev:
                    CURRENCY_LIST.find(
                      (item) =>
                        String(item.id) === String(previous_content.currency),
                    )?.name || 'N/A',
                  curr:
                    CURRENCY_LIST.find(
                      (item) =>
                        String(item.id) === String(current_content.currency),
                    )?.name || 'N/A',
                },
                {
                  label: 'Notes',
                  prev: previous_content.notes,
                  curr: current_content.notes,
                },
              ].map((row, index) => (
                <TableRow key={index}>
                  <TableCell>{row.label}</TableCell>
                  <TableCell className="whitespace-pre-line">
                    {row.prev as React.ReactNode}
                  </TableCell>
                  <TableCell className="whitespace-pre-line">
                    {row.curr as React.ReactNode}
                  </TableCell>
                </TableRow>
              ))}

              <TableRow>
                <TableCell>Student Condition</TableCell>
                <TableCell>
                  {COMMON_DECORATORS.student_condition(
                    previous_content,
                    'student_condition',
                  )}
                </TableCell>
                <TableCell>
                  {COMMON_DECORATORS.student_condition(
                    current_content,
                    'student_condition',
                  )}
                </TableCell>
              </TableRow>

              <TableRow>
                <TableCell>Campus Condition</TableCell>
                <TableCell>
                  {COMMON_DECORATORS.all_specific_condition(
                    previous_content,
                    'campus_condition',
                  )}
                </TableCell>
                <TableCell>
                  {COMMON_DECORATORS.all_specific_condition(
                    current_content,
                    'campus_condition',
                  )}
                </TableCell>
              </TableRow>

              <TableRow>
                <TableCell>Study Level Condition</TableCell>
                <TableCell>
                  {COMMON_DECORATORS.all_specific_condition(
                    previous_content,
                    'study_level_condition',
                  )}
                </TableCell>
                <TableCell>
                  {COMMON_DECORATORS.all_specific_condition(
                    current_content,
                    'study_level_condition',
                  )}
                </TableCell>
              </TableRow>

              <TableRow>
                <TableCell>Course Condition</TableCell>
                <TableCell>
                  {COMMON_DECORATORS.all_specific_condition(
                    previous_content,
                    'course_condition',
                  )}
                </TableCell>
                <TableCell>
                  {COMMON_DECORATORS.all_specific_condition(
                    current_content,
                    'course_condition',
                  )}
                </TableCell>
              </TableRow>

              {/* <TableRow>
                <TableCell>General Contract</TableCell>
                <TableCell>
                  {renderAttachments(
                    Array.isArray(previous_content?.attachment_file)
                      ? previous_content.attachment_file
                      : undefined,
                  )}
                </TableCell>
                <TableCell>
                  {renderAttachments(
                    Array.isArray(current_content?.attachment_file)
                      ? current_content.attachment_file
                      : undefined,
                  )}
                </TableCell>
              </TableRow> */}

              <TableRow>
                <TableCell>Applicable On Sets</TableCell>
                <TableCell>
                  <HistoryApplicableOnSetTable
                    applicableSets={
                      Array.isArray(
                        previous_content?.vcm_commission_contract_applicable_sets,
                      )
                        ? previous_content.vcm_commission_contract_applicable_sets
                        : []
                    }
                    selector="previous"
                  />
                </TableCell>
                <TableCell>
                  <HistoryApplicableOnSetTable
                    applicableSets={
                      Array.isArray(current_content?.applicable_sets)
                        ? current_content.applicable_sets
                        : []
                    }
                    selector="current"
                  />
                </TableCell>
              </TableRow>
            </TableBody>
          )}
        </Table>
      </div>
    </div>
  );
}
