import { getApiBaseUrl, getMemberToken } from '../../_lib/api';
import Link from 'next/link';
import { GroupOptOutButton } from './GroupOptOutButton';

interface MemberGroupSummary {
  id: string;
  name: string;
  tenantId: string;
  scopes: string[];
  retentionDays: number;
  policyVersion: string;
  consentStatus: 'GRANTED' | 'REVOKED' | 'PENDING';
  joinedAt: string;
}

async function fetchGroups(token: string): Promise<MemberGroupSummary[] | null> {
  const res = await fetch(`${getApiBaseUrl()}/my/groups`, {
    headers: { Accept: 'application/json', Authorization: `Bearer ${token}` },
    cache: 'no-store',
  }).catch(() => null);
  if (!res || !res.ok) return null;
  return (await res.json()) as MemberGroupSummary[];
}

export default async function MyGroupsPage() {
  const token = await getMemberToken();
  if (!token) {
    return (
      <div className="max-w-2xl mx-auto mt-12 p-6 rounded-lg border border-yellow-200 bg-yellow-50">
        <h1 className="text-lg font-semibold text-yellow-800">Sign in required</h1>
        <p className="text-sm text-yellow-700">Complete onboarding to view your groups.</p>
      </div>
    );
  }

  const groups = await fetchGroups(token);
  if (!groups) {
    return (
      <div className="max-w-2xl mx-auto mt-12 p-6 rounded-lg border border-red-200 bg-red-50">
        <h1 className="text-lg font-semibold text-red-800">Couldn&apos;t load your groups</h1>
        <p className="text-sm text-red-700">Your session may have expired. Please try signing out and back in.</p>
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto mt-12 p-6">
      <h1 className="text-xl font-semibold mb-4">Your groups</h1>
      {groups.length === 0 ? (
        <p className="text-sm text-gray-500">
          You haven&apos;t joined any TOWER-managed groups yet.
        </p>
      ) : (
        <ul className="flex flex-col gap-3">
          {groups.map((g) => (
            <li key={g.id} className="rounded-xl border border-gray-200 bg-white p-4">
              <div className="flex items-start justify-between gap-4">
                <div>
                  <Link href={`/my/groups/${g.id}`} className="text-sm font-medium text-blue-600 underline">
                    {g.name}
                  </Link>
                  <div className="mt-1 text-xs text-gray-500">
                    Status:{' '}
                    <span
                      className={
                        g.consentStatus === 'GRANTED'
                          ? 'text-green-700'
                          : g.consentStatus === 'REVOKED'
                            ? 'text-red-700'
                            : 'text-yellow-700'
                      }
                    >
                      {g.consentStatus}
                    </span>
                    {' · '}Retention {g.retentionDays}d · Policy {g.policyVersion}
                  </div>
                  <div className="mt-1 text-xs text-gray-500">
                    Scopes: {g.scopes.join(', ')}
                  </div>
                </div>
                {g.consentStatus === 'GRANTED' && <GroupOptOutButton groupId={g.id} groupName={g.name} />}
              </div>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
