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

interface FullProfile {
  id: string;
  jid: string;
  displayName: string | null;
  avatar: string | null;
  hometown: string | null;
  currentLocation: string | null;
  interests: string[];
  language: string;
  digestPreference: string;
  directoryVisible: boolean;
  createdAt: string;
}

interface GroupSummary {
  id: string;
  name: string;
  joinedAt: string;
  consentStatus: string;
}

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

export default async function SettingsPage() {
  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 manage your account.</p>
      </div>
    );
  }

  const data = await fetchDashboard(token);

  return (
    <div className="max-w-2xl mx-auto space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-semibold text-gray-900">Profile &amp; settings</h1>
        <Link href="/my" className="text-sm text-indigo-600 hover:underline">← Dashboard</Link>
      </div>

      {/* Profile edit */}
      <section className="rounded-xl border border-gray-200 bg-white p-5">
        <h2 className="text-sm font-semibold text-gray-700 mb-4">Your profile</h2>
        {data ? (
          <ProfileForm
            initial={{
              displayName: data.profile.displayName,
              hometown: data.profile.hometown,
              currentLocation: data.profile.currentLocation,
              interests: data.profile.interests,
              language: data.profile.language,
              digestPreference: data.profile.digestPreference,
              directoryVisible: data.profile.directoryVisible,
            }}
          />
        ) : (
          <p className="text-sm text-gray-500">Could not load profile data.</p>
        )}
      </section>

      {/* Privacy center — consent records */}
      {data && data.groups.length > 0 && (
        <section className="rounded-xl border border-gray-200 bg-white p-5">
          <h2 className="text-sm font-semibold text-gray-700 mb-1">Privacy center</h2>
          <p className="text-xs text-gray-400 mb-4">
            You gave consent to receive messages from these groups. You can opt out at any time.
          </p>
          <div className="divide-y divide-gray-100">
            {data.groups.map((g) => (
              <div key={g.id} className="flex items-center justify-between py-3">
                <div>
                  <p className="text-sm font-medium text-gray-900">{g.name}</p>
                  <p className="text-xs text-gray-400">
                    Since {new Date(g.joinedAt).toLocaleDateString()} · {g.consentStatus === 'GRANTED' ? 'Active' : 'Revoked'}
                  </p>
                </div>
                {g.consentStatus === 'GRANTED' && (
                  <form method="POST" action="/api/my/opt-out">
                    <input type="hidden" name="groupId" value={g.id} />
                    <button
                      type="submit"
                      className="text-xs text-red-500 hover:text-red-700 border border-red-200 rounded-md px-3 py-1.5 hover:bg-red-50"
                    >
                      Opt out
                    </button>
                  </form>
                )}
              </div>
            ))}
          </div>
        </section>
      )}

      {/* Session */}
      <section className="rounded-xl border border-gray-200 bg-white p-5">
        <h2 className="text-sm font-semibold text-gray-700 mb-2">Session</h2>
        <p className="text-sm text-gray-600 mb-3">
          Sign out of your member portal. Your consent records are kept until you delete your account.
        </p>
        <MemberLogoutButton />
      </section>

      {/* Danger zone */}
      <section className="rounded-xl border border-red-200 bg-red-50 p-5">
        <h2 className="text-sm font-semibold text-red-800 mb-2">Delete your account</h2>
        <p className="text-sm text-red-700 mb-3">
          This permanently deletes your TOWER user record, all consent records, opt-out history, and
          sessions. The messages themselves stay in their original groups. This cannot be undone.
        </p>
        <DeleteAccountButton />
      </section>
    </div>
  );
}
