"use client";

import { FormEvent, useState } from "react";
import { KeyRound, Plus, X } from "lucide-react";
import { type McpConnection, useDemoStore } from "@/components/demo-store";
import { PageTitle } from "@/components/page-title";
import { StatusBadge } from "@/components/status-badge";

function ConnectionDialog({ close }: { close: () => void }) {
  const { addConnection, sites } = useDemoStore();
  function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const form = new FormData(event.currentTarget);
    const connection: McpConnection = { id: crypto.randomUUID(), name: String(form.get("name")).trim(), clientType: String(form.get("clientType")) as McpConnection["clientType"], permissionProfile: String(form.get("permissionProfile")) as McpConnection["permissionProfile"], requiresApproval: form.get("approval") === "on", siteScope: form.get("siteScope") === "all" ? "All enrolled sites" : `${sites.length} selected site${sites.length === 1 ? "" : "s"}`, createdAt: new Date().toLocaleString() };
    addConnection(connection);
    close();
  }
  return <div className="dialog-backdrop" role="presentation"><section className="dialog" role="dialog" aria-modal="true" aria-labelledby="mcp-dialog-title"><header><div><h2 id="mcp-dialog-title">Create MCP connection</h2><p>Save the access policy. A deployable MCP endpoint comes in the next backend milestone.</p></div><button className="icon-button" aria-label="Close" onClick={close}><X size={18} /></button></header><form onSubmit={submit}><div className="dialog-body"><label className="field"><span>Connection name</span><input name="name" required placeholder="Daniel - ChatGPT" /></label><label className="field"><span>Client type</span><select name="clientType"><option>ChatGPT</option><option>Claude</option><option>Custom</option></select></label><label className="field"><span>Site access</span><select name="siteScope"><option value="all">All enrolled sites</option><option value="selected">Selected sites</option></select></label><label className="field"><span>Permission profile</span><select name="permissionProfile" defaultValue="Standard"><option>Read-only</option><option>Standard</option><option>Custom</option></select></label><label className="check-field"><input name="approval" type="checkbox" defaultChecked /><span><strong>Require approval for writes</strong><small>Recommended default for all production sites.</small></span></label></div><footer><button className="button" type="button" onClick={close}>Cancel</button><button className="button button-primary" type="submit"><KeyRound size={16} /> Save connection policy</button></footer></form></section></div>;
}

export default function McpAccessPage() {
  const { connections } = useDemoStore();
  const [showCreate, setShowCreate] = useState(false);
  return <><PageTitle title="MCP Access" description="Define which AI clients may operate which enrolled WordPress sites." action={<button className="button button-primary" onClick={() => setShowCreate(true)}><Plus size={16} /> Create connection</button>} />
    {connections.length === 0 ? <section className="empty-panel"><KeyRound size={30} /><h2>No MCP connections configured</h2><p>Create a connection policy now. The hosted MCP endpoint is added after the SaaS is deployed.</p><button className="button button-primary" onClick={() => setShowCreate(true)}><Plus size={16} /> Create connection</button></section> : <section className="panel data-table-wrap"><table><thead><tr><th>Connection</th><th>Client</th><th>Permissions</th><th>Allowed sites</th><th>Write approval</th><th>Status</th></tr></thead><tbody>{connections.map((connection) => <tr key={connection.id}><td className="cell-strong">{connection.name}<small className="table-sub">Created {connection.createdAt}</small></td><td className="muted">{connection.clientType}</td><td><StatusBadge tone={connection.permissionProfile === "Standard" ? "accent" : "neutral"}>{connection.permissionProfile}</StatusBadge></td><td className="muted">{connection.siteScope}</td><td className="muted">{connection.requiresApproval ? "Required" : "Not required"}</td><td><StatusBadge tone="warning">Local policy only</StatusBadge></td></tr>)}</tbody></table></section>}
    {showCreate && <ConnectionDialog close={() => setShowCreate(false)} />}
  </>;
}
