import { createContext, useContext, useEffect, useReducer, useState } from "react";
import { useI18n } from "../../shared/I18nProvider.jsx";
import { LegalSupportSection } from "../context/LegalSupportSection.jsx";
import { createReviewDemoState, reviewDemoReducer } from "./review-demo-state.js";
import "./review-demo.css";

const ReviewDemoContext = createContext(null);

export function ReviewDemoProvider({ children }) {
  const [active, setActive] = useState(false);
  const controls = { startReviewDemo: () => setActive(true), stopReviewDemo: () => setActive(false) };
  return <ReviewDemoContext.Provider value={controls}>
    {active ? <ReviewDemo onExit={controls.stopReviewDemo} /> : children}
  </ReviewDemoContext.Provider>;
}

export function useReviewDemo() {
  const context = useContext(ReviewDemoContext);
  if (!context) throw new Error("ReviewDemoProvider is required");
  return context;
}

function DemoChat({ state, dispatch }) {
  const { t } = useI18n();
  const [message, setMessage] = useState("");
  useEffect(() => {
    if (!state.responsePending) return undefined;
    const timer = setTimeout(() => dispatch({ type: "complete-response" }), 500);
    return () => clearTimeout(timer);
  }, [dispatch, state.responsePending]);

  function submit(event) {
    event.preventDefault();
    if (!message.trim()) return;
    dispatch({ type: "send", message });
    setMessage("");
  }

  return <section className="review-demo-chat" aria-label={t("reviewDemo.chat") }>
    <button className="review-demo-back" type="button" onClick={() => dispatch({ type: "navigate", mode: "chats" })}>{t("settings.back")}</button>
    <h1>{state.threads[0].title}</h1>
    <div className="review-demo-messages">
      {state.messages.map((item) => <article className={`review-demo-message ${item.role}`} key={item.id}>
        <strong>{item.role === "assistant" ? "Codex" : t("reviewDemo.you")}</strong>
        <p>{item.text}{item.status === "streaming" && <span className="review-demo-cursor" aria-label={t("reviewDemo.responding")}>▋</span>}</p>
      </article>)}
      <article className="review-demo-approval">
        <small>{t("reviewDemo.approval")}</small>
        <strong>{state.approval.title}</strong>
        <code>{state.approval.command}</code>
        {state.approval.status === "pending" ? <div>
          <button type="button" onClick={() => dispatch({ type: "decide-approval", decision: "denied" })}>{t("reviewDemo.deny")}</button>
          <button type="button" onClick={() => dispatch({ type: "decide-approval", decision: "approved" })}>{t("reviewDemo.approve")}</button>
        </div> : <p className="review-demo-decision">{t(`reviewDemo.${state.approval.status}`)}</p>}
      </article>
    </div>
    <form className="review-demo-composer" onSubmit={submit}>
      <input value={message} onChange={(event) => setMessage(event.target.value)} placeholder={t("reviewDemo.messagePlaceholder")} aria-label={t("reviewDemo.messagePlaceholder")} disabled={state.responsePending} />
      <button type="submit" disabled={!message.trim() || state.responsePending}>{t("reviewDemo.send")}</button>
    </form>
  </section>;
}

function DemoChats({ state, dispatch }) {
  const { t } = useI18n();
  return <section className="review-demo-page"><h1>{t("reviewDemo.chats")}</h1><p>{t("reviewDemo.chatsDescription")}</p><div className="review-demo-list">
    {state.threads.map((thread) => <button type="button" key={thread.id} onClick={() => dispatch({ type: "open-chat" })}><strong>{thread.title}</strong><span>{thread.preview}</span></button>)}
  </div></section>;
}

function DemoUsage({ usage }) {
  const { t } = useI18n();
  return <section className="review-demo-page"><h1>{t("reviewDemo.usage")}</h1><p>{t("reviewDemo.usageDescription")}</p><div className="review-demo-metrics">
    <article><span>{t("usage.fiveHourRemaining")}</span><strong>{usage.fiveHourRemaining}%</strong><progress max="100" value={usage.fiveHourRemaining} /></article>
    <article><span>{t("usage.weeklyRemaining")}</span><strong>{usage.weeklyRemaining}%</strong><progress max="100" value={usage.weeklyRemaining} /></article>
  </div></section>;
}

function DemoChanges({ files }) {
  const { t } = useI18n();
  return <section className="review-demo-page"><h1>{t("reviewDemo.changes")}</h1><p>{t("reviewDemo.changesDescription")}</p><div className="review-demo-files">
    {files.map((file) => <article key={file.path}><strong>{file.path}</strong><span><b>+{file.additions}</b> <i>-{file.deletions}</i></span></article>)}
  </div><pre className="review-demo-diff"><span>- status = 'connecting'</span>{"\n"}<b>+ status = 'connected'</b>{"\n"}<b>+ label = 'Sample PC'</b></pre></section>;
}

function DemoSettings({ dispatch }) {
  const { t } = useI18n();
  return <section className="review-demo-page review-demo-settings"><h1>{t("settings.title")}</h1><section><h2>{t("reviewDemo.demoData")}</h2><button type="button" onClick={() => dispatch({ type: "reset" })}>{t("reviewDemo.reset")}</button></section><LegalSupportSection /></section>;
}

export function ReviewDemo({ onExit }) {
  const { t } = useI18n();
  const [state, dispatch] = useReducer(reviewDemoReducer, undefined, createReviewDemoState);
  const page = state.mode === "chat" ? <DemoChat state={state} dispatch={dispatch} />
    : state.mode === "usage" ? <DemoUsage usage={state.usage} />
      : state.mode === "changes" ? <DemoChanges files={state.files} />
        : state.mode === "settings" ? <DemoSettings dispatch={dispatch} />
          : <DemoChats state={state} dispatch={dispatch} />;

  return <main className="review-demo-shell">
    <header className="review-demo-banner"><div><strong>{t("reviewDemo.title")}</strong><span>{t("reviewDemo.syntheticNotice")}</span></div><button type="button" onClick={onExit}>{t("reviewDemo.exit")}</button></header>
    <div className="review-demo-content">{page}</div>
    <nav className="review-demo-nav" aria-label={t("reviewDemo.navigation") }>
      {["chats", "usage", "changes", "settings"].map((mode) => <button type="button" className={state.mode === mode || (mode === "chats" && state.mode === "chat") ? "active" : ""} aria-current={state.mode === mode ? "page" : undefined} key={mode} onClick={() => dispatch({ type: "navigate", mode })}>{t(`reviewDemo.${mode}`)}</button>)}
    </nav>
  </main>;
}
