import { useEffect, useState } from "react";
import { useBackLayer } from "../../app/useBackLayer.js";
import { useExitTransition } from "../../app/useExitTransition.js";
import { useI18n } from "../../shared/I18nProvider.jsx";
import { CloseIcon } from "../../shared/ActionIcons.jsx";
import { translate } from "../../shared/i18n.js";

const english = (key, values) => translate("en", key, values);

export function summarizeChangePath(path) {
  const parts = String(path ?? "").split(/[\\/]+/).filter(Boolean);
  const filename = parts.at(-1) ?? "";
  const folders = parts.slice(0, -1);
  const directory = folders.length > 2 ? `.../${folders.slice(-2).join("/")}/` : folders.length > 0 ? `${folders.join("/")}/` : "";
  const extensionStart = filename.lastIndexOf(".");
  const hasExtension = extensionStart > 0;
  return { directory, basename: hasExtension ? filename.slice(0, extensionStart) : filename, extension: hasExtension ? filename.slice(extensionStart) : "" };
}

export function diffUnavailableMessage(reason, t = english) {
  return reason ? t(`changes.unavailable.${reason}`) : "";
}

function DiffDisclosure({ diff, t }) {
  const [expanded, setExpanded] = useState(true);
  const pathSummary = summarizeChangePath(diff.path);
  const unavailableMessage = diffUnavailableMessage(diff.unavailableReason, t);
  return <details className="change-sheet-diff" open={expanded} onToggle={(event) => setExpanded(event.currentTarget.open)}>
    <summary><span className="change-file-name" title={diff.path}><span className="change-file-directory">{pathSummary.directory}</span><span className="change-file-basename">{pathSummary.basename}</span><span className="change-file-extension">{pathSummary.extension}</span></span><span className="change-file-stats" aria-label={`${diff.additions ?? 0} additions and ${diff.deletions ?? 0} deletions`}><span className="change-file-additions">+{diff.additions ?? 0}</span><span className="change-file-deletions">-{diff.deletions ?? 0}</span></span></summary>
    {diff.error && <p className="change-sheet-state error">{t("changes.diffLoadFailed")}</p>}
    {unavailableMessage && <p>{unavailableMessage}</p>}
    {!diff.error && !diff.unavailableReason && <pre className="diff-code">{diff.lines.map((line) => line.kind === "fold" ? <span className="diff-fold" key={line.id}>{line.text}</span> : <span className={`diff-line ${line.kind}`} key={line.id}><span className="diff-line-number">{line.lineNumber ?? ""}</span><span className="diff-line-text">{line.text}</span></span>)}</pre>}
  </details>;
}

export function ChangeDiffSheet({ open, files, diffs, pending, error, onClose }) {
  const { t } = useI18n();
  const motion = useExitTransition(onClose, 220);
  const closeSheet = useBackLayer(open, motion.startExit, "change-sheet");
  useEffect(() => {
    if (!open) return undefined;
    const closeOnEscape = (event) => { if (event.key === "Escape") closeSheet(); };
    globalThis.addEventListener?.("keydown", closeOnEscape);
    return () => globalThis.removeEventListener?.("keydown", closeOnEscape);
  }, [closeSheet, open]);
  if (!open) return null;
  return <div className={`change-sheet-backdrop${motion.exiting ? " change-sheet-backdrop--exit" : ""}`} onClick={closeSheet}><section className={`change-sheet${motion.exiting ? " change-sheet--exit" : ""}`} role="dialog" aria-modal="true" aria-label={t("changes.title")} onClick={(event) => event.stopPropagation()}><div className="change-sheet-handle" aria-hidden="true" /><header><strong>{t("activity.filesChanged", { count: files.length })}</strong><button className="change-sheet-close" type="button" aria-label={t("changes.close")} onClick={closeSheet}><CloseIcon /></button></header>{pending === "diffs" && <p className="change-sheet-state">{t("changes.loadingDiffs")}</p>}{error && <p className="change-sheet-state error" role="alert">{t("changes.diffLoadFailed")}</p>}<div className="change-sheet-diffs">{diffs.map((diff, index) => <DiffDisclosure diff={diff} t={t} key={`${diff.path}-${index}`} />)}</div></section></div>;
}
