"use client";

import { useState } from "react";

interface Query {
  query: string;
  region: string;
  count: number;
}

interface AiSearchModalProps {
  onStart: (queries: Query[]) => void;
  onClose: () => void;
  searchMode?: string;
}

export function AiSearchModal({ onStart, onClose, searchMode = "custom" }: AiSearchModalProps) {
  const [description, setDescription] = useState("");
  const [loading, setLoading] = useState(false);
  const [queries, setQueries] = useState<Query[]>([]);
  const [selected, setSelected] = useState<Set<number>>(new Set());
  const [error, setError] = useState("");

  async function generate() {
    if (!description.trim() || loading) return;
    setLoading(true);
    setError("");
    setQueries([]);
    try {
      // Load history for this mode
      let history: Array<{ query: string; region: string }> = [];
      if (searchMode !== "custom") {
        try {
          const hRes = await fetch(`/api/search-history?mode=${searchMode}`);
          if (hRes.ok) history = await hRes.json() as Array<{ query: string; region: string }>;
        } catch { /* ignore */ }
      }

      const res = await fetch("/api/ai-search", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ description, searchMode, history }),
      });
      const data = await res.json() as { queries?: Query[]; error?: string };
      if (!res.ok || !data.queries) throw new Error(data.error || "Fehler");
      setQueries(data.queries);
      setSelected(new Set(data.queries.map((_, i) => i)));
    } catch (e) {
      setError(e instanceof Error ? e.message : "Unbekannter Fehler");
    } finally {
      setLoading(false);
    }
  }

  function toggle(i: number) {
    setSelected(prev => {
      const n = new Set(prev);
      if (n.has(i)) n.delete(i); else n.add(i);
      return n;
    });
  }

  function handleStart() {
    const chosen = queries.filter((_, i) => selected.has(i));
    if (!chosen.length) return;
    onStart(chosen);
  }

  return (
    <div
      style={{
        position: "fixed", inset: 0, zIndex: 50,
        display: "flex", alignItems: "center", justifyContent: "center",
        background: "rgba(0,0,0,0.6)",
      }}
      onClick={onClose}
    >
      <div
        style={{
          background: "#111118", border: "1px solid #1e1e2e", borderRadius: 14,
          padding: 28, width: "100%", maxWidth: 520,
          display: "flex", flexDirection: "column", gap: 16,
        }}
        onClick={e => e.stopPropagation()}
      >
        {/* Header */}
        <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between" }}>
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
              <span style={{ fontSize: 18 }}>✨</span>
              <h2 style={{ margin: 0, fontSize: 16, fontWeight: 500, color: "#fff" }}>
                KI-gestützte Suche
              </h2>
            </div>
            <p style={{ margin: 0, fontSize: 12, color: "#6b7280" }}>
              Beschreibe deine Zielgruppe — die KI generiert passende Suchanfragen.
            </p>
          </div>
          <button onClick={onClose} style={{ background: "none", border: "none", color: "#6b7280", cursor: "pointer", padding: 4 }}>
            <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
              <path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z"/>
            </svg>
          </button>
        </div>

        {/* Textarea */}
        <div>
          <textarea
            value={description}
            onChange={e => setDescription(e.target.value)}
            onKeyDown={e => { if (e.key === "Enter" && e.ctrlKey) generate(); }}
            placeholder="z.B. Ich suche kleine Dachdecker und Solarinstallateure in Bayern, am liebsten mit Inhaber direkt erreichbar."
            rows={4}
            style={{
              width: "100%", background: "#0d0d18", border: "1px solid #1e1e2e",
              borderRadius: 8, padding: "10px 12px", fontSize: 13, color: "#fff",
              outline: "none", resize: "vertical", fontFamily: "inherit",
              lineHeight: 1.6, boxSizing: "border-box",
            }}
            onFocus={e => { e.currentTarget.style.borderColor = "#3b82f6"; }}
            onBlur={e => { e.currentTarget.style.borderColor = "#1e1e2e"; }}
          />
          <p style={{ margin: "4px 0 0", fontSize: 11, color: "#4b5563" }}>
            Tipp: Branche, Region, Firmengröße und gewünschten Entscheidungsträger erwähnen · Strg+Enter zum Generieren
          </p>
        </div>

        {/* Generate button */}
        {queries.length === 0 && (
          <button
            onClick={generate}
            disabled={!description.trim() || loading}
            style={{
              width: "100%", padding: "11px 16px", borderRadius: 8, border: "none",
              background: !description.trim() || loading ? "#1e1e2e" : "linear-gradient(135deg, #3b82f6, #8b5cf6)",
              color: !description.trim() || loading ? "#4b5563" : "#fff",
              fontSize: 14, fontWeight: 500, cursor: !description.trim() || loading ? "not-allowed" : "pointer",
              display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
            }}
          >
            {loading ? (
              <>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ animation: "spin 1s linear infinite" }}>
                  <path d="M21 12a9 9 0 1 1-6.219-8.56"/>
                </svg>
                Suchanfragen werden generiert…
              </>
            ) : (
              <>✨ Suchanfragen generieren</>
            )}
          </button>
        )}

        {/* Error */}
        {error && (
          <p style={{ margin: 0, fontSize: 12, color: "#ef4444", background: "rgba(239,68,68,0.08)", padding: "8px 12px", borderRadius: 6, borderLeft: "3px solid #ef4444" }}>
            {error}
          </p>
        )}

        {/* Generated queries */}
        {queries.length > 0 && (
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            <p style={{ margin: 0, fontSize: 11, color: "#6b7280", textTransform: "uppercase", letterSpacing: "0.05em" }}>
              Generierte Suchanfragen — wähle aus was starten soll
            </p>
            {queries.map((q, i) => (
              <button
                key={i}
                onClick={() => toggle(i)}
                style={{
                  display: "flex", alignItems: "center", justifyContent: "space-between",
                  padding: "10px 14px", borderRadius: 8, cursor: "pointer", textAlign: "left",
                  border: selected.has(i) ? "1px solid rgba(59,130,246,0.5)" : "1px solid #1e1e2e",
                  background: selected.has(i) ? "rgba(59,130,246,0.08)" : "#0d0d18",
                  transition: "all 0.15s",
                }}
              >
                <div>
                  <span style={{ fontSize: 13, color: "#fff", fontWeight: 500 }}>{q.query}</span>
                  {q.region && (
                    <span style={{ fontSize: 12, color: "#6b7280", marginLeft: 8 }}>📍 {q.region}</span>
                  )}
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <div style={{
                    width: 16, height: 16, borderRadius: 4,
                    border: selected.has(i) ? "none" : "1px solid #2e2e3e",
                    background: selected.has(i) ? "#3b82f6" : "transparent",
                    display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
                  }}>
                    {selected.has(i) && (
                      <svg width="10" height="10" viewBox="0 0 10 10" fill="none">
                        <path d="M2 5l2.5 2.5L8 3" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                      </svg>
                    )}
                  </div>
                </div>
              </button>
            ))}

            <div style={{ display: "flex", gap: 8, marginTop: 4 }}>
              <button
                onClick={() => { setQueries([]); setSelected(new Set()); }}
                style={{
                  flex: 1, padding: "10px", borderRadius: 8, border: "1px solid #1e1e2e",
                  background: "#0d0d18", color: "#6b7280", fontSize: 13, cursor: "pointer",
                }}
              >
                Neu generieren
              </button>
              <button
                onClick={handleStart}
                disabled={selected.size === 0}
                style={{
                  flex: 2, padding: "10px", borderRadius: 8, border: "none",
                  background: selected.size > 0 ? "linear-gradient(135deg, #3b82f6, #8b5cf6)" : "#1e1e2e",
                  color: selected.size > 0 ? "#fff" : "#4b5563",
                  fontSize: 13, fontWeight: 500, cursor: selected.size > 0 ? "pointer" : "not-allowed",
                }}
              >
                {selected.size} {selected.size === 1 ? "Suche" : "Suchen"} starten →
              </button>
            </div>
          </div>
        )}

        <style>{`@keyframes spin { to { transform: rotate(360deg) } }`}</style>
      </div>
    </div>
  );
}
