import { useState } from 'react';
import { ChevronDown, Users } from 'lucide-react';

import { StatePanel } from '@/components/ui/state-panel';
import { UserAvatar } from '@/components/common/UserAvatar';
import { TenantLogo } from '@/components/common/TenantLogo';
import type { DirectorQuizResultRow } from '@/business/director-dashboard/types';
import { cn } from '@/lib/utils';

interface DirectorQuizResultsPanelProps {
  readonly results: readonly DirectorQuizResultRow[];
}

export function DirectorQuizResultsPanel({ results }: DirectorQuizResultsPanelProps) {
  const [isPanelExpanded, setIsPanelExpanded] = useState(false);
  const [expandedUserIds, setExpandedUserIds] = useState<ReadonlySet<string>>(() => new Set());
  const completedQuizCount = results.reduce(
    (total, result) => total + result.completedCount,
    0,
  );
  const totalQuizCount = results.reduce(
    (total, result) => total + result.totalCount,
    0,
  );

  function toggleUser(userId: string) {
    setExpandedUserIds((current) => {
      const next = new Set(current);
      if (next.has(userId)) {
        next.delete(userId);
      } else {
        next.add(userId);
      }
      return next;
    });
  }

  return (
    <div className="bg-white rounded-2xl border border-violet-100 shadow-sm p-5">
      <button
        type="button"
        onClick={() => setIsPanelExpanded((current) => !current)}
        className="mb-4 flex w-full items-center justify-between gap-4 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-400 focus-visible:ring-offset-2"
        aria-expanded={isPanelExpanded}
        aria-controls="director-quiz-results-panel"
      >
        <span>
          <span className="font-semibold text-gray-800 flex items-center gap-2">
            <Users size={18} className="text-violet-500" />
            Quiz Results
          </span>
          <span className="mt-1 block text-sm text-gray-500">
            {results.length} staff · {completedQuizCount}/{totalQuizCount} quizzes complete
          </span>
        </span>
        <ChevronDown
          size={20}
          className={cn('shrink-0 text-gray-400 transition-transform', isPanelExpanded && 'rotate-180')}
          aria-hidden="true"
        />
      </button>

      <div id="director-quiz-results-panel">
        {isPanelExpanded && results.length > 0 ? (
          <div className="overflow-hidden rounded-xl border border-gray-100">
            <div className="grid grid-cols-[minmax(0,1.5fr)_minmax(0,1.2fr)_minmax(8rem,0.8fr)_minmax(7rem,0.7fr)_2rem] gap-3 bg-gray-50 px-4 py-3 text-xs font-semibold uppercase text-gray-500">
              <span>Staff</span>
              <span>Tenant</span>
              <span className="text-center">Role</span>
              <span className="text-center">Quizzes</span>
              <span className="sr-only">Toggle</span>
            </div>
            <div className="divide-y divide-gray-100">
              {results.map((result) => {
                const isExpanded = expandedUserIds.has(result.id);
                return (
                  <div key={result.id}>
                    <button
                      type="button"
                      onClick={() => toggleUser(result.id)}
                      className="grid w-full grid-cols-[minmax(0,1.5fr)_minmax(0,1.2fr)_minmax(8rem,0.8fr)_minmax(7rem,0.7fr)_2rem] items-center gap-3 bg-white px-4 py-3 text-left transition-transform hover:scale-[1.005] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-400 focus-visible:ring-offset-2"
                      aria-expanded={isExpanded}
                      aria-controls={`quiz-results-${result.id}`}
                    >
                      <span className="flex min-w-0 items-center gap-2">
                        <UserAvatar
                          name={result.staffName}
                          avatarUrl={result.avatar}
                          className="h-8 w-8 border-gray-200 bg-gray-100 text-[10px] text-gray-600"
                        />
                        <span className="truncate font-medium text-gray-700">{result.staffName}</span>
                      </span>
                      <span className="flex min-w-0 items-center gap-2">
                        <TenantLogo
                          name={result.tenant}
                          logoUrl={result.tenantLogo}
                          className="h-7 w-7 rounded-md text-[10px]"
                        />
                        <span className="truncate text-sm text-gray-500">{result.tenant}</span>
                      </span>
                      <span className="text-center text-xs capitalize text-gray-500">{result.role}</span>
                      <span className="text-center">
                        <span className={cn(
                          'rounded-lg px-2.5 py-1 text-xs font-semibold',
                          result.completedCount === result.totalCount
                            ? 'bg-emerald-100 text-emerald-700'
                            : 'bg-amber-100 text-amber-700',
                        )}>
                          {result.completedCount}/{result.totalCount}
                        </span>
                      </span>
                      <ChevronDown
                        size={18}
                        className={cn('text-gray-400 transition-transform', isExpanded && 'rotate-180')}
                        aria-hidden="true"
                      />
                    </button>
                    {isExpanded && (
                      <div id={`quiz-results-${result.id}`} className="bg-gray-50 px-4 py-3">
                        <div className="overflow-hidden rounded-lg border border-gray-100 bg-white">
                          <div className="grid grid-cols-[minmax(0,1.3fr)_8rem_minmax(0,1fr)] gap-3 border-b border-gray-100 px-3 py-2 text-xs font-semibold uppercase text-gray-500">
                            <span>Quiz</span>
                            <span>Date</span>
                            <span>Result</span>
                          </div>
                          <div className="divide-y divide-gray-100">
                            {result.details.map((detail) => (
                              <div
                                key={`${result.id}-${detail.id}`}
                                className="grid grid-cols-[minmax(0,1.3fr)_8rem_minmax(0,1fr)] items-center gap-3 px-3 py-2 text-sm"
                              >
                                <span className="font-medium text-gray-700">{detail.quiz}</span>
                                <span className="text-xs text-gray-500">{detail.date}</span>
                                <span>
                                  <span className={cn(
                                    'rounded-lg px-2 py-0.5 text-xs font-semibold',
                                    detail.status === 'complete'
                                      ? 'bg-emerald-100 text-emerald-700'
                                      : 'bg-amber-100 text-amber-700',
                                  )}>
                                    {detail.result}
                                  </span>
                                </span>
                              </div>
                            ))}
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        ) : isPanelExpanded ? (
          <StatePanel className="border-0 bg-transparent" alignment="center">
            No staff are in this completion scope yet.
          </StatePanel>
        ) : (
          <div className="rounded-xl bg-gray-50 px-4 py-3 text-sm text-gray-500">
            Expand to review each staff member's quiz completion details.
          </div>
        )}
      </div>
    </div>
  );
}
