import React, { useMemo } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useSfdaAssetMatches, useSfdaEntryDetails } from '../hooks/useSfdaEntries';
import API_CONFIG from '../config/api';
import {
  FaArrowLeft,
  FaFileMedical,
  FaFilePdf,
  FaExternalLinkAlt,
  FaCheckCircle,
  FaTimesCircle,
  FaTable,
  FaInfoCircle,
  FaUser,
} from 'react-icons/fa';
import type { SfdaDeviceEntry } from '../services/sfdaEntriesService';

type DeviceDataColumnKey = Exclude<
  keyof SfdaDeviceEntry,
  'name' | 'detail_pdf' | 'ade_detail_url' | 'idx'
>;

const DEVICE_COLUMNS_BEFORE_ACTIONS: Array<{ key: DeviceDataColumnKey; labelKey: string }> = [
  { key: 'ncmdr_ref', labelKey: 'sfdaEntries.columns.ncmdrRef' },
  { key: 'manufacturer', labelKey: 'sfdaEntries.columns.manufacturer' },
  { key: 'material', labelKey: 'sfdaEntries.deviceFields.material' },
  { key: 'serial_no', labelKey: 'sfdaEntries.deviceFields.serialNo' },
  { key: 'serial_no_matching', labelKey: 'sfdaEntries.deviceFields.matching' },
];

const DEVICE_COLUMNS_AFTER_ACTIONS: Array<{ key: DeviceDataColumnKey; labelKey: string }> = [
  { key: 'catalog_number', labelKey: 'sfdaEntries.deviceFields.catalogNumber' },
  { key: 'udi', labelKey: 'sfdaEntries.deviceFields.udi' },
  { key: 'gstn', labelKey: 'sfdaEntries.deviceFields.gtin' },
  { key: 'material_description', labelKey: 'sfdaEntries.deviceFields.materialDescription' },
  { key: 'batch', labelKey: 'sfdaEntries.deviceFields.batch' },
];

const DEVICE_TABLE_COLUMN_COUNT =
  1 + DEVICE_COLUMNS_BEFORE_ACTIONS.length + 2 + DEVICE_COLUMNS_AFTER_ACTIONS.length;

function buildPdfUrl(detailPdf?: string): string | null {
  if (!detailPdf) return null;
  const baseUrl = API_CONFIG.BASE_URL || '';
  return detailPdf.startsWith('http') ? detailPdf : `${baseUrl}${detailPdf}`;
}

function isSerialNoMatchingYes(value?: string): boolean {
  return (value || '').trim().toLowerCase() === 'yes';
}

function formatMatchingValue(value?: string): string {
  const trimmed = (value || '').trim();
  return trimmed || '-';
}

interface MatchedValueLinkProps {
  value?: string;
  isMatch: boolean;
  onNavigate: (path: string) => void;
  title?: string;
}

const MatchedValueLink: React.FC<MatchedValueLinkProps> = ({ value, isMatch, onNavigate, title }) => {
  const trimmed = (value || '').trim();
  if (!trimmed) {
    return <>-</>;
  }
  if (!isMatch) {
    return <span className="text-xs line-clamp-3 break-words">{trimmed}</span>;
  }
  return (
    <button
      type="button"
      title={title}
      onClick={() => onNavigate(`/assets?serial_number=${encodeURIComponent(trimmed)}`)}
      className="text-red-600 dark:text-red-400 hover:underline font-medium text-left text-xs line-clamp-3 break-words"
    >
      {trimmed}
    </button>
  );
};

