"use client";

import { useState } from "react";
import { Button } from "@/components/ui";
import { Field, inputClass } from "@/components/ui/form";
import { Modal } from "@/components/features/library/modal";
import { StatusLine, useRun } from "@/components/features/accounts/use-run";
import { createIntegrationAction, updateIntegrationAction } from "@/lib/actions/integrations";
import { ANALYTICS_INFO, ANALYTICS_PROVIDERS, INTEGRATION_TYPES, SOCIAL_INFO, SOCIAL_PLATFORMS, TYPE_INFO, WEBHOOK_EVENTS, WEBHOOK_EVENT_LABELS, type IntegrationType } from "@/lib/integrations/schema";
import type { IntegrationRow } from "@/lib/services/integrations";

type Draft = Record<string, unknown> & { type: IntegrationType; name: string };

function initial(type: IntegrationType, row?: IntegrationRow): Draft {
  const c = row?.config ?? {};
  switch (type) {
    case "webhook": return { type, name: row?.name ?? "", url: String(c.url ?? ""), events: Array.isArray(c.events) ? c.events : ["form.submitted"], secret: "" };
    case "smtp": return { type, name: row?.name ?? "", host: String(c.host ?? ""), port: Number(c.port ?? 587), secure: Boolean(c.secure), username: String(c.username ?? ""), password: "", fromEmail: String(c.fromEmail ?? ""), fromName: String(c.fromName ?? "") };
    case "analytics": return { type, name: row?.name ?? "", provider: String(c.provider ?? "ga4"), trackingId: String(c.trackingId ?? "") };
    case "social": return { type, name: row?.name ?? "", links: { ...((c.links as object) ?? {}) } };
  }
}

