"use client";

import { useState } from "react";
import {
  Sparkles,
  Target,
  Plus,
  Trash2,
  Check,
  Pencil,
  Trophy,
  Sun,
  Moon,
  Bot,
  Loader2,
  Lightbulb,
  Heart,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Modal } from "@/components/ui/modal";
import { Skeleton } from "@/components/ui/skeleton";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
import { useMindset } from "@/hooks/use-mindset";
import { useWorkspaceStore } from "@/stores/workspace-store";

const GOAL_COLORS = [
  "#ef4444", "#f59e0b", "#10b981", "#3b82f6",
  "#6366f1", "#8b5cf6", "#ec4899", "#06b6d4",
];

const GOAL_ICONS = ["🎯", "💰", "💪", "📈", "🏠", "🎬", "🧠", "❤️", "🚀", "⭐", "🔥", "👑"];

const DAILY_MINDSET_QUOTES = [
  {
    line: "Du musst heute nicht alles lösen. Du musst nur den nächsten ehrlichen Schritt gehen.",
    focus: "Weniger Druck, mehr Klarheit. Frag dich: Was ist der nächste kleine Schritt, der mir wirklich hilft?",
  },
  {
    line: "Fortschritt entsteht oft leise. Auch ruhige Tage bringen dich voran.",
    focus: "Miss den Tag nicht nur an Tempo. Miss ihn daran, ob du dir selbst treu geblieben bist.",
  },
  {
    line: "Deine aktuelle Lage ist ein Kapitel, nicht deine ganze Geschichte.",
    focus: "Trenne den Moment von deiner Identität. Ein schwerer Tag macht dich nicht schwach.",
  },
  {
    line: "Klarheit kommt selten vor dem Handeln. Sie entsteht oft mitten im ersten Schritt.",
    focus: "Warte nicht auf perfekte Sicherheit. Fang klein an und lass Bewegung die Sicht verbessern.",
  },
  {
    line: "Was dich belastet, darf Raum haben. Es muss aber nicht das Steuer übernehmen.",
    focus: "Nimm deine Sorge ernst, ohne ihr automatisch die Führung zu geben.",
  },
  {
    line: "Du brauchst heute keine perfekte Version von dir. Du brauchst eine ehrliche.",
    focus: "Frag dich nicht, wie du beeindruckst. Frag dich, was dir gerade wirklich guttut.",
  },
  {
    line: "Konstanz ist oft mutiger als Motivation.",
    focus: "Wenn die Energie fehlt, zählt nicht Größe. Es zählt, dass du dranbleibst.",
  },
  {
    line: "Ein klarer Gedanke am Morgen kann den ganzen Tag neu ausrichten.",
    focus: "Wähle bewusst einen Satz, dem du heute folgen willst, statt jedem Impuls nachzulaufen.",
  },
  {
    line: "Nicht jede Unsicherheit ist ein Stoppschild. Manchmal ist sie nur Begleitung auf neuem Boden.",
    focus: "Du darfst dich unsicher fühlen und trotzdem handeln.",
  },
  {
    line: "Selbstvertrauen wächst nicht nur durch Siege, sondern auch dadurch, dass du dir in schweren Momenten beistehst.",
    focus: "Rede heute mit dir so, wie du mit jemandem reden würdest, der dir wichtig ist.",
  },
  {
    line: "Dein Nervensystem braucht nicht nur Ziele. Es braucht auch Sicherheit.",
    focus: "Bevor du dich antreibst, frag: Was würde mich gerade ein Stück ruhiger machen?",
  },
  {
    line: "Ein ruhiger Fokus schlägt hektischen Aktionismus.",
    focus: "Weniger Dinge, sauberer umgesetzt, bringen heute wahrscheinlich mehr.",
  },
];

function getDailyMindsetQuote(date = new Date()) {
  const startOfDay = new Date(date.getFullYear(), date.getMonth(), date.getDate());
  const dayKey = Math.floor(startOfDay.getTime() / 86_400_000);
  return DAILY_MINDSET_QUOTES[Math.abs(dayKey) % DAILY_MINDSET_QUOTES.length];
}

