"use client";

import { useEffect, useState, type ReactNode } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { AdminBackLink } from "@/components/admin/AdminBackLink";
import { AdminBooleanBadge } from "@/components/admin/AdminBooleanBadge";
import {
  AdminDetailSection,
  AdminInfoList,
  AdminInfoRow,
} from "@/components/admin/AdminDetailSection";
import { AdminShell } from "@/components/admin/AdminShell";
import { AdminStatusBadge } from "@/components/admin/AdminStatusBadge";
import { AdminDetailSkeleton } from "@/components/admin/AdminTableSkeleton";
import { ErrorState } from "@/components/ui/ErrorState";
import { ApiError } from "@/lib/api";
import { adminListHref } from "@/lib/admin-list-query";
import { adminApi, formatAdminDate } from "@/lib/api/admin";
import type { AdminUserDetail } from "@/types/admin";

function ActivityLink({
  href,
  count,
  label,
}: {
  href: string | null;
  count: number;
  label: string;
}): ReactNode {
  if (!href || count <= 0) {
    return (
      <span>
        {count}
        <span className="ml-1 text-ink-40">{label}</span>
      </span>
    );
  }

  return (
    <Link href={href} className="text-primary underline-offset-2 hover:underline">
      {count}
      <span className="ml-1 text-ink-60">{label}</span>
    </Link>
  );
}

export function AdminUserDetailPage() {
  return (
    <AdminShell title="User" subtitle="Profile & operational status">
      {() => <UserDetailContent />}
    </AdminShell>
  );
}