/** Add or edit one integration. `row` set = edit (type can't change). */
export function IntegrationDialog({ siteId, open, onClose, row, policies }: { siteId: string; open: boolean; onClose: () => void; row?: IntegrationRow; policies: Record<IntegrationType, boolean> }) {
  const [type, setType] = useState<IntegrationType>(row?.type ?? "webhook");
  const [d, setD] = useState<Draft>(() => initial(row?.type ?? "webhook", row));
  const [secret, setSecret] = useState<string | null>(null);
  const { pending, msg, errors, run } = useRun();
  const set = (k: string, v: unknown) => setD((x) => ({ ...x, [k]: v }));
  const pick = (t: IntegrationType) => { setType(t); setD(initial(t)); };
  const text = (k: string, label: string, extra: { type?: string; help?: string; placeholder?: string; autoComplete?: string } = {}) => (
    <Field id={`i-${k}`} label={label} help={extra.help} error={errors[k]}>
      <input id={`i-${k}`} type={extra.type ?? "text"} value={String(d[k] ?? "")} placeholder={extra.placeholder} autoComplete={extra.autoComplete ?? "off"} aria-invalid={Boolean(errors[k])} onChange={(e) => set(k, e.target.value)} className={inputClass} />
    </Field>
  );
  const submit = () => {
    let shown = false;
    run(async () => {
      const r = row ? await updateIntegrationAction(siteId, row.id, d) : await createIntegrationAction(siteId, d);
      if (r.ok && !row && r.data?.secret) { shown = true; setSecret(r.data.secret); }
      return r;
    }, () => { if (!shown) onClose(); });
  };
  const close = () => { setSecret(null); onClose(); };
  const needs = policies[type];

  return (
    <Modal open={open} onClose={close} title={row ? `Edit ${row.name}` : "Add integration"}>
      {secret ? (
        <div className="space-y-3">
          <p className="text-sm">Integration added. Copy the signing secret now; it is not shown again. Use it to check the <code>x-webhook-signature</code> header.</p>
          <code className="block break-all rounded-md border border-border bg-muted p-3 text-xs">{secret}</code>
          <div className="flex justify-end"><Button onClick={close}>Done</Button></div>
        </div>
      ) : (
        <form onSubmit={(e) => { e.preventDefault(); submit(); }} className="space-y-4">
          {!row ? (
            <Field id="i-type" label="Type">
              <select id="i-type" value={type} onChange={(e) => pick(e.target.value as IntegrationType)} className={inputClass}>{INTEGRATION_TYPES.map((t) => <option key={t} value={t}>{TYPE_INFO[t].label}</option>)}</select>
            </Field>
          ) : null}
          <p className="text-xs text-muted-foreground">{TYPE_INFO[type].description}{needs ? " A platform administrator must approve it before it starts working." : ""}</p>
          {text("name", "Name", { placeholder: "e.g. CRM sync" })}
          {type === "webhook" ? (
            <>
              {text("url", "Endpoint URL", { type: "url", placeholder: "https://example.com/hooks/cms" })}
              <fieldset className="space-y-1"><legend className="text-xs font-medium">Send a message when</legend>
                {WEBHOOK_EVENTS.map((ev) => {
                  const list = (d.events as string[]) ?? [];
                  return <label key={ev} className="flex items-center gap-2 text-sm"><input type="checkbox" checked={list.includes(ev)} onChange={(e) => set("events", e.target.checked ? [...list, ev] : list.filter((x) => x !== ev))} />{WEBHOOK_EVENT_LABELS[ev]}</label>;
                })}
                {errors.events ? <p role="alert" className="text-xs text-danger">{errors.events}</p> : null}
              </fieldset>
              {text("secret", "Signing secret", { help: row ? "Leave blank to keep the current secret." : "Leave blank to generate one.", autoComplete: "new-password" })}
            </>
          ) : null}
          {type === "smtp" ? (
            <>
              <div className="grid gap-3 sm:grid-cols-2">{text("host", "Mail server", { placeholder: "smtp.example.com" })}{text("port", "Port", { type: "number" })}</div>
              <label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={Boolean(d.secure)} onChange={(e) => set("secure", e.target.checked)} />Use SSL/TLS from the start (usually port 465)</label>
              <div className="grid gap-3 sm:grid-cols-2">{text("username", "Username")}{text("password", "Password", { type: "password", autoComplete: "new-password", help: row ? "Leave blank to keep the current password." : undefined })}</div>
              <div className="grid gap-3 sm:grid-cols-2">{text("fromEmail", "Sender email", { type: "email" })}{text("fromName", "Sender name")}</div>
            </>
          ) : null}
          {type === "analytics" ? (
            <>
              <Field id="i-provider" label="Provider"><select id="i-provider" value={String(d.provider)} onChange={(e) => set("provider", e.target.value)} className={inputClass}>{ANALYTICS_PROVIDERS.map((p) => <option key={p} value={p}>{ANALYTICS_INFO[p].label}</option>)}</select></Field>
              {text("trackingId", ANALYTICS_INFO[d.provider as keyof typeof ANALYTICS_INFO]?.idLabel ?? "ID", { placeholder: ANALYTICS_INFO[d.provider as keyof typeof ANALYTICS_INFO]?.placeholder, help: ANALYTICS_INFO[d.provider as keyof typeof ANALYTICS_INFO]?.hint })}
            </>
          ) : null}
          {type === "social" ? (
            <fieldset className="space-y-3"><legend className="text-xs font-medium">Profile links</legend>
              {errors.links ? <p role="alert" className="text-xs text-danger">{errors.links}</p> : null}
              {SOCIAL_PLATFORMS.map((p) => {
                const links = (d.links as Record<string, string>) ?? {};
                return (
                  <Field key={p} id={`i-link-${p}`} label={SOCIAL_INFO[p].label} error={errors[`links.${p}`]}>
                    <input id={`i-link-${p}`} type="url" value={links[p] ?? ""} placeholder={`https://${SOCIAL_INFO[p].hosts[0]}/…`} onChange={(e) => set("links", { ...links, [p]: e.target.value })} className={inputClass} />
                  </Field>
                );
              })}
            </fieldset>
          ) : null}
          <div className="flex items-center justify-end gap-3"><StatusLine msg={msg} /><Button variant="ghost" onClick={close}>Cancel</Button><Button type="submit" disabled={pending}>{pending ? "Saving…" : row ? "Save" : "Add integration"}</Button></div>
        </form>
      )}
    </Modal>
  );
}
