import React from 'react';
import { CheckCircle2, FileDown, Lock, Save, Share2 } from 'lucide-react';
import ExerciseInput from './ExerciseInput';
import SaveDialog from './SaveDialog';
import { downloadAssessmentPdf } from '../../utils/pdfExport';
import { useTranslation } from '../../i18n/LanguageContext';

const PatDetail = ({
  currentAssessment,
  hasUnsavedChanges,
  onBack,
  onSave,
  onAssessmentChange,
  onUpdateExercise,
  onMarkDirty,
  showSaveDialog,
  onSaveAndExit,
  onDiscardAndExit,
  onCancelExit,
  getPatTypeColor,
  getAchievement,
  calculateTotal,
  isReadOnly = false,
  canFinalize = false,
  finalizeDisabledReason = '',
  onFinalize,
  isShareActive = false,
  testsVisible = true,
  canShare = false,
  shareDisabledReason = '',
  onShare,
  onRevokeShare
}) => {
  const t = useTranslation();

  if (!currentAssessment) return null;

  const totalPoints = calculateTotal();
  const achievement = getAchievement(currentAssessment?.patType, totalPoints);
  const handleDownloadPdf = async () => {
    await downloadAssessmentPdf({
      assessment: currentAssessment,
      totalPoints,
      achievement
    });
  };

  return (
    <div className="min-h-screen bg-gray-100 dark:bg-gray-950 p-6 text-gray-900 dark:text-gray-100">
      <div className="max-w-5xl mx-auto">
        <SaveDialog
          show={showSaveDialog}
          onSave={onSaveAndExit}
          onDiscard={onDiscardAndExit}
          onCancel={onCancelExit}
        />

        <div className="bg-white dark:bg-gray-900 rounded-lg shadow-lg p-6 border border-gray-200 dark:border-gray-800">
          <div className="flex justify-between items-center mb-6">
            <div className="flex items-center gap-4">
              <button
                onClick={onBack}
                className="text-gray-600 dark:text-gray-300 hover:text-gray-800 dark:hover:text-gray-100 font-medium"
              >
                {t('detail.back')}
              </button>
              {hasUnsavedChanges && (
                <span className="text-orange-500 dark:text-orange-300 text-sm font-semibold">
                  {t('detail.unsaved')}
                </span>
              )}
              <span
                className={`px-4 py-2 rounded-full text-sm font-semibold ${getPatTypeColor(
                  currentAssessment?.patType
                )}`}
              >
                {currentAssessment?.patType}
              </span>
              {isShareActive && (
                <span className={`px-4 py-2 rounded-full text-sm font-semibold ${
                  testsVisible
                    ? 'bg-sky-100 text-sky-800 dark:bg-sky-900/40 dark:text-sky-200'
                    : 'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-200'
                }`}>
                  {testsVisible ? t('detail.share_active') : t('detail.share_paused')}
                </span>
              )}
              {currentAssessment?.isFinalized && (
                <span className="px-4 py-2 rounded-full text-sm font-semibold bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-200">
                  {t('detail.finalized')}
                </span>
              )}
            </div>
            <div className="flex gap-2">
              {!isReadOnly && (
                <>
                  <button
                    onClick={onSave}
                    className="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition flex items-center gap-2 text-sm"
                  >
                    <Save className="w-4 h-4" aria-hidden="true" />
                    {t('detail.save')}
                  </button>
                  <button
                    onClick={onFinalize}
                    disabled={!canFinalize}
                    title={finalizeDisabledReason || 'Test final abschließen'}
                    className={`px-4 py-2 rounded-lg transition flex items-center gap-2 text-sm ${
                      canFinalize
                        ? 'bg-emerald-700 text-white hover:bg-emerald-800'
                        : 'bg-gray-300 dark:bg-gray-700 text-gray-500 dark:text-gray-400 cursor-not-allowed'
                    }`}
                  >
                    <CheckCircle2 className="w-4 h-4" aria-hidden="true" />
                    {t('detail.finalize')}
                  </button>
                </>
              )}
              <button
                onClick={handleDownloadPdf}
                className="bg-amber-600 text-white px-4 py-2 rounded-lg hover:bg-amber-700 transition flex items-center gap-2 text-sm"
              >
                <FileDown className="w-4 h-4" aria-hidden="true" />
                {t('detail.pdf')}
              </button>
              <button
                onClick={onShare}
                disabled={!canShare}
                title={shareDisabledReason || 'Test als Link teilen'}
                className={`px-4 py-2 rounded-lg transition flex items-center gap-2 text-sm ${
                  canShare
                    ? 'bg-sky-600 text-white hover:bg-sky-700'
                    : 'bg-gray-300 dark:bg-gray-700 text-gray-500 dark:text-gray-400 cursor-not-allowed'
                }`}
              >
                <Share2 className="w-4 h-4" aria-hidden="true" />
                {t('detail.share')}
              </button>
              {isShareActive && (
                <button
                  onClick={onRevokeShare}
                  className="border border-rose-300 text-rose-700 dark:border-rose-700 dark:text-rose-300 px-4 py-2 rounded-lg hover:bg-rose-50 dark:hover:bg-rose-950/40 transition text-sm"
                >
                  {t('detail.unshare')}
                </button>
              )}
            </div>
          </div>

          {isReadOnly && (
            <div className="mb-6 rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-3 text-emerald-800 dark:border-emerald-900/60 dark:bg-emerald-950/40 dark:text-emerald-200">
              <div className="flex items-center gap-2 font-semibold">
                <Lock className="h-4 w-4" aria-hidden="true" />
                {t('detail.readonly')}
              </div>
              <p className="mt-1 text-sm">
                {t('detail.readonly_hint')}
              </p>
            </div>
          )}

          <div className="grid grid-cols-4 gap-2 mb-6 bg-gray-50 dark:bg-gray-800 p-4 rounded">
            <div className="font-bold">{t('detail.date_name')}</div>
            <div></div>
            <input
              type="date"
              value={currentAssessment?.datum || ''}
              disabled={isReadOnly}
              onChange={(e) => {
                onAssessmentChange({ ...currentAssessment, datum: e.target.value });
                onMarkDirty();
              }}
              className={`px-3 py-2 border border-gray-300 dark:border-gray-700 rounded bg-white dark:bg-gray-900 ${
                isReadOnly ? 'opacity-70 cursor-not-allowed bg-gray-100 dark:bg-gray-800' : ''
              }`}
            />
            <input
              type="text"
              value={currentAssessment?.name || ''}
              disabled={isReadOnly}
              onChange={(e) => {
                onAssessmentChange({ ...currentAssessment, name: e.target.value });
                onMarkDirty();
              }}
              placeholder={t('detail.name_placeholder')}
              className={`px-3 py-2 border border-gray-300 dark:border-gray-700 rounded bg-white dark:bg-gray-900 ${
                isReadOnly ? 'opacity-70 cursor-not-allowed bg-gray-100 dark:bg-gray-800' : ''
              }`}
            />
          </div>

          {currentAssessment?.exercises.map((exercise, exIndex) => (
            <div key={exIndex} className="mb-6 border-b pb-4 border-gray-200 dark:border-gray-800">
              <div className="font-bold text-lg mb-2 text-gray-700 dark:text-gray-200">{exercise.name}</div>

              <ExerciseInput exercise={exercise} exIndex={exIndex} onChange={onUpdateExercise} disabled={isReadOnly} />

              <div className="grid grid-cols-5 gap-2 mb-1 bg-blue-50 dark:bg-blue-900/30 p-2 rounded">
                <div className="font-semibold">{t('detail.col_avg_target', { soll: exercise.soll })}</div>
                <div className="font-semibold">{t('detail.col_actual')}</div>
                <div className="font-bold text-center">{exercise.durchschnitt.toFixed(2)}</div>
              </div>

              <div className="grid grid-cols-5 gap-2 mb-1">
                <div>{t('detail.col_factor')}</div>
                <div></div>
                <div className="text-center font-semibold">{exercise.faktor}</div>
              </div>

              <div className="grid grid-cols-5 gap-2 bg-green-50 dark:bg-green-900/30 p-2 rounded">
                <div className="font-bold">{t('detail.col_points')}</div>
                <div></div>
                <div className="text-center font-bold text-green-600 dark:text-green-300">{exercise.points.toFixed(0)}</div>
              </div>
            </div>
          ))}

          <div className="mt-6 bg-gradient-to-r from-green-100 to-blue-100 dark:from-gray-800 dark:to-gray-700 p-6 rounded-lg">
            <div className="flex justify-between items-center mb-4">
              <span className="text-2xl font-bold text-gray-800 dark:text-gray-100">{t('detail.col_result')}</span>
              <span className="text-4xl font-bold text-green-600 dark:text-green-300">{totalPoints.toFixed(0)}</span>
            </div>

            <div className={`mt-4 px-6 py-4 rounded-lg ${achievement.color} ${achievement.text} text-center`}>
              <p className="text-2xl font-bold">{achievement.name}</p>
              {achievement.subtitle && <p className="text-lg mt-2">{achievement.subtitle}</p>}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default PatDetail;
