'use client';

import { apiFetch } from '@/lib/api/client';
import { useQueryClient } from '@tanstack/react-query';

interface Signer {
  id: string;
  signerName: string;
  signerEmail: string;
  signerRole: string;
  signingOrder: number;
  status: string;
  signedAt?: string | null;
}

interface SigningProgressProps {
  documentId: string;
  signers: Signer[];
}

const STATUS_COLORS: Record<string, string> = {
  pending: 'bg-muted border-muted-foreground/30 text-muted-foreground',
  signed: 'bg-green-100 border-green-500 text-green-800',
  declined: 'bg-red-100 border-red-500 text-red-800',
};

const STATUS_LABELS: Record<string, string> = {
  pending: 'Pending',
  signed: 'Signed',
  declined: 'Declined',
};

const ROLE_LABELS: Record<string, string> = {
  client: 'Client',
  developer: 'Developer',
  approver: 'Sales/Approver',
};

export function SigningProgress({ documentId, signers }: SigningProgressProps) {
  const queryClient = useQueryClient();

  const sorted = [...signers].sort((a, b) => a.signingOrder - b.signingOrder);

  const handleResend = async (_signer: Signer) => {
    try {
      await apiFetch(`/api/v1/documents/${documentId}/remind`, { method: 'POST' });
      queryClient.invalidateQueries({ queryKey: ['documents', documentId, 'signers'] });
    } catch {
      // silent
    }
  };

  return (
    <div className="flex items-start gap-2">
      {sorted.map((signer, idx) => (
        <div key={signer.id} className="flex items-center gap-2">
          <div className="flex flex-col items-center gap-1">
            <div
              className={`flex h-10 w-10 items-center justify-center rounded-full border-2 text-xs font-bold ${STATUS_COLORS[signer.status] ?? STATUS_COLORS.pending}`}
            >
              {signer.signingOrder}
            </div>
            <div className="max-w-24 text-center">
              <p className="truncate text-xs font-medium">{signer.signerName}</p>
              <p className="truncate text-xs text-muted-foreground">
                {ROLE_LABELS[signer.signerRole] ?? signer.signerRole}
              </p>
              <p className="text-xs text-muted-foreground">
                {STATUS_LABELS[signer.status] ?? signer.status}
              </p>
              {signer.signedAt && (
                <p className="text-xs text-muted-foreground">
                  {new Date(signer.signedAt).toLocaleDateString('en-GB')}
                </p>
              )}
              {signer.status === 'pending' && (
                <button
                  onClick={() => handleResend(signer)}
                  className="mt-1 text-xs text-primary underline hover:no-underline"
                >
                  Resend
                </button>
              )}
            </div>
          </div>
          {idx < sorted.length - 1 && <div className="mb-6 h-0.5 w-8 shrink-0 bg-border" />}
        </div>
      ))}
    </div>
  );
}
