import { createFileRoute, redirect } from "@tanstack/react-router";
import { useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { AuthLayout, submitClass } from "@/components/auth/AuthLayout";

type OAuthDetails = {
  client?: { name?: string | null } | null;
  redirect_url?: string | null;
  redirect_to?: string | null;
};

function redirectTarget(value: unknown): string | null {
  const v = (value ?? null) as OAuthDetails | null;
  return v?.redirect_url ?? v?.redirect_to ?? null;
}

export const Route = createFileRoute("/.lovable/oauth/consent")({
  ssr: false,
  head: () => ({
    meta: [
      { title: "Authorize access | Emma Mold Inspection Services" },
      { name: "description", content: "Approve or deny an AI assistant's request to access your Emma Mold account." },
      { property: "og:title", content: "Authorize access | Emma Mold" },
      { property: "og:description", content: "Review and approve app access to your Emma Mold inspection data." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
  }),
  validateSearch: (s: Record<string, unknown>) => ({
    authorization_id: typeof s.authorization_id === "string" ? s.authorization_id : "",
  }),
  beforeLoad: async ({ search, location }) => {
    if (!search.authorization_id) throw new Error("Missing authorization_id");
    const { data } = await supabase.auth.getSession();
    const next = location.pathname + location.searchStr;
    if (!data.session) throw redirect({ to: "/auth/customer", search: { next } });
  },
  loader: async ({ location }) => {
    const authorizationId = new URLSearchParams(location.search).get("authorization_id")!;
    const { data, error } = await supabase.auth.oauth.getAuthorizationDetails(authorizationId);
    if (error) throw error;
    const details = data as OAuthDetails | null;
    const immediate = redirectTarget(details);
    if (immediate && !details?.client) throw redirect({ href: immediate });
    return details;
  },
  component: Consent,
  errorComponent: ({ error }) => (
    <AuthLayout title="Authorization failed" subtitle="Emma Mold Inspection Services">
      <p className="mt-4 text-sm text-muted-foreground">
        Could not load this authorization request: {String((error as Error)?.message ?? error)}
      </p>
    </AuthLayout>
  ),
});

function Consent() {
  const details = Route.useLoaderData();
  const { authorization_id } = Route.useSearch();
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const clientName = details?.client?.name ?? "an application";

  async function decide(approve: boolean) {
    setBusy(true);
    setError(null);
    const { data, error: err } = approve
      ? await supabase.auth.oauth.approveAuthorization(authorization_id)
      : await supabase.auth.oauth.denyAuthorization(authorization_id);
    if (err) {
      setBusy(false);
      setError(err.message);
      return;
    }
    const target = redirectTarget(data);
    if (!target) {
      setBusy(false);
      setError("No redirect returned by the authorization server.");
      return;
    }
    window.location.href = target;
  }

  return (
    <AuthLayout title={`Connect ${clientName}`} subtitle="Emma Mold Inspection Services">
      <p className="mt-4 text-sm text-muted-foreground">
        {clientName} is asking to use Emma Mold Inspection Services as you. It will be able to read your mold scans,
        bookings and notifications, and book inspections on your behalf.
      </p>
      {error ? (
        <p role="alert" className="mt-3 rounded-xl bg-destructive/10 p-3 text-xs text-destructive">
          {error}
        </p>
      ) : null}
      <div className="mt-6 space-y-2">
        <button disabled={busy} className={submitClass} onClick={() => decide(true)}>
          {busy ? "Please wait…" : "Approve"}
        </button>
        <button
          disabled={busy}
          onClick={() => decide(false)}
          className="w-full rounded-xl border border-border bg-card px-4 py-3 text-sm font-semibold"
        >
          Deny
        </button>
      </div>
    </AuthLayout>
  );
}
