'use client';
import { useEffect, useState } from 'react';

interface Account {
  id: string;
  jid: string;
  displayName: string | null;
  status: string;
  platform: string;
}

export function AccountCard({ account }: { account: Account }) {
  const [qrDataUrl, setQrDataUrl] = useState<string | null>(null);
  const isDisconnected = account.status === 'DISCONNECTED';

  useEffect(() => {
    if (!isDisconnected) {
      setQrDataUrl(null);
      return;
    }

    async function fetchQr() {
      try {
        const res = await fetch(`/api/accounts/${account.id}/qr`);
        if (!res.ok) return;
        const data = await res.json();
        setQrDataUrl(data.qrDataUrl ?? null);
      } catch {
        // ignore fetch errors (e.g. network issues)
      }
    }

    fetchQr();
    const interval = setInterval(fetchQr, 5000);
    return () => clearInterval(interval);
  }, [account.id, isDisconnected]);

  return (
    <div className="border rounded-lg p-4 bg-white">
      <div className="flex items-center justify-between mb-2">
        <div>
          <p className="font-medium">{account.displayName ?? account.jid}</p>
          {account.displayName && (
            <p className="text-xs text-gray-500">{account.jid}</p>
          )}
        </div>
        <span
          className={`text-xs px-2 py-1 rounded-full font-medium ${
            account.status === 'ACTIVE'
              ? 'bg-green-100 text-green-700'
              : 'bg-yellow-100 text-yellow-700'
          }`}
        >
          {account.status === 'ACTIVE' ? 'Connected' : 'Awaiting scan'}
        </span>
      </div>

      {isDisconnected && qrDataUrl && (
        <div className="mt-3">
          <p className="text-sm text-gray-600 mb-2">
            Open WhatsApp → Linked Devices → Link a Device → scan below
          </p>
          <img src={qrDataUrl} alt="WhatsApp QR Code" className="w-48 h-48" />
        </div>
      )}

      {isDisconnected && !qrDataUrl && (
        <p className="text-sm text-gray-500 mt-2">Waiting for QR code from worker...</p>
      )}
    </div>
  );
}
