"use client";

import { buttonClass } from "@/components/ui/button";
import { useState } from "react";
import { Button, Card } from "@/components/ui";
import { Field, inputClass } from "@/components/ui/form";
import type { SiteSettings } from "@/lib/site-settings";
import { SaveBar, useSection } from "./section-kit";

const NOTICE: Record<string, { ok: boolean; text: string }> = {
  ok: { ok: true, text: "Instagram account linked." },
  denied: { ok: false, text: "Instagram access was not granted." },
  failed: { ok: false, text: "Instagram could not be linked. Check the app id, app secret and redirect address, then try again." },
  setup: { ok: false, text: "Save the app id and secret before authorising." },
};

/** ShowOff "Instagram Integration": link the website to an Instagram account through Instagram Login. */
export function InstagramForm({ siteId, instagram, secretSet, connected, redirectUri, notice }: { siteId: string; instagram: SiteSettings["instagram"]; secretSet: boolean; connected: boolean; redirectUri: string; notice?: string }) {
  const cred = useSection(siteId);
  const disc = useSection(siteId);
  const [appId, setAppId] = useState(instagram.appId);
  const [secret, setSecret] = useState("");
  const [isConnected, setConnected] = useState(connected);
  const flash = notice ? NOTICE[notice] : undefined;
  const fmt = (iso: string) => (iso ? new Date(iso).toISOString().slice(0, 10) : "");

  return (
    <div className="space-y-4">
      {flash ? <p role="status" className={`rounded-md border border-border px-3 py-2 text-sm ${flash.ok ? "text-success" : "text-danger"}`}>{flash.text}</p> : null}
      <Card className="space-y-4 p-4">
        <div>
          <h2 className="text-sm font-semibold">Instagram integration</h2>
          <p className="text-xs text-muted-foreground">To link your Instagram account, enter the app details from your Meta app (Instagram API with Instagram Login), then click Authorize. The account must be a professional (business or creator) account.</p>
        </div>
        <div className="grid gap-4 sm:grid-cols-2">
          <Field id="ig-app" label="Instagram app id" error={cred.errors["appId"]}><input id="ig-app" inputMode="numeric" className={inputClass} maxLength={24} value={appId} onChange={(e) => setAppId(e.target.value)} /></Field>
          <Field id="ig-secret" label="Instagram app secret" help={secretSet ? "A secret is saved. Leave blank to keep it." : "Stored encrypted and never shown again."} error={cred.errors["appSecret"]}>
            <input id="ig-secret" type="password" autoComplete="off" className={inputClass} maxLength={100} value={secret} onChange={(e) => setSecret(e.target.value)} aria-describedby="ig-secret-help" />
          </Field>
        </div>
        <Field id="ig-redirect" label="Redirect address to add in your Meta app" help="Copy this into Valid OAuth Redirect URIs.">
          <input id="ig-redirect" readOnly className={`${inputClass} font-mono`} value={redirectUri} onFocus={(e) => e.currentTarget.select()} aria-describedby="ig-redirect-help" />
        </Field>
        <SaveBar pending={cred.pending} msg={cred.msg} label="Save app details" onSave={() => cred.save("instagram", { appId, ...(secret ? { appSecret: secret } : {}) }, () => { setSecret(""); setConnected(false); })} />
      </Card>
      <Card className="space-y-3 p-4">
        <h2 className="text-sm font-semibold">Connection</h2>
        {isConnected ? (
          <p className="text-sm">Linked to <strong>@{instagram.username || "your account"}</strong>{instagram.connectedAt ? `, since ${fmt(instagram.connectedAt)}` : ""}{instagram.expiresAt ? `. Access runs out on ${fmt(instagram.expiresAt)}; authorise again before then to keep it linked.` : "."}</p>
        ) : <p className="text-sm text-muted-foreground">Not linked yet.</p>}
        <div className="flex flex-wrap items-center gap-3">
          {secretSet && instagram.appId ? <a href={`/api/instagram/authorize?siteId=${encodeURIComponent(siteId)}`} className={buttonClass("primary")}>{isConnected ? "Authorize again" : "Authorize"}</a> : <Button disabled>Authorize</Button>}
          {isConnected ? <Button variant="secondary" disabled={disc.pending} onClick={() => disc.save("instagramDisconnect", {}, () => setConnected(false))}>Disconnect</Button> : null}
          <p role="status" aria-live="polite" className={disc.msg ? (disc.msg.ok ? "text-sm text-success" : "text-sm text-danger") : "sr-only"}>{disc.msg?.text}</p>
        </div>
      </Card>
    </div>
  );
}