function UserDetailContent() {
  const params = useParams<{ id: string }>();
  const id = Number(params.id);
  const [user, setUser] = useState<AdminUserDetail | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  async function load() {
    if (!Number.isFinite(id)) {
      setError("Invalid user id.");
      setLoading(false);
      return;
    }
    setLoading(true);
    setError(null);
    try {
      setUser(await adminApi.getUser(id));
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "Unable to load user.");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    void load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]);

  if (loading) {
    return <AdminDetailSkeleton />;
  }

  if (error || !user) {
    return (
      <div className="space-y-4">
        <AdminBackLink href="/admin/users">Back to users</AdminBackLink>
        <ErrorState title="User unavailable" message={error ?? "Not found."} onRetry={() => void load()} />
      </div>
    );
  }

  const profileName =
    user.creator_profile?.display_name ??
    user.brand_profile?.company_name ??
    null;

  return (
    <div className="space-y-5">
      <AdminBackLink href="/admin/users">Back to users</AdminBackLink>

      <header className="rounded-[10px] border border-line/80 bg-surface p-4 shadow-pv sm:p-5">
        <div className="flex flex-wrap items-center gap-2">
          <h2 className="text-[1.25rem] font-semibold tracking-[-0.02em] text-primary">{user.name}</h2>
          <AdminStatusBadge status={user.account_type} />
          <AdminStatusBadge status={user.status} />
        </div>
        <div className="mt-2.5 flex flex-wrap gap-x-5 gap-y-1 text-[0.8125rem] text-ink-60">
          <span>{user.email}</span>
          {profileName ? <span>Profile · {profileName}</span> : null}
          <span className="text-ink-40">Created {formatAdminDate(user.created_at)}</span>
        </div>
      </header>

      <div className="grid gap-4 lg:grid-cols-2">
        <AdminDetailSection title="Profile">
          <AdminInfoList>
            <AdminInfoRow label="Email verified">
              {user.email_verified ? "Yes" : "No"}
            </AdminInfoRow>
            <AdminInfoRow label="Onboarding">
              {user.onboarding_completed ? "Complete" : "Incomplete"}
            </AdminInfoRow>
            {user.creator_profile ? (
              <>
                <AdminInfoRow label="Display name">
                  {user.creator_profile.display_name ?? "—"}
                </AdminInfoRow>
                <AdminInfoRow label="Username">
                  {user.creator_profile.username ? `@${user.creator_profile.username}` : "—"}
                </AdminInfoRow>
                <AdminInfoRow label="Niche">{user.creator_profile.niche ?? "—"}</AdminInfoRow>
                <AdminInfoRow label="Country">{user.creator_profile.country ?? "—"}</AdminInfoRow>
                {user.creator_profile.website ? (
                  <AdminInfoRow label="Website">{user.creator_profile.website}</AdminInfoRow>
                ) : null}
                {user.creator_profile.bio ? (
                  <AdminInfoRow label="Bio">
                    <span className="leading-snug text-ink-60">{user.creator_profile.bio}</span>
                  </AdminInfoRow>
                ) : null}
              </>
            ) : null}
            {user.brand_profile ? (
              <>
                <AdminInfoRow label="Company">
                  {user.brand_profile.company_name ?? "—"}
                </AdminInfoRow>
                <AdminInfoRow label="Username">
                  {user.brand_profile.username ? `@${user.brand_profile.username}` : "—"}
                </AdminInfoRow>
                <AdminInfoRow label="Industry">{user.brand_profile.industry ?? "—"}</AdminInfoRow>
                <AdminInfoRow label="Location">{user.brand_profile.location ?? "—"}</AdminInfoRow>
                {user.brand_profile.website ? (
                  <AdminInfoRow label="Website">{user.brand_profile.website}</AdminInfoRow>
                ) : null}
                {user.brand_profile.bio ? (
                  <AdminInfoRow label="Bio">
                    <span className="leading-snug text-ink-60">{user.brand_profile.bio}</span>
                  </AdminInfoRow>
                ) : null}
              </>
            ) : null}
          </AdminInfoList>
        </AdminDetailSection>

        <AdminDetailSection
          title="Social connections"
          description={`${user.social_summary.connected}/${user.social_summary.total} connected`}
        >
          {user.social_accounts.length === 0 ? (
            <p className="py-3 text-[0.8125rem] text-ink-60">No social accounts linked.</p>
          ) : (
            <ul className="divide-y divide-line">
              {user.social_accounts.map((account) => (
                <li
                  key={account.id}
                  className="flex flex-wrap items-center justify-between gap-2 py-2.5 text-[0.8125rem]"
                >
                  <div className="min-w-0">
                    <p className="font-medium capitalize text-primary">{account.provider}</p>
                    <p className="text-[0.75rem] text-ink-60">@{account.username ?? "—"}</p>
                  </div>
                  <div className="flex items-center gap-2">
                    <AdminStatusBadge status={account.status} />
                    <span className="text-[0.75rem] text-ink-40">
                      {formatAdminDate(account.connected_at)}
                    </span>
                  </div>
                </li>
              ))}
            </ul>
          )}
        </AdminDetailSection>

        {user.stripe_connect ? (
          <AdminDetailSection title="Stripe Connect">
            <AdminInfoList>
              <AdminInfoRow label="Connected">
                <AdminBooleanBadge
                  enabled={user.stripe_connect.connected}
                  enabledLabel="Connected"
                  disabledLabel="Not connected"
                />
              </AdminInfoRow>
              <AdminInfoRow label="Readiness">
                <AdminStatusBadge status={user.stripe_connect.readiness} />
              </AdminInfoRow>
              <AdminInfoRow label="Charges enabled">
                <AdminBooleanBadge enabled={user.stripe_connect.charges_enabled} />
              </AdminInfoRow>
              <AdminInfoRow label="Payouts enabled">
                <AdminBooleanBadge enabled={user.stripe_connect.payouts_enabled} />
              </AdminInfoRow>
              <AdminInfoRow label="Account">
                <span className="font-mono text-[0.75rem] text-ink-60">
                  {user.stripe_connect.provider_account_id ?? "—"}
                </span>
              </AdminInfoRow>
              <AdminInfoRow label="Details submitted">
                {user.stripe_connect.details_submitted ? "Yes" : "No"}
              </AdminInfoRow>
              <AdminInfoRow label="Last synced">
                {formatAdminDate(user.stripe_connect.requirements_synced_at)}
              </AdminInfoRow>
            </AdminInfoList>
          </AdminDetailSection>
        ) : null}

        <AdminDetailSection title="Marketplace activity">
          <AdminInfoList>
            <AdminInfoRow label="Campaigns">
              <ActivityLink
                count={user.activity_summary.campaigns}
                label="campaigns"
                href={
                  user.brand_profile
                    ? adminListHref("/admin/campaigns", {
                        brand_profile_id: user.brand_profile.id,
                      })
                    : user.creator_profile
                      ? adminListHref("/admin/campaigns", {
                          creator_profile_id: user.creator_profile.id,
                        })
                      : null
                }
              />
            </AdminInfoRow>
            <AdminInfoRow label="Applications">
              <ActivityLink
                count={user.activity_summary.applications}
                label="(via campaigns)"
                href={
                  user.creator_profile && user.activity_summary.applications > 0
                    ? adminListHref("/admin/campaigns", {
                        creator_profile_id: user.creator_profile.id,
                      })
                    : null
                }
              />
            </AdminInfoRow>
            <AdminInfoRow label="Participations">
              <ActivityLink
                count={user.activity_summary.participations}
                label="deliverables"
                href={
                  user.creator_profile && user.activity_summary.participations > 0
                    ? adminListHref("/admin/deliverables", {
                        creator_profile_id: user.creator_profile.id,
                      })
                    : null
                }
              />
            </AdminInfoRow>
          </AdminInfoList>
        </AdminDetailSection>

        <AdminDetailSection title="Financial summary" className="lg:col-span-2">
          <AdminInfoList>
            <AdminInfoRow label="Earnings records">
              <ActivityLink
                count={user.activity_summary.earnings}
                label="earnings"
                href={
                  user.creator_profile && user.activity_summary.earnings > 0
                    ? adminListHref("/admin/finance/earnings", {
                        creator_profile_id: user.creator_profile.id,
                      })
                    : null
                }
              />
            </AdminInfoRow>
            <AdminInfoRow label="Payment records">
              <ActivityLink
                count={user.activity_summary.payments}
                label="payments"
                href={
                  user.brand_profile && user.activity_summary.payments > 0
                    ? adminListHref("/admin/finance/payments", {
                        brand_profile_id: user.brand_profile.id,
                      })
                    : null
                }
              />
            </AdminInfoRow>
            {user.stripe_connect?.provider_account_id ? (
              <AdminInfoRow label="Stripe account">
                <Link
                  href={adminListHref("/admin/finance/stripe", {
                    search: user.stripe_connect.provider_account_id,
                  })}
                  className="font-mono text-[0.75rem] text-primary underline-offset-2 hover:underline"
                >
                  {user.stripe_connect.provider_account_id}
                </Link>
              </AdminInfoRow>
            ) : null}
          </AdminInfoList>
        </AdminDetailSection>
      </div>
    </div>
  );
}