function formatMindsetDate(date = new Date()) {
  return date.toLocaleDateString("de-DE", {
    weekday: "long",
    day: "numeric",
    month: "long",
  });
}

export default function MindsetPage() {
  const {
    affirmations,
    goals,
    loading,
    addAffirmation,
    updateAffirmation,
    deleteAffirmation,
    addGoal,
    updateGoal,
    deleteGoal,
  } = useMindset();
  const activeTeamId = useWorkspaceStore((state) => state.activeTeamId);

  const [newAffirmation, setNewAffirmation] = useState("");
  const [editingAff, setEditingAff] = useState<string | null>(null);
  const [editAffText, setEditAffText] = useState("");
  const [showGoalModal, setShowGoalModal] = useState(false);
  const [editingGoal, setEditingGoal] = useState<string | null>(null);
  const [supportInput, setSupportInput] = useState("");
  const [supportResponse, setSupportResponse] = useState("");
  const [supportError, setSupportError] = useState<string | null>(null);
  const [supportLoading, setSupportLoading] = useState(false);
  const [supportSource, setSupportSource] = useState<{
    provider: string;
    model: string;
  } | null>(null);

  // Goal form state
  const [goalTitle, setGoalTitle] = useState("");
  const [goalDesc, setGoalDesc] = useState("");
  const [goalDate, setGoalDate] = useState("");
  const [goalColor, setGoalColor] = useState("#6366f1");
  const [goalIcon, setGoalIcon] = useState("🎯");

  // Time-based reminder
  const hour = new Date().getHours();
  const isMorning = hour >= 5 && hour < 11;
  const isEvening = hour >= 20 || hour < 5;
  const showReminder = isMorning || isEvening;
  const dailyQuote = getDailyMindsetQuote();
  const dailyQuoteDate = formatMindsetDate();

  function handleAddAffirmation() {
    if (!newAffirmation.trim()) return;
    addAffirmation(newAffirmation.trim());
    setNewAffirmation("");
  }

  function handleEditAffirmation(id: string) {
    if (!editAffText.trim()) return;
    updateAffirmation(id, editAffText.trim());
    setEditingAff(null);
  }

  function openGoalForm(goalId?: string) {
    if (goalId) {
      const g = goals.find((x) => x.id === goalId);
      if (g) {
        setGoalTitle(g.title);
        setGoalDesc(g.description || "");
        setGoalDate(g.target_date || "");
        setGoalColor(g.color);
        setGoalIcon(g.icon);
        setEditingGoal(goalId);
      }
    } else {
      setGoalTitle("");
      setGoalDesc("");
      setGoalDate("");
      setGoalColor("#6366f1");
      setGoalIcon("🎯");
      setEditingGoal(null);
    }
    setShowGoalModal(true);
  }

  function handleSaveGoal() {
    if (!goalTitle.trim()) return;
    if (editingGoal) {
      updateGoal(editingGoal, {
        title: goalTitle.trim(),
        description: goalDesc.trim() || null,
        target_date: goalDate || null,
        color: goalColor,
        icon: goalIcon,
      });
    } else {
      addGoal({
        title: goalTitle.trim(),
        description: goalDesc.trim(),
        target_date: goalDate,
        color: goalColor,
        icon: goalIcon,
      });
    }
    setShowGoalModal(false);
  }

  async function handleGenerateSupport() {
    const trimmed = supportInput.trim();
    if (!trimmed) return;

    setSupportLoading(true);
    setSupportError(null);

    try {
      const res = await fetch("/api/ai/mindset-support", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          concern: trimmed,
          workspaceTeamId: activeTeamId,
        }),
      });

      const data = await res.json();

      if (!res.ok) {
        throw new Error(
          typeof data?.error === "string"
            ? data.error
            : "Die KI-Antwort konnte gerade nicht erzeugt werden."
        );
      }

      setSupportResponse(typeof data?.text === "string" ? data.text : "");
      setSupportSource(
        typeof data?.provider === "string" && typeof data?.model === "string"
          ? {
              provider: data.provider,
              model: data.model,
            }
          : null
      );
    } catch (error) {
      setSupportError(
        error instanceof Error
          ? error.message
          : "Die KI-Antwort konnte gerade nicht erzeugt werden."
      );
    } finally {
      setSupportLoading(false);
    }
  }

  if (loading) {
    return (
      <div>
        <div className="flex items-center gap-3 mb-6">
          <Sparkles className="h-5 w-5 text-muted-foreground" />
          <h1 className="text-2xl font-bold tracking-tight">Mindset</h1>
        </div>
        <div className="space-y-4">
          <Skeleton className="h-48 rounded-xl" />
          <Skeleton className="h-48 rounded-xl" />
        </div>
      </div>
    );
  }

  return (
    <div>
      <div className="flex items-center gap-3 mb-6">
        <Sparkles className="h-5 w-5 text-muted-foreground" />
        <h1 className="text-2xl font-bold tracking-tight">Mindset</h1>
      </div>

      {activeTeamId && (
        <div className="mb-6 rounded-xl border border-primary/20 bg-primary/5 px-4 py-3 text-sm text-muted-foreground">
          Team-Workspace ist aktiv. Ziele, die du hier erstellst, sind mit dem Team geteilt. Glaubenssätze bleiben weiterhin privat in deinem Account.
        </div>
      )}

      <div className="mb-6 grid gap-6 xl:grid-cols-[0.9fr_1.1fr]">
        <div className="rounded-2xl border border-amber-500/20 bg-gradient-to-br from-amber-500/10 via-background to-background p-5">
          <div className="mb-4 flex items-center gap-2">
            <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-amber-500/12">
              <Lightbulb className="h-4 w-4 text-amber-500" />
            </div>
            <div>
              <h2 className="text-lg font-semibold">Motivationsspruch des Tages</h2>
              <p className="text-xs text-muted-foreground capitalize">{dailyQuoteDate}</p>
            </div>
          </div>

          <div className="rounded-xl border border-border/70 bg-background/80 p-4">
            <p className="text-base font-medium leading-relaxed">
              &ldquo;{dailyQuote.line}&rdquo;
            </p>
            <div className="mt-4 flex items-start gap-2 rounded-lg bg-amber-500/8 px-3 py-3">
              <Heart className="mt-0.5 h-4 w-4 shrink-0 text-amber-500" />
              <p className="text-sm text-muted-foreground">{dailyQuote.focus}</p>
            </div>
          </div>
        </div>

        <div className="rounded-2xl border border-indigo-500/20 bg-gradient-to-br from-indigo-500/10 via-background to-background p-5">
          <div className="mb-4 flex items-center gap-2">
            <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-indigo-500/12">
              <Bot className="h-4 w-4 text-indigo-500" />
            </div>
            <div>
              <h2 className="text-lg font-semibold">KI-Unterstützung für deine Lage</h2>
              <p className="text-xs text-muted-foreground">
                Schreib auf, was dich gerade belastet. Du bekommst eine klare, hilfreiche Antwort.
              </p>
            </div>
          </div>

          <div className="space-y-3">
            <Textarea
              value={supportInput}
              onChange={(event) => setSupportInput(event.target.value)}
              onKeyDown={(event) => {
                if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {
                  event.preventDefault();
                  void handleGenerateSupport();
                }
              }}
              placeholder="z.B. Ich bin gerade überfordert, zweifle an mir und weiß nicht, womit ich anfangen soll..."
              className="min-h-[140px] rounded-xl border-border/70 bg-background/80"
              maxLength={1800}
            />

            <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
              <p className="text-xs text-muted-foreground">
                Je konkreter du deine Sorge beschreibst, desto besser kann die Antwort dir helfen.
              </p>
              <Button
                onClick={() => {
                  void handleGenerateSupport();
                }}
                disabled={!supportInput.trim() || supportLoading}
              >
                {supportLoading ? (
                  <>
                    <Loader2 className="h-4 w-4 animate-spin" />
                    Antwort wird erstellt...
                  </>
                ) : (
                  <>
                    <Sparkles className="h-4 w-4" />
                    KI-Antwort generieren
                  </>
                )}
              </Button>
            </div>

            {supportError && (
              <div className="rounded-xl border border-destructive/20 bg-destructive/5 px-4 py-3 text-sm text-destructive">
                {supportError}
              </div>
            )}

            {supportResponse && (
              <div className="rounded-xl border border-border/70 bg-background/85 p-4">
                <div className="mb-3 flex items-center justify-between gap-3">
                  <p className="text-sm font-semibold">Dein KI-Impuls</p>
                  {supportSource && (
                    <span className="text-[11px] text-muted-foreground">
                      {supportSource.provider} · {supportSource.model}
                    </span>
                  )}
                </div>
                <p className="whitespace-pre-wrap text-sm leading-6 text-foreground/90">
                  {supportResponse}
                </p>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Affirmation Reminder Banner */}
      {showReminder && affirmations.length > 0 && (
        <div className="mb-6 rounded-xl border-2 border-indigo-500/30 bg-indigo-500/5 p-5">
          <div className="flex items-center gap-2 mb-3">
            {isMorning ? (
              <Sun className="h-5 w-5 text-amber-500" />
            ) : (
              <Moon className="h-5 w-5 text-indigo-400" />
            )}
            <span className="font-semibold text-sm">
              {isMorning
                ? "Guten Morgen! Sage deine Glaubenssätze laut auf:"
                : "Gute Nacht! Sage deine Glaubenssätze vor dem Schlafen:"}
            </span>
          </div>
          <div className="space-y-2">
            {affirmations.map((aff, i) => (
              <div
                key={aff.id}
                className="flex items-start gap-3 rounded-lg bg-background/50 px-4 py-3"
              >
                <span className="text-indigo-500 font-bold text-sm mt-0.5">
                  {i + 1}.
                </span>
                <p className="text-sm font-medium italic">
                  &ldquo;{aff.text}&rdquo;
                </p>
              </div>
            ))}
          </div>
        </div>
      )}

      <div className="grid gap-6 lg:grid-cols-2">
        {/* ─── Glaubenssätze ─── */}
        <div>
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold flex items-center gap-2">
              <Sparkles className="h-4 w-4 text-indigo-500" />
              Glaubenssätze
            </h2>
          </div>
          <p className="text-xs text-muted-foreground mb-4">
            Sage diese Sätze jeden Morgen nach dem Aufstehen und jeden Abend vor
            dem Schlafen laut auf. Wiederholung programmiert dein Unterbewusstsein.
          </p>

          {/* Add new */}
          <div className="flex gap-2 mb-4">
            <Input
              placeholder="Ich bin erfolgreich und..."
              value={newAffirmation}
              onChange={(e) => setNewAffirmation(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && handleAddAffirmation()}
              className="text-sm"
            />
            <Button
              onClick={handleAddAffirmation}
              disabled={!newAffirmation.trim()}
              size="sm"
            >
              <Plus className="h-4 w-4" />
            </Button>
          </div>

          {/* List */}
          <div className="space-y-2">
            {affirmations.length === 0 ? (
              <div className="text-center py-10 rounded-xl border border-dashed border-border">
                <Sparkles className="h-8 w-8 mx-auto mb-2 text-muted-foreground opacity-40" />
                <p className="text-sm text-muted-foreground">
                  Füge deinen ersten Glaubenssatz hinzu
                </p>
              </div>
            ) : (
              affirmations.map((aff, i) => (
                <div
                  key={aff.id}
                  className="group flex items-center gap-3 rounded-xl border border-border bg-card px-4 py-3 transition-colors hover:bg-accent/30"
                >
                  <span className="text-indigo-500 font-bold text-sm w-5 shrink-0">
                    {i + 1}.
                  </span>
                  {editingAff === aff.id ? (
                    <div className="flex-1 flex gap-2">
                      <Input
                        value={editAffText}
                        onChange={(e) => setEditAffText(e.target.value)}
                        onKeyDown={(e) =>
                          e.key === "Enter" && handleEditAffirmation(aff.id)
                        }
                        className="text-sm"
                        autoFocus
                      />
                      <Button
                        size="sm"
                        variant="ghost"
                        onClick={() => handleEditAffirmation(aff.id)}
                      >
                        <Check className="h-4 w-4" />
                      </Button>
                    </div>
                  ) : (
                    <>
                      <p className="flex-1 text-sm italic">
                        &ldquo;{aff.text}&rdquo;
                      </p>
                      <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                        <button
                          onClick={() => {
                            setEditingAff(aff.id);
                            setEditAffText(aff.text);
                          }}
                          className="p-1 rounded-md hover:bg-accent cursor-pointer"
                        >
                          <Pencil className="h-3.5 w-3.5 text-muted-foreground" />
                        </button>
                        <button
                          onClick={() => deleteAffirmation(aff.id)}
                          className="p-1 rounded-md hover:bg-accent cursor-pointer"
                        >
                          <Trash2 className="h-3.5 w-3.5 text-red-500" />
                        </button>
                      </div>
                    </>
                  )}
                </div>
              ))
            )}
          </div>
        </div>

        {/* ─── Ziele ─── */}
        <div>
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold flex items-center gap-2">
              <Target className="h-4 w-4 text-indigo-500" />
              Ziele
            </h2>
            <Button size="sm" onClick={() => openGoalForm()}>
              <Plus className="h-4 w-4" />
              Neues Ziel
            </Button>
          </div>

          <div className="space-y-3">
            {goals.length === 0 ? (
              <div className="text-center py-10 rounded-xl border border-dashed border-border">
                <Target className="h-8 w-8 mx-auto mb-2 text-muted-foreground opacity-40" />
                <p className="text-sm text-muted-foreground">
                  Definiere dein erstes Ziel
                </p>
              </div>
            ) : (
              goals.map((goal) => (
                <div
                  key={goal.id}
                  className={cn(
                    "rounded-xl border border-border bg-card p-4 transition-all",
                    goal.completed && "opacity-60"
                  )}
                >
                  <div className="flex items-start gap-3">
                    <span className="text-2xl">{goal.icon}</span>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2">
                        <h3
                          className={cn(
                            "font-semibold text-sm",
                            goal.completed && "line-through text-muted-foreground"
                          )}
                        >
                          {goal.title}
                        </h3>
                        {goal.completed && (
                          <Trophy className="h-4 w-4 text-amber-500" />
                        )}
                      </div>
                      {goal.description && (
                        <p className="text-xs text-muted-foreground mt-0.5 line-clamp-2">
                          {goal.description}
                        </p>
                      )}

                      {/* Progress bar */}
                      <div className="flex items-center gap-3 mt-3">
                        <div className="flex-1 h-2 rounded-full bg-muted overflow-hidden">
                          <div
                            className="h-full rounded-full transition-all duration-500"
                            style={{
                              width: `${goal.progress}%`,
                              backgroundColor: goal.color,
                            }}
                          />
                        </div>
                        <span
                          className="text-xs font-bold"
                          style={{ color: goal.color }}
                        >
                          {goal.progress}%
                        </span>
                      </div>

                      {/* Progress buttons */}
                      <div className="flex items-center gap-2 mt-2">
                        {[10, 25, 50, 75, 100].map((val) => (
                          <button
                            key={val}
                            onClick={() =>
                              updateGoal(goal.id, {
                                progress: val,
                                completed: val === 100,
                              })
                            }
                            className={cn(
                              "text-[10px] px-2 py-0.5 rounded-full border cursor-pointer transition-colors",
                              goal.progress >= val
                                ? "border-transparent text-white"
                                : "border-border hover:bg-accent text-muted-foreground"
                            )}
                            style={
                              goal.progress >= val
                                ? { backgroundColor: goal.color }
                                : undefined
                            }
                          >
                            {val}%
                          </button>
                        ))}
                      </div>

                      {goal.target_date && (
                        <p className="text-[10px] text-muted-foreground mt-2">
                          Ziel bis:{" "}
                          {new Date(goal.target_date + "T00:00:00").toLocaleDateString(
                            "de-DE",
                            { day: "numeric", month: "short", year: "numeric" }
                          )}
                        </p>
                      )}
                    </div>

                    {/* Actions */}
                    <div className="flex items-center gap-1 shrink-0">
                      <button
                        onClick={() => openGoalForm(goal.id)}
                        className="p-1 rounded-md hover:bg-accent cursor-pointer"
                      >
                        <Pencil className="h-3.5 w-3.5 text-muted-foreground" />
                      </button>
                      <button
                        onClick={() => deleteGoal(goal.id)}
                        className="p-1 rounded-md hover:bg-accent cursor-pointer"
                      >
                        <Trash2 className="h-3.5 w-3.5 text-red-500" />
                      </button>
                    </div>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      </div>

      {/* Goal Form Modal */}
      {showGoalModal && (
        <Modal
          open={showGoalModal}
          onClose={() => setShowGoalModal(false)}
          title={editingGoal ? "Ziel bearbeiten" : "Neues Ziel"}
        >
          <div className="space-y-4">
            <div>
              <label className="text-sm font-medium">Titel</label>
              <Input
                value={goalTitle}
                onChange={(e) => setGoalTitle(e.target.value)}
                placeholder="z.B. 100k Follower"
                className="mt-1"
                autoFocus
              />
            </div>
            <div>
              <label className="text-sm font-medium">Beschreibung</label>
              <Input
                value={goalDesc}
                onChange={(e) => setGoalDesc(e.target.value)}
                placeholder="Optional"
                className="mt-1"
              />
            </div>
            <div>
              <label className="text-sm font-medium">Zieldatum</label>
              <Input
                type="date"
                value={goalDate}
                onChange={(e) => setGoalDate(e.target.value)}
                className="mt-1"
              />
            </div>

            {/* Icon picker */}
            <div>
              <label className="text-sm font-medium">Icon</label>
              <div className="flex flex-wrap gap-2 mt-1">
                {GOAL_ICONS.map((icon) => (
                  <button
                    key={icon}
                    onClick={() => setGoalIcon(icon)}
                    className={cn(
                      "w-9 h-9 rounded-lg flex items-center justify-center text-lg cursor-pointer border-2 transition-colors",
                      goalIcon === icon
                        ? "border-primary bg-accent"
                        : "border-transparent hover:bg-accent"
                    )}
                  >
                    {icon}
                  </button>
                ))}
              </div>
            </div>

            {/* Color picker */}
            <div>
              <label className="text-sm font-medium">Farbe</label>
              <div className="flex gap-2 mt-1">
                {GOAL_COLORS.map((color) => (
                  <button
                    key={color}
                    onClick={() => setGoalColor(color)}
                    className={cn(
                      "w-7 h-7 rounded-full cursor-pointer border-2 transition-transform",
                      goalColor === color
                        ? "border-foreground scale-110"
                        : "border-transparent hover:scale-105"
                    )}
                    style={{ backgroundColor: color }}
                  />
                ))}
              </div>
            </div>

            <div className="flex justify-end gap-2 pt-2">
              <Button variant="ghost" onClick={() => setShowGoalModal(false)}>
                Abbrechen
              </Button>
              <Button onClick={handleSaveGoal} disabled={!goalTitle.trim()}>
                {editingGoal ? "Speichern" : "Ziel erstellen"}
              </Button>
            </div>
          </div>
        </Modal>
      )}
    </div>
  );
}