const SfdaEntriesDetail: React.FC = () => {
  const { t } = useTranslation();
  const { entryName } = useParams<{ entryName: string }>();
  const navigate = useNavigate();
  const { entry, loading, error } = useSfdaEntryDetails(entryName || null);

  const formatDate = (dateStr?: string) =>
    dateStr
      ? new Date(dateStr).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' })
      : '-';

  const formatDateTime = (dateStr?: string) =>
    dateStr
      ? new Date(dateStr).toLocaleString('en-US', {
          year: 'numeric',
          month: 'short',
          day: 'numeric',
          hour: '2-digit',
          minute: '2-digit',
        })
      : '-';

  const formatUsername = (email?: string) => {
    if (!email) return '-';
    const atIndex = email.indexOf('@');
    return atIndex === -1 ? email : email.substring(0, atIndex);
  };

  const isPassed = entry?.passed === 1 || entry?.passed === true;
  const deviceList = entry?.device_list || [];
  const { sortedDeviceList, matchedSerialNumbers, matchesLoading } = useSfdaAssetMatches(deviceList);

  const uniqueAlerts = useMemo(() => {
    const refs = new Set<string>();
    deviceList.forEach((row) => {
      if (row.ncmdr_ref) refs.add(row.ncmdr_ref);
    });
    return refs.size;
  }, [deviceList]);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-50 dark:bg-gray-900">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto" />
          <p className="mt-4 text-gray-600 dark:text-gray-400">{t('sfdaEntries.detail.loading')}</p>
        </div>
      </div>
    );
  }

  if (error || !entry) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-900 min-h-screen">
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-6">
          <h2 className="text-xl font-bold text-red-800 dark:text-red-300 mb-4">{t('sfdaEntries.detail.errorLoading')}</h2>
          <p className="text-red-700 dark:text-red-400 mb-4">{error || t('sfdaEntries.detail.notFound')}</p>
          <button onClick={() => navigate('/sfda-entries')} className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded">
            {t('sfdaEntries.detail.backToList')}
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 p-6">
      <div className="mb-6 flex justify-between items-center">
        <div className="flex items-center gap-4">
          <button
            onClick={() => navigate('/sfda-entries')}
            className="text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200"
          >
            <FaArrowLeft size={20} />
          </button>
          <div>
            <h1 className="text-2xl font-bold text-gray-800 dark:text-white flex items-center gap-3 flex-wrap">
              <FaFileMedical className="text-blue-500" />
              {entry.title || entry.name}
              <span
                className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-sm font-medium ${
                  isPassed
                    ? 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300 border border-green-200 dark:border-green-800'
                    : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-gray-600'
                }`}
              >
                {isPassed ? <FaCheckCircle size={12} /> : <FaTimesCircle size={12} />}
                {isPassed ? t('sfdaEntries.detail.passed') : t('sfdaEntries.detail.notPassed')}
              </span>
            </h1>
            <p className="text-gray-600 dark:text-gray-400 mt-1">
              {formatDate(entry.date)} · {uniqueAlerts} {t('sfdaEntries.detail.alerts')} · {deviceList.length}{' '}
              {t('sfdaEntries.detail.devices')}
            </p>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-6 mb-6">
        <div className="lg:col-span-3">
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 border border-gray-200 dark:border-gray-700 h-full">
            <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
              <FaInfoCircle className="text-blue-500" />
              {t('sfdaEntries.detail.entryInformation')}
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <Field label={t('sfdaEntries.columns.title')} value={entry.title} highlight />
              <Field label={t('sfdaEntries.columns.date')} value={formatDate(entry.date)} />
              <Field label={t('sfdaEntries.detail.alertCount')} value={String(uniqueAlerts)} />
              <Field label={t('sfdaEntries.detail.passedDate')} value={formatDateTime(entry.passed_date)} />
            </div>
          </div>
        </div>

        <div className="lg:col-span-1">
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-4 border border-gray-200 dark:border-gray-700 h-full">
            <h2 className="text-sm font-semibold text-gray-800 dark:text-white mb-3 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
              <FaUser className="text-purple-500" size={14} />
              {t('sfdaEntries.detail.auditInfo')}
            </h2>
            <div className="space-y-2">
              <div className="p-2 bg-gray-50 dark:bg-gray-700 rounded-lg">
                <p className="text-[10px] text-gray-500 dark:text-gray-400">{t('commonFields.createdOn')}</p>
                <p className="text-xs font-medium text-gray-900 dark:text-white">{formatDateTime(entry.creation)}</p>
              </div>
              <div className="p-2 bg-gray-50 dark:bg-gray-700 rounded-lg">
                <p className="text-[10px] text-gray-500 dark:text-gray-400">{t('commonFields.createdBy')}</p>
                <p className="text-xs font-medium text-gray-900 dark:text-white">{formatUsername(entry.owner)}</p>
              </div>
              <div className="p-2 bg-gray-50 dark:bg-gray-700 rounded-lg">
                <p className="text-[10px] text-gray-500 dark:text-gray-400">{t('commonFields.modifiedOn')}</p>
                <p className="text-xs font-medium text-gray-900 dark:text-white">{formatDateTime(entry.modified)}</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md border border-gray-200 dark:border-gray-700 overflow-hidden">
            <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
              <h2 className="text-lg font-semibold text-gray-800 dark:text-white flex items-center gap-2">
                <FaTable className="text-orange-500" />
                {t('sfdaEntries.detail.deviceList')}
              </h2>
              <span className="text-sm text-gray-500 dark:text-gray-400 flex items-center gap-2">
                {sortedDeviceList.length} {t('sfdaEntries.detail.devices')}
                {matchesLoading && (
                  <span className="inline-flex items-center gap-1 text-xs text-blue-600 dark:text-blue-400">
                    <span className="animate-spin rounded-full h-3 w-3 border-b-2 border-blue-500" />
                    {t('sfdaEntries.detail.resolvingMatches')}
                  </span>
                )}
              </span>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full text-xs">
                <thead className="bg-gray-100 dark:bg-gray-700">
                  <tr>
                    <th className="px-2 py-2 text-left text-[10px] font-medium text-gray-500 dark:text-gray-400 uppercase">
                      #
                    </th>
                    {DEVICE_COLUMNS_BEFORE_ACTIONS.map((col) => (
                      <th
                        key={col.key}
                        className="px-2 py-2 text-left text-[10px] font-medium text-gray-500 dark:text-gray-400 uppercase whitespace-nowrap"
                      >
                        {t(col.labelKey)}
                      </th>
                    ))}
                    <th className="px-2 py-2 text-left text-[10px] font-medium text-gray-500 dark:text-gray-400 uppercase whitespace-nowrap">
                      {t('sfdaEntries.detail.adeDetailPdf')}
                    </th>
                    <th className="px-2 py-2 text-left text-[10px] font-medium text-gray-500 dark:text-gray-400 uppercase whitespace-nowrap">
                      {t('sfdaEntries.detail.adeDetailUrl')}
                    </th>
                    {DEVICE_COLUMNS_AFTER_ACTIONS.map((col) => (
                      <th
                        key={col.key}
                        className="px-2 py-2 text-left text-[10px] font-medium text-gray-500 dark:text-gray-400 uppercase whitespace-nowrap"
                      >
                        {t(col.labelKey)}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                  {sortedDeviceList.length === 0 ? (
                    <tr>
                      <td
                        colSpan={DEVICE_TABLE_COLUMN_COUNT}
                        className="px-2 py-6 text-center text-xs text-gray-500 dark:text-gray-400"
                      >
                        {t('sfdaEntries.detail.noDevices')}
                      </td>
                    </tr>
                  ) : (
                    sortedDeviceList.map((row, index) => {
                      const pdfUrl = buildPdfUrl(row.detail_pdf);
                      const matchingYes = isSerialNoMatchingYes(row.serial_no_matching);
                      const serialTrimmed = (row.serial_no || '').trim();
                      const catalogTrimmed = (row.catalog_number || '').trim();
                      const serialIsMatch =
                        matchingYes && serialTrimmed !== '' && matchedSerialNumbers.has(serialTrimmed);
                      const catalogIsMatch =
                        matchingYes && catalogTrimmed !== '' && matchedSerialNumbers.has(catalogTrimmed);
                      const assetLinkTitle = t('sfdaEntries.detail.openMatchingAsset');

                      const renderDataCell = (col: { key: DeviceDataColumnKey; labelKey: string }) => (
                        <td key={col.key} className="px-2 py-2 text-xs text-gray-700 dark:text-gray-300 max-w-[10rem]">
                          {col.key === 'serial_no_matching' ? (
                            <span className="line-clamp-3 break-words">
                              {formatMatchingValue(row.serial_no_matching)}
                            </span>
                          ) : col.key === 'serial_no' ? (
                            <MatchedValueLink
                              value={row.serial_no}
                              isMatch={serialIsMatch}
                              onNavigate={navigate}
                              title={assetLinkTitle}
                            />
                          ) : col.key === 'catalog_number' ? (
                            <MatchedValueLink
                              value={row.catalog_number}
                              isMatch={catalogIsMatch}
                              onNavigate={navigate}
                              title={assetLinkTitle}
                            />
                          ) : (
                            <span className="line-clamp-3 break-words">{row[col.key] || '-'}</span>
                          )}
                        </td>
                      );

                      return (
                        <tr
                          key={row.name || index}
                          className={
                            matchingYes
                              ? 'bg-orange-50 dark:bg-orange-900/25 hover:bg-orange-100 dark:hover:bg-orange-900/35'
                              : 'hover:bg-gray-50 dark:hover:bg-gray-700/50'
                          }
                        >
                          <td className="px-2 py-2 text-xs text-gray-500 dark:text-gray-400">{index + 1}</td>
                          {DEVICE_COLUMNS_BEFORE_ACTIONS.map(renderDataCell)}
                          <td className="px-2 py-2 text-xs">
                            {pdfUrl ? (
                              <a
                                href={pdfUrl}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="text-red-600 dark:text-red-400 hover:underline inline-flex items-center gap-1 whitespace-nowrap"
                              >
                                <FaFilePdf size={10} />
                                {t('sfdaEntries.detail.openPdfNewTab')}
                              </a>
                            ) : (
                              '-'
                            )}
                          </td>
                          <td className="px-2 py-2 text-xs max-w-[6rem]">
                            {row.ade_detail_url ? (
                              <a
                                href={row.ade_detail_url}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="text-blue-600 dark:text-blue-400 hover:underline inline-flex items-center gap-1"
                                title={t('sfdaEntries.detail.viewAde')}
                              >
                                <FaExternalLinkAlt size={9} />
                                {/* {t('sfdaEntries.detail.viewAde')} */}
                              </a>
                            ) : (
                              '-'
                            )}
                          </td>
                          {DEVICE_COLUMNS_AFTER_ACTIONS.map(renderDataCell)}
                        </tr>
                      );
                    })
                  )}
                </tbody>
              </table>
            </div>
      </div>
    </div>
  );
};

interface FieldProps {
  label: string;
  value?: React.ReactNode;
  highlight?: boolean;
}

const Field: React.FC<FieldProps> = ({ label, value, highlight }) => (
  <div>
    <label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">{label}</label>
    <div
      className={`px-3 py-2 rounded-md border text-sm ${
        highlight
          ? 'bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800 text-blue-800 dark:text-blue-300 font-medium'
          : 'bg-gray-50 dark:bg-gray-700/50 border-gray-200 dark:border-gray-600 text-gray-900 dark:text-white'
      }`}
    >
      {value || '-'}
    </div>
  </div>
);

export default SfdaEntriesDetail;
