import React, { useMemo } from 'react';
import {
  FileText, Play, Clock, Trash2, User,
  Check, BookOpen, Plus
} from 'lucide-react';
import { useLanguage } from '../../context/LanguageContext';

export default function ModelCard({
  model,
  onAddAnnotation,
  onDelete,
  onSelectAnnotation,
  checkFilter = 'all'
}) {
  const { t, lang } = useLanguage();

  const filteredAnnotations = useMemo(() => {
    if (!model.annotations) return [];
    if (checkFilter === 'all') return model.annotations;
    if (checkFilter === 'checked') return model.annotations.filter((ann) => ann.isChecked);
    if (checkFilter === 'unchecked') return model.annotations.filter((ann) => !ann.isChecked);
    return model.annotations;
  }, [model.annotations, checkFilter]);

  const totalAnnotations = model.annotations?.length || 0;
  const hasAnnotations = filteredAnnotations.length > 0;
  const annotationCountLabel = checkFilter === 'all'
    ? String(totalAnnotations)
    : `${filteredAnnotations.length} / ${totalAnnotations}`;

  return (
    <div className={`group relative overflow-hidden rounded-[32px] border bg-white shadow-sm transition-all hover:shadow-xl ${hasAnnotations ? 'border-green-200' : 'border-slate-200'}`}>
      <div className="flex flex-col xl:flex-row">
        <div className="relative shrink-0 border-b border-slate-100 bg-gradient-to-br from-slate-50 via-white to-slate-50/40 p-5 xl:w-[280px] xl:border-b-0 xl:border-r">
          <button
            onClick={(e) => onDelete(e, model)}
            className="absolute right-4 top-4 p-2 text-slate-300 transition-all hover:rounded-xl hover:bg-red-50 hover:text-red-600 opacity-0 group-hover:opacity-100"
            title={t('deleteTooltip')}
          >
            <Trash2 size={18} />
          </button>

          <div className="mb-4 pr-10">
            <div className={`flex h-12 w-12 items-center justify-center rounded-2xl ${hasAnnotations ? 'bg-green-50 text-green-600' : 'bg-blue-50 text-blue-600'}`}>
              <FileText size={20} />
            </div>
          </div>

          <div className="space-y-3">
            <h3 className="truncate text-lg font-black text-slate-900" title={model.external_id}>
              {model.external_id}
            </h3>

            <div className="space-y-2.5">
              <div className="rounded-2xl border border-slate-200 bg-white/80 px-4 py-2.5">
                <div className="mb-1 flex items-center gap-2 text-[10px] font-black uppercase tracking-[0.18em] text-slate-400">
                  <Clock size={12} />
                  {t('uploadedAt')}
                </div>
                <div className="text-sm font-bold text-slate-800">
                  {new Date(model.created_at).toLocaleString(lang === 'cs' ? 'cs-CZ' : 'en-US')}
                </div>
              </div>

              <div className="rounded-2xl border border-slate-200 bg-white/80 px-4 py-2.5">
                <div className="mb-1 flex items-center gap-2 text-[10px] font-black uppercase tracking-[0.18em] text-slate-400">
                  <BookOpen size={12} className={hasAnnotations ? 'text-amber-500' : 'text-slate-400'} />
                  {t('annotations')}
                </div>
                <div className="text-sm font-bold text-slate-800">{annotationCountLabel}</div>
              </div>
            </div>
          </div>
        </div>

        <div className="min-w-0 flex-1 p-4 sm:p-5">
          <div className="mb-3 flex items-center justify-end gap-3">
            <div className="text-xs font-medium text-slate-400">{annotationCountLabel}</div>
          </div>

          <div className="overflow-x-auto pb-2">
            <div className="flex min-w-max gap-4 pr-2">
              <button
                onClick={() => onAddAnnotation(model)}
                className="flex w-[210px] shrink-0 flex-col items-center justify-center rounded-[24px] border-2 border-dashed border-slate-200 bg-slate-50/70 px-5 py-6 text-center transition-all hover:border-blue-300 hover:bg-blue-50 hover:shadow-md"
              >
                <div className="mb-3 flex h-12 w-12 items-center justify-center rounded-2xl bg-white text-slate-400 shadow-sm">
                  <Plus size={24} />
                </div>
                <div className="text-[10px] font-black uppercase tracking-[0.2em] text-slate-400">{t('addAnnotation')}</div>
                <div className="mt-1.5 text-sm font-bold text-slate-800">{model.external_id}</div>
              </button>

              {filteredAnnotations.map((ann) => {
                const filled = ann.filledTraitsCount || 0;
                const total = ann.totalTraitsInAtlas || 0;
                const isDone = filled >= total && total > 0;
                const progress = total > 0 ? Math.round((filled / total) * 100) : 0;

                return (
                  <div
                    key={ann.annotationId}
                    className={`w-[240px] shrink-0 rounded-[24px] border p-4 shadow-sm transition-all hover:-translate-y-0.5 hover:shadow-lg ${ann.isChecked ? 'border-green-200 bg-green-50/40' : 'border-slate-200 bg-white'}`}
                  >
                    <div className="mb-4 flex items-start justify-between gap-3">
                      <div className="min-w-0">
                        <div className="truncate text-base font-black text-slate-900">{ann.annotator || t('valueNotSpecified')}</div>
                        <div className="mt-1 flex items-center gap-2 text-[10px] font-bold uppercase tracking-[0.14em] text-slate-400">
                          <Clock size={11} />
                          {new Date(ann.lastUpdated).toLocaleString(lang === 'cs' ? 'cs-CZ' : 'en-US')}
                        </div>
                      </div>

                      <div className="flex flex-col items-end gap-2">
                        {/* <span className={`inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-[9px] font-black uppercase tracking-[0.14em] ${isDone ? 'bg-green-100 text-green-700' : 'bg-amber-100 text-amber-700'}`}>
                          {isDone ? <CheckCircle2 size={11} /> : <CircleDashed size={11} className={progress > 0 ? 'animate-spin' : ''} />}
                          {isDone ? t('statusDone') : t('statusInProgress')}
                        </span> */}
                        {ann.isChecked && (
                          <span className="inline-flex h-7 w-7 items-center justify-center rounded-full bg-green-100 text-green-700 shrink-0">
                            <Check size={10} />
                          </span>
                        )}
                      </div>
                    </div>

                    <div className="mb-4 space-y-2 text-[11px] font-semibold text-slate-600">
                      <div className="flex items-center gap-2">
                        <User size={12} className="text-blue-500" />
                        <span className="truncate">{ann.annotator || t('valueNotSpecified')}</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <BookOpen size={12} className="text-amber-500" />
                        <span className="truncate">{(lang === 'cs' ? ann.atlasNameCs : ann.atlasNameEn) || t('valueNotSpecified')}</span>
                      </div>
                    </div>

                    <div className="mb-4">
                      <div className="mb-2 flex items-center justify-between text-[10px] font-black uppercase tracking-[0.12em] text-slate-400">
                        <span>{filled} / {total} {t('traitsCount')}</span>
                        <span>{progress}%</span>
                      </div>
                      <div className="h-2 overflow-hidden rounded-full bg-slate-100">
                        <div
                          className={`h-full transition-all duration-700 ${ann.isChecked ? 'bg-green-500' : isDone ? 'bg-green-400' : 'bg-blue-600'}`}
                          style={{ width: `${Math.min(progress, 100)}%` }}
                        />
                      </div>
                    </div>

                    <button
                      onClick={() => onSelectAnnotation(ann.annotationId)}
                      className={`flex w-full items-center justify-center gap-2 rounded-2xl py-3 text-sm font-black text-white shadow-lg transition-all ${ann.isChecked ? 'bg-green-600 hover:bg-green-700' : 'bg-slate-900 hover:bg-blue-600'}`}
                    >
                      <Play size={14} fill="currentColor" />
                      {t('continue')}
                    </button>
                  </div>
                );
              })}

              {!hasAnnotations && (
                <div className="flex w-[240px] shrink-0 flex-col justify-center rounded-[24px] border border-slate-200 bg-slate-50/70 p-5 text-center">
                  <div className="mb-2 text-[10px] font-black uppercase tracking-[0.2em] text-slate-400">{t('noAnnotations')}</div>
                  <div className="text-sm font-semibold text-slate-600">
                    {checkFilter === 'all' ? t('addAnnotation') : t('noAnnotations')}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}