import { useState, useEffect } from "react";
import { invoke } from "@tauri-apps/api/core";
import { openUrl } from "@tauri-apps/plugin-opener";
import { QuestStep, RichSegment } from "../types";
import { TextWithCoords } from "./TextWithCoords";

const DPLN_BASE = "https://www.dofuspourlesnoobs.com";

interface Props {
  questName: string;
  questUrl: string | null;
  profileId: string;
  onClose: () => void;
  onSelectQuest?: (quest: { name: string; url: string | null }) => void;
}

export default function QuestDetailPanel({ questName, questUrl, profileId, onClose, onSelectQuest }: Props) {
  const [steps, setSteps] = useState<QuestStep[]>([]);
  const [completedSteps, setCompletedSteps] = useState<Set<number>>(new Set());
  const [expandedSteps, setExpandedSteps] = useState<Set<number>>(new Set());
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!questUrl) {
      setError("Aucun lien disponible pour cette quête.");
      setLoading(false);
      return;
    }

    setLoading(true);
    setError(null);

    Promise.all([
      invoke<QuestStep[]>("fetch_quest_detail", { url: questUrl }),
      invoke<number[]>("get_completed_steps", { profileId, questName }),
    ]).then(([fetchedSteps, completedIndices]) => {
      setSteps(fetchedSteps);
      setCompletedSteps(new Set(completedIndices));
    }).catch(e => {
      setError(`Impossible de charger la page : ${e}`);
    }).finally(() => setLoading(false));
  }, [questUrl, questName, profileId]);

  const toggleStep = async (index: number) => {
    const isNow = await invoke<boolean>("toggle_quest_step", { profileId, questName, stepIndex: index });
    setCompletedSteps(prev => {
      const next = new Set(prev);
      if (isNow) next.add(index); else next.delete(index);
      return next;
    });
  };

  const toggleExpanded = (index: number) => {
    setExpandedSteps(prev => {
      const next = new Set(prev);
      if (next.has(index)) next.delete(index); else next.add(index);
      return next;
    });
  };

  const firstIsHeader = steps.length > 0 && steps[0].launch_position != null;
  const headerStep = firstIsHeader ? steps[0] : null;
  const actionSteps = firstIsHeader ? steps.slice(1) : steps;
  const completedCount = actionSteps.filter(s => completedSteps.has(s.index)).length;
  const pct = actionSteps.length > 0 ? Math.round((completedCount / actionSteps.length) * 100) : 0;

  return (
    <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden", minHeight: 0 }}>
      {/* Title bar */}
      <div style={{
        padding: "12px 16px", borderBottom: "1px solid #2d3748",
        background: "#161b22", flexShrink: 0,
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: "10px", marginBottom: "6px" }}>
          <button
            onClick={onClose}
            style={{
              background: "transparent", border: "1px solid #2d3748",
              borderRadius: "5px", color: "#94a3b8", cursor: "pointer",
              fontSize: "11px", padding: "3px 8px", flexShrink: 0, transition: "all 0.15s",
            }}
            onMouseEnter={e => { (e.currentTarget as HTMLElement).style.borderColor = "#f0c040"; (e.currentTarget as HTMLElement).style.color = "#f0c040"; }}
            onMouseLeave={e => { (e.currentTarget as HTMLElement).style.borderColor = "#2d3748"; (e.currentTarget as HTMLElement).style.color = "#94a3b8"; }}
          >
            ← Retour
          </button>
          <span style={{ fontSize: "13px", fontWeight: 600, color: "#e2e8f0", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
            {questName}
          </span>
        </div>

        {actionSteps.length > 0 && (
          <div>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: "11px", color: "#94a3b8", marginBottom: "4px" }}>
              <span>{completedCount}/{actionSteps.length} étapes</span>
              <span style={{ color: pct === 100 ? "#4ade80" : "#f0c040", fontWeight: 600 }}>{pct}%</span>
            </div>
            <div style={{ height: "3px", background: "#2d3748", borderRadius: "2px", overflow: "hidden" }}>
              <div style={{
                height: "100%", width: `${pct}%`,
                background: pct === 100 ? "#4ade80" : "linear-gradient(90deg, #4a9eff, #f0c040)",
                transition: "width 0.3s ease", borderRadius: "2px",
              }} />
            </div>
          </div>
        )}

        {questUrl && (
          <button
            onClick={() => openUrl(questUrl)}
            style={{
              marginTop: "6px", background: "transparent", border: "none",
              color: "#4a5568", fontSize: "10px", cursor: "pointer", padding: 0,
              textDecoration: "underline",
            }}
            onMouseEnter={e => (e.currentTarget.style.color = "#93c5fd")}
            onMouseLeave={e => (e.currentTarget.style.color = "#4a5568")}
          >
            Ouvrir sur Dofus Pour Les Noobs ↗
          </button>
        )}
      </div>

      {/* Content */}
      <div className="with-scrollbar" style={{ flex: 1, overflowY: "auto", padding: "12px 16px" }}>
        {loading && (
          <div style={{ display: "flex", alignItems: "center", justifyContent: "center", height: "120px", color: "#4a5568", fontSize: "13px" }}>
            <span style={{ animation: "spin 1s linear infinite", display: "inline-block", marginRight: "8px" }}>↻</span>
            Chargement…
          </div>
        )}

        {error && (
          <div style={{
            padding: "12px", background: "rgba(248,113,113,0.08)",
            border: "1px solid rgba(248,113,113,0.2)", borderRadius: "6px",
            color: "#f87171", fontSize: "12px",
          }}>
            {error}
          </div>
        )}

        {!loading && !error && steps.length === 0 && (
          <div style={{ color: "#4a5568", fontSize: "12px", textAlign: "center", paddingTop: "40px" }}>
            Aucune étape trouvée sur la page.
          </div>
        )}

        {!loading && headerStep && (
          <QuestHeader step={headerStep} />
        )}

        {!loading && actionSteps.map((step) => {
          const done = completedSteps.has(step.index);
          const expanded = expandedSteps.has(step.index);

          if (done) {
            const firstLine = step.text.split('\n').find(l => l.trim().length > 0) ?? step.text;
            return (
              <div key={step.index} onClick={() => toggleStep(step.index)} style={{
                marginBottom: "4px",
                padding: "6px 12px",
                border: "1px solid rgba(74,222,128,0.1)",
                borderRadius: "7px",
                background: "rgba(74,222,128,0.03)",
                opacity: 0.5,
                cursor: "pointer",
              }}>
                <div style={{ display: "flex", gap: "10px", alignItems: "center" }}>
                  <input
                    type="checkbox"
                    checked={true}
                    onChange={() => toggleStep(step.index)}
                    onClick={e => e.stopPropagation()}
                    style={{ flexShrink: 0, cursor: "pointer" }}
                  />
                  <span style={{
                    fontSize: "12px", color: "#4a5568",
                    textDecoration: "line-through",
                    overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
                    flex: 1, minWidth: 0,
                  }}>
                    {firstLine}
                  </span>
                </div>
              </div>
            );
          }

          const lines = step.text.split('\n').filter(l => l.trim().length > 0);
          const needsTruncate = lines.length > 4;

          return (
            <div key={step.index} onClick={() => toggleStep(step.index)} style={{
              marginBottom: "8px",
              background: "rgba(255,255,255,0.02)",
              border: "1px solid #2d3748",
              borderRadius: "7px", padding: "10px 12px",
              transition: "all 0.15s",
              cursor: "pointer",
            }}>
              <div style={{ display: "flex", gap: "10px", alignItems: "flex-start" }}>
                <input
                  type="checkbox"
                  checked={false}
                  onChange={() => toggleStep(step.index)}
                  onClick={e => e.stopPropagation()}
                  style={{ marginTop: "2px", flexShrink: 0, cursor: "pointer" }}
                />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{
                    fontSize: "12px", color: "#94a3b8",
                    lineHeight: 1.6, whiteSpace: "pre-wrap", wordBreak: "break-word",
                  }}>
                    {step.rich_text.length > 0 && (expanded || !needsTruncate)
                      ? <RichText segments={step.rich_text} onSelectQuest={onSelectQuest} />
                      : <TextWithCoords text={needsTruncate && !expanded ? lines.slice(0, 4).join('\n') : step.text} />
                    }
                  </div>

                  {needsTruncate && (
                    <button
                      onClick={e => { e.stopPropagation(); toggleExpanded(step.index); }}
                      style={{
                        marginTop: "4px", background: "transparent", border: "none",
                        color: "#4a9eff", fontSize: "11px", cursor: "pointer",
                        padding: 0, textDecoration: "underline",
                      }}
                    >
                      {expanded ? "Voir moins" : "Voir plus"}
                    </button>
                  )}

                  {step.images.length > 0 && (
                    <div style={{ marginTop: "8px", display: "flex", flexDirection: "column", gap: "6px" }}>
                      {step.images.map((src, j) => (
                        <img
                          key={j}
                          src={src}
                          onClick={e => { e.stopPropagation(); invoke("open_image_viewer", { imageUrl: src }); }}
                          style={{
                            maxWidth: "100%", height: "auto",
                            borderRadius: "6px", display: "block",
                            border: "1px solid #2d3748", cursor: "pointer",
                          }}
                        />
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function RichText({
  segments,
  onSelectQuest,
}: {
  segments: RichSegment[];
  onSelectQuest?: (quest: { name: string; url: string | null }) => void;
}) {
  return (
    <>
      {segments.map((seg, i) => {
        if (seg.type === "QuestLink") {
          return (
            <span
              key={i}
              onClick={e => {
                e.stopPropagation();
                onSelectQuest?.({ name: seg.text, url: DPLN_BASE + seg.href });
              }}
              style={{
                color: "#4a9eff",
                textDecoration: "underline",
                cursor: "pointer",
              }}
              onMouseEnter={e => (e.currentTarget.style.color = "#93c5fd")}
              onMouseLeave={e => (e.currentTarget.style.color = "#4a9eff")}
            >
              {seg.text}
            </span>
          );
        }
        return <TextWithCoords key={i} text={seg.text} />;
      })}
    </>
  );
}

function QuestHeader({ step }: { step: QuestStep }) {
  return (
    <div style={{
      marginBottom: "14px",
      border: "1px solid #2d3748",
      borderRadius: "8px",
      overflow: "hidden",
    }}>
      <div style={{ padding: "10px 14px", display: "flex", alignItems: "baseline", gap: "8px", fontSize: "12px" }}>
        <span style={{ fontSize: "13px", flexShrink: 0 }}>📍</span>
        <span style={{
          color: "#4a5568", fontWeight: 600, fontSize: "10px",
          textTransform: "uppercase", letterSpacing: "0.05em",
          flexShrink: 0,
        }}>
          Position
        </span>
        <span style={{ color: "#cbd5e1", lineHeight: 1.5, wordBreak: "break-word" }}>
          <TextWithCoords text={step.launch_position!} />
        </span>
      </div>

      {step.images.length > 0 && (
        <div style={{ padding: "0 14px 10px", display: "flex", flexDirection: "column", gap: "6px" }}>
          {step.images.map((src, j) => (
            <img
              key={j}
              src={src}
              onClick={() => invoke("open_image_viewer", { imageUrl: src })}
              style={{
                maxWidth: "100%", height: "auto",
                borderRadius: "6px", display: "block",
                border: "1px solid #2d3748", cursor: "pointer",
              }}
            />
          ))}
        </div>
      )}
    </div>
  );
}
