import { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import Markdown from "react-markdown";
import remarkGfm from "remark-gfm";
import {
  applyFixToBranch,
  cancelTicket,
  deleteWorktreeCmd,
  getTicketResult,
  getWorktreeDiff,
  listLocalBranchesForWorktree,
  retryTicket,
} from "../../lib/api";
import { getErrorMessage } from "../../lib/errors";
import {
  buildTicketResourceLink,
  DEFAULT_TICKET_RESOURCE_CONFIG,
  fetchTicketResourceConfig,
  type TicketResourceConfig,
} from "../../lib/ticketResource";
import type { ProcessedTicket, Worktree } from "../../lib/types";
import ConfirmModal from "../ui/ConfirmModal";
import TicketStatusBadge from "../ui/TicketStatusBadge";
import {
  buttonClass,
  cardContentClass,
  inputClass,
  noticeClass,
  pageClass,
  pageTitleClass,
} from "../ui/primitives";

function DiffViewer({ diff }: { diff: string }) {
  if (!diff) {
    return <div className="py-4 text-center text-sm text-gray-400">No changes detected.</div>;
  }

  const lines = diff.split("\n");
  return (
    <pre className="max-h-[600px] overflow-auto rounded-lg bg-gray-900 p-4 font-mono text-xs text-gray-100">
      {lines.map((line, i) => {
        let cls = "";
        if (line.startsWith("+++") || line.startsWith("---")) cls = "text-gray-400";
        else if (line.startsWith("+")) cls = "bg-green-900/20 text-green-400";
        else if (line.startsWith("-")) cls = "bg-red-900/20 text-red-400";
        else if (line.startsWith("@@")) cls = "text-blue-400";
        else if (line.startsWith("diff ")) cls = "font-bold text-yellow-400";
        return (
          <div key={i} className={cls}>
            {line}
          </div>
        );
      })}
    </pre>
  );
}

export default function TicketDetail() {
  const { ticketId } = useParams();
  const navigate = useNavigate();
  const [ticket, setTicket] = useState<ProcessedTicket | null>(null);
  const [resourceConfig, setResourceConfig] = useState<TicketResourceConfig>(
    DEFAULT_TICKET_RESOURCE_CONFIG
  );
  const [worktree, setWorktree] = useState<Worktree | null>(null);
  const [diff, setDiff] = useState<string | null>(null);
  const [targetBranch, setTargetBranch] = useState("");
  const [availableBranches, setAvailableBranches] = useState<string[]>([]);
  const [branchInputMode, setBranchInputMode] = useState<"select" | "manual">("select");
  const [branchesLoadedForWorktreeId, setBranchesLoadedForWorktreeId] = useState<string | null>(null);
  const [branchesLoading, setBranchesLoading] = useState(false);
  const [branchesError, setBranchesError] = useState("");
  const [diffLoading, setDiffLoading] = useState(false);
  const [diffError, setDiffError] = useState("");
  const [tab, setTab] = useState<"info" | "analyst" | "developer" | "diff">("info");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [isDeleteWorktreeModalOpen, setIsDeleteWorktreeModalOpen] = useState(false);

  async function loadBranchOptions(worktreeId: string) {
    setBranchesLoading(true);
    setBranchesError("");
    try {
      const branches = await listLocalBranchesForWorktree(worktreeId);
      setAvailableBranches(branches);

      if (branches.length > 0) {
        setBranchInputMode("select");
        setTargetBranch((prev) => {
          const trimmedPrev = prev.trim();
          if (trimmedPrev && branches.includes(trimmedPrev)) return trimmedPrev;
          return branches[0];
        });
      } else {
        setBranchInputMode("manual");
      }
    } catch (err) {
      setAvailableBranches([]);
      setBranchInputMode("manual");
      setBranchesError(getErrorMessage(err));
    } finally {
      setBranchesLoading(false);
    }
  }

  async function loadData() {
    if (!ticketId) return;
    setError("");
    try {
      const result = await getTicketResult(ticketId);
      setTicket(result.ticket);
      try {
        const config = await fetchTicketResourceConfig(result.ticket.project_id);
        setResourceConfig(config);
      } catch {
        setResourceConfig(DEFAULT_TICKET_RESOURCE_CONFIG);
      }
      setWorktree(result.worktree);
      setTab("info");
      setDiff(null);
      setDiffError("");
      setDiffLoading(false);
      setAvailableBranches([]);
      setBranchInputMode("select");
      setTargetBranch("");
      setBranchesError("");
      setBranchesLoading(false);
      setBranchesLoadedForWorktreeId(null);

      if (result.worktree && result.worktree.status === "Active") {
        return;
      }
    } catch (err) {
      setError(getErrorMessage(err));
    }
  }

  useEffect(() => {
    void loadData();
  }, [ticketId]);

  useEffect(() => {
    if (tab !== "info") return;
    if (!worktree || worktree.status !== "Active") return;
    if (branchesLoading) return;
    if (branchesLoadedForWorktreeId === worktree.id) return;

    let cancelled = false;

    void (async () => {
      await loadBranchOptions(worktree.id);
      if (!cancelled) {
        setBranchesLoadedForWorktreeId(worktree.id);
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [tab, worktree?.id, worktree?.status, branchesLoadedForWorktreeId]);

  useEffect(() => {
    if (tab !== "diff") return;
    if (!worktree || worktree.status !== "Active") return;
    if (diff !== null || diffLoading) return;

    let cancelled = false;
    setDiffLoading(true);
    setDiffError("");

    void getWorktreeDiff(worktree.id)
      .then((value) => {
        if (!cancelled) {
          setDiff(value);
        }
      })
      .catch((err) => {
        if (!cancelled) {
          setDiff("");
          setDiffError(getErrorMessage(err));
        }
      })
      .finally(() => {
        if (!cancelled) {
          setDiffLoading(false);
        }
      });

    return () => {
      cancelled = true;
    };
  }, [tab, worktree?.id, worktree?.status, diff]);

  async function handleRetry() {
    if (!ticketId) return;
    setLoading(true);
    try {
      await retryTicket(ticketId);
      await loadData();
    } catch (err) {
      setError(getErrorMessage(err));
    }
    setLoading(false);
  }

  async function handleCancel() {
    if (!ticketId) return;
    setLoading(true);
    try {
      await cancelTicket(ticketId);
      await loadData();
    } catch (err) {
      setError(getErrorMessage(err));
    }
    setLoading(false);
  }

  async function handleApplyFix() {
    if (!worktree) return;
    const normalizedTargetBranch = targetBranch.trim();

    if (!normalizedTargetBranch) {
      setError("Veuillez sélectionner ou saisir une branche cible.");
      return;
    }
    if (
      availableBranches.length > 0 &&
      !availableBranches.includes(normalizedTargetBranch)
    ) {
      setError(
        `La branche cible "${normalizedTargetBranch}" n'existe pas localement.`
      );
      return;
    }

    setLoading(true);
    setError("");
    try {
      await applyFixToBranch(worktree.id, normalizedTargetBranch);
      await loadData();
    } catch (err) {
      setError(getErrorMessage(err));
    }
    setLoading(false);
  }

  async function handleDeleteWorktree() {
    if (!worktree) return;
    setIsDeleteWorktreeModalOpen(false);
    setLoading(true);
    try {
      await deleteWorktreeCmd(worktree.id);
      setWorktree(null);
      setDiff(null);
      setAvailableBranches([]);
      setTargetBranch("");
      setBranchInputMode("select");
      setBranchesError("");
      setBranchesLoading(false);
    } catch (err) {
      setError(getErrorMessage(err));
    }
    setLoading(false);
  }

  if (!ticket) {
    return <div className="p-8 text-gray-400">Loading...</div>;
  }

  const tabs = [
    { key: "info" as const, label: "Info" },
    {
      key: "analyst" as const,
      label: "Analyst Report",
      disabled: !ticket.analyst_report,
    },
    {
      key: "developer" as const,
      label: "Developer Report",
      disabled: !ticket.developer_report,
    },
    {
      key: "diff" as const,
      label: "Diff",
      disabled: !worktree || worktree.status !== "Active",
    },
  ];
  const sourceLink = buildTicketResourceLink(ticket, resourceConfig);

  return (
    <div className={pageClass}>
      <div className="mb-6 flex items-center justify-between">
        <div>
          <button
            onClick={() => navigate(`/projects/${ticket.project_id}/tickets`)}
            className={buttonClass({ variant: "ghost", size: "xs" })}
          >
            Back
          </button>
          <h2 className={`flex items-center gap-3 ${pageTitleClass}`}>
            <span className="font-mono text-base text-gray-400">#{ticket.artifact_id}</span>
            {ticket.artifact_title}
            <TicketStatusBadge status={ticket.status} />
          </h2>
        </div>
        <div className="flex gap-2">
          {(ticket.status === "Error" || ticket.status === "Done" || ticket.status === "Cancelled") && (
            <button
              onClick={handleRetry}
              disabled={loading}
              className={buttonClass({ variant: "primary", size: "sm" })}
            >
              Retry
            </button>
          )}
          {(ticket.status === "Pending" ||
            ticket.status === "Analyzing" ||
            ticket.status === "Developing") && (
            <button
              onClick={handleCancel}
              disabled={loading}
              className={buttonClass({ variant: "dangerSoft", size: "sm" })}
            >
              Cancel
            </button>
          )}
        </div>
      </div>

      {error && (
        <div className={`mb-4 ${noticeClass("error")}`}>{error}</div>
      )}

      <div className="mb-6 flex gap-1 border-b border-gray-200">
        {tabs.map((t) => (
          <button
            key={t.key}
            onClick={() => setTab(t.key)}
            disabled={t.disabled}
            className={`-mb-px border-b-2 px-4 py-2 text-sm font-medium transition-colors ${
              tab === t.key
                ? "border-blue-600 text-blue-600"
                : t.disabled
                ? "cursor-not-allowed border-transparent text-gray-300"
                : "border-transparent text-gray-500 hover:text-gray-700"
            }`}
          >
            {t.label}
          </button>
        ))}
      </div>

      {tab === "info" && (
        <div className="space-y-4">
          <div className={`space-y-3 ${cardContentClass}`}>
            <div>
              <span className="text-sm text-gray-500">Status:</span>
              <span className="ml-2 text-sm">{ticket.status}</span>
            </div>
            <div>
              <span className="text-sm text-gray-500">Source:</span>
              <span className="ml-2 text-sm uppercase">{ticket.source}</span>
            </div>
            {sourceLink && (
              <div>
                <span className="text-sm text-gray-500">Resource:</span>
                <a
                  href={sourceLink.href}
                  target="_blank"
                  rel="noreferrer"
                  className="ml-2 text-sm text-blue-600 hover:underline"
                >
                  {sourceLink.label}
                </a>
              </div>
            )}
            {ticket.source_ref && ticket.source_ref !== sourceLink?.href && (
              <div>
                <span className="text-sm text-gray-500">Source ref:</span>
                <span className="ml-2 break-all font-mono text-sm">{ticket.source_ref}</span>
              </div>
            )}
            <div>
              <span className="text-sm text-gray-500">Detected:</span>
              <span className="ml-2 text-sm">{new Date(ticket.detected_at).toLocaleString()}</span>
            </div>
            {ticket.processed_at && (
              <div>
                <span className="text-sm text-gray-500">Processed:</span>
                <span className="ml-2 text-sm">{new Date(ticket.processed_at).toLocaleString()}</span>
              </div>
            )}
            {worktree && (
              <div>
                <span className="text-sm text-gray-500">Worktree:</span>
                <span className="ml-2 font-mono text-sm">{worktree.branch_name}</span>
                <span
                  className={`ml-2 rounded-full px-2 py-0.5 text-xs ${
                    worktree.status === "Active"
                      ? "bg-green-100 text-green-700"
                      : worktree.status === "Merged"
                      ? "bg-blue-100 text-blue-700"
                      : "bg-gray-100 text-gray-500"
                  }`}
                >
                  {worktree.status}
                </span>
              </div>
            )}
          </div>

          {worktree && worktree.status === "Active" && (
            <div className={cardContentClass}>
              <h3 className="mb-3 text-sm font-semibold">Worktree Actions</h3>
              <div className="mb-2 flex items-center justify-between">
                <p className="text-xs text-gray-500">Target branch</p>
                {availableBranches.length > 0 && (
                  <button
                    type="button"
                    onClick={() =>
                      setBranchInputMode((mode) => (mode === "select" ? "manual" : "select"))
                    }
                    className={buttonClass({ variant: "ghost", size: "xs" })}
                  >
                    {branchInputMode === "select"
                      ? "Use manual input"
                      : "Choose existing branch"}
                  </button>
                )}
              </div>

              <div className="mb-3 flex items-center gap-2">
                {branchInputMode === "select" && availableBranches.length > 0 ? (
                  <select
                    value={targetBranch}
                    onChange={(e) => setTargetBranch(e.target.value)}
                    className={`flex-1 bg-white ${inputClass}`}
                  >
                    {availableBranches.map((branch) => (
                      <option key={branch} value={branch}>
                        {branch}
                      </option>
                    ))}
                  </select>
                ) : (
                  <input
                    type="text"
                    placeholder="Target branch (e.g. feature/login)"
                    value={targetBranch}
                    onChange={(e) => setTargetBranch(e.target.value)}
                    className={`flex-1 ${inputClass}`}
                  />
                )}
                <button
                  onClick={handleApplyFix}
                  disabled={loading || branchesLoading || !targetBranch.trim()}
                  className={buttonClass({ variant: "success", size: "sm" })}
                >
                  Apply fix
                </button>
              </div>
              {branchesLoading && <p className="mb-3 text-xs text-gray-500">Loading local branches...</p>}
              {!branchesLoading && branchesError && (
                <p className="mb-3 text-xs text-amber-700">
                  Could not preload branches. Manual input is still available.
                </p>
              )}
              {!branchesLoading &&
                !branchesError &&
                availableBranches.length === 0 &&
                branchInputMode === "manual" && (
                  <p className="mb-3 text-xs text-gray-500">
                    No local branches detected. Enter the target branch manually.
                  </p>
                )}
              <button
                onClick={() => setIsDeleteWorktreeModalOpen(true)}
                disabled={loading}
                className={buttonClass({ variant: "dangerGhost", size: "xs" })}
              >
                Delete worktree
              </button>
            </div>
          )}

          {worktree && worktree.status === "Merged" && (
            <div className={noticeClass("info")}>
              Fix applied to branch: {worktree.merged_into}
            </div>
          )}
        </div>
      )}

      {tab === "analyst" && ticket.analyst_report && (
        <div className="prose prose-sm max-w-none rounded-lg border border-gray-200 bg-white p-6">
          <Markdown remarkPlugins={[remarkGfm]}>{ticket.analyst_report}</Markdown>
        </div>
      )}

      {tab === "developer" && ticket.developer_report && (
        <div className="prose prose-sm max-w-none rounded-lg border border-gray-200 bg-white p-6">
          <Markdown remarkPlugins={[remarkGfm]}>{ticket.developer_report}</Markdown>
        </div>
      )}

      {tab === "diff" && (
        <>
          {diffLoading ? (
            <div className="p-4 text-sm text-gray-500">Loading diff...</div>
          ) : diffError ? (
            <div className={noticeClass("warning")}>
              Could not load diff: {diffError}
            </div>
          ) : (
            <DiffViewer diff={diff || ""} />
          )}
        </>
      )}

      <ConfirmModal
        isOpen={isDeleteWorktreeModalOpen}
        confirmDisabled={loading}
        onCancel={() => setIsDeleteWorktreeModalOpen(false)}
        onConfirm={() => void handleDeleteWorktree()}
      />
    </div>
  );
}
