"use client";

import { useMemo } from "react";
import { useRouter } from "next/navigation";
import { ArrowRight, Clock3, Flame, Play, Sparkles, Target, Timer } from "lucide-react";
import { FocusCenter } from "@/components/focus/focus-center";
import { fmtDelta, fmtMs, useFocusStore, type FocusReviewSnapshot } from "@/stores/focus-store";
import { cn } from "@/lib/utils";

function formatReviewDate(review: FocusReviewSnapshot) {
  return new Date(review.endedAt).toLocaleDateString("de-DE", {
    weekday: "short",
    day: "2-digit",
    month: "short",
  });
}

function formatReviewTimeRange(review: FocusReviewSnapshot) {
  const start = review.startedAt ? new Date(review.startedAt) : new Date(review.endedAt);
  const end = new Date(review.endedAt);

  return `${start.toLocaleTimeString("de-DE", {
    hour: "2-digit",
    minute: "2-digit",
  })} - ${end.toLocaleTimeString("de-DE", {
    hour: "2-digit",
    minute: "2-digit",
  })}`;
}

function toLocalDayKey(date: Date): string {
  const year = date.getFullYear();
  const month = `${date.getMonth() + 1}`.padStart(2, "0");
  const day = `${date.getDate()}`.padStart(2, "0");
  return `${year}-${month}-${day}`;
}

function buildDeepWorkStats(history: FocusReviewSnapshot[]) {
  const activeReviews = history.filter(
    (review) => review.workDuration > 0 || review.completedTasks.length > 0,
  );
  const dayKeys = Array.from(
    new Set(activeReviews.map((review) => toLocalDayKey(new Date(review.endedAt)))),
  ).sort((a, b) => b.localeCompare(a));

  const cursor = new Date();
  let streak = 0;
  for (let index = 0; index < 30; index++) {
    const key = toLocalDayKey(cursor);
    if (!dayKeys.includes(key)) {
      if (streak === 0 && index === 0) {
        cursor.setDate(cursor.getDate() - 1);
        continue;
      }
      break;
    }

    streak += 1;
    cursor.setDate(cursor.getDate() - 1);
  }

  return {
    bestWorkDuration: Math.max(0, ...activeReviews.map((review) => review.workDuration)),
    sessions: activeReviews.length,
    streak,
    totalTasks: activeReviews.reduce((sum, review) => sum + review.completedTasks.length, 0),
    totalWorkDuration: activeReviews.reduce((sum, review) => sum + review.workDuration, 0),
  };
}

export default function FocusPage() {
  const router = useRouter();
  const focusActive = useFocusStore((state) => state.focusActive);
  const focusReviewHistory = useFocusStore((state) => state.focusReviewHistory);
  const lastFocusReview = useFocusStore((state) => state.lastFocusReview);
  const openFocusReview = useFocusStore((state) => state.openFocusReview);
  const startFocusMode = useFocusStore((state) => state.startFocusMode);

  const latestReview = useMemo(
    () => lastFocusReview ?? focusReviewHistory[0] ?? null,
    [focusReviewHistory, lastFocusReview],
  );
  const deepWorkStats = useMemo(
    () => buildDeepWorkStats(focusReviewHistory),
    [focusReviewHistory],
  );

  function handleStartFocus() {
    startFocusMode();
  }

  function handleOpenReview(reviewId: string) {
    openFocusReview(reviewId);
    router.push("/focus/review");
  }

  if (focusActive) {
    return <FocusCenter />;
  }

  return (
    <div className="min-h-screen bg-[radial-gradient(circle_at_top,#2b1d45_0%,#0b0a12_42%,#06060a_100%)] px-6 py-10 text-white">
      <div className="mx-auto w-full max-w-6xl">
        <div className="rounded-[32px] border border-white/[0.08] bg-[#0f0d17]/86 p-8 shadow-[0_24px_90px_rgba(0,0,0,0.48)] backdrop-blur-xl md:p-10">
          <div className="flex flex-col gap-5 border-b border-white/[0.06] pb-8 lg:flex-row lg:items-end lg:justify-between">
            <div>
              <div className="flex items-center gap-4">
                <div className="flex h-16 w-16 items-center justify-center rounded-[22px] bg-violet-500/15">
                  <Target className="h-7 w-7 text-violet-300" />
                </div>
                <div>
                  <p className="text-[12px] font-bold uppercase tracking-[0.2em] text-[#d7baff]/70">
                    Focus Hub
                  </p>
                  <h1 className="mt-2 text-[34px] font-bold tracking-tight text-white">
                    Erst sehen, dann bewusst starten
                  </h1>
                </div>
              </div>
              <p className="mt-5 max-w-2xl text-[15px] leading-relaxed text-white/45">
                Hier siehst du zuerst deinen letzten Fokus und den Verlauf der letzten
                Reviews. Eine neue Session startet erst, wenn du bewusst auf Starten drückst.
              </p>
            </div>

            <div className="flex flex-col gap-3 sm:flex-row">
              <button
                onClick={handleStartFocus}
                className="inline-flex items-center justify-center gap-2 rounded-2xl bg-violet-500 px-5 py-3 text-[14px] font-semibold text-white shadow-[0_18px_40px_rgba(139,92,246,0.28)] transition-all hover:bg-violet-400"
              >
                <Play className="h-4 w-4 translate-x-[1px]" />
                Fokus starten
              </button>

              <button
                onClick={() => router.push("/")}
                className="inline-flex items-center justify-center gap-2 rounded-2xl border border-white/[0.08] bg-white/[0.03] px-5 py-3 text-[14px] font-semibold text-white/75 transition-all hover:bg-white/[0.06] hover:text-white"
              >
                Zurück zur App
              </button>
            </div>
          </div>

          {/* Block plan suggestion */}
          <BlockPlan />

          <div className="mt-8 grid gap-6 xl:grid-cols-[1.15fr_0.85fr]">
            <div className="rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-6">
              <div className="flex items-center gap-3">
                <div className="flex h-10 w-10 items-center justify-center rounded-2xl bg-violet-500/12">
                  <Sparkles className="h-4 w-4 text-violet-300" />
                </div>
                <div>
                  <p className="text-[11px] font-bold uppercase tracking-[0.18em] text-white/25">
                    Letzter Focus
                  </p>
                  <p className="mt-1 text-sm text-white/45">
                    Deine letzte abgeschlossene Session auf einen Blick
                  </p>
                </div>
              </div>

              {latestReview ? (
                <div className="mt-5 space-y-5">
                  <div className="rounded-[24px] border border-white/[0.06] bg-[linear-gradient(135deg,rgba(168,85,247,0.14),rgba(59,130,246,0.08))] p-5">
                    <div className="flex flex-col gap-4 md:flex-row md:items-end md:justify-between">
                      <div>
                        <p className="text-[11px] font-bold uppercase tracking-[0.16em] text-white/35">
                          {formatReviewDate(latestReview)}
                        </p>
                        <h2 className="mt-2 text-[28px] font-bold tracking-tight text-white">
                          {latestReview.completedTasks.length} Tasks abgeschlossen
                        </h2>
                        <p className="mt-2 text-sm text-white/45">
                          Session von {formatReviewTimeRange(latestReview)}
                        </p>
                      </div>

                      <button
                        onClick={() => handleOpenReview(latestReview.id)}
                        className="inline-flex items-center gap-2 rounded-2xl border border-white/[0.1] bg-white/[0.05] px-4 py-3 text-[13px] font-semibold text-white transition-all hover:bg-white/[0.08]"
                      >
                        Review öffnen
                        <ArrowRight className="h-4 w-4" />
                      </button>
                    </div>
                  </div>

                  <div className="grid gap-3 md:grid-cols-3">
                    <SessionMetric
                      label="Arbeitszeit"
                      value={fmtMs(latestReview.workDuration)}
                    />
                    <SessionMetric
                      label="Im Fokus"
                      value={fmtDelta(latestReview.focusDuration)}
                    />
                    <SessionMetric
                      label="Ø pro Task"
                      value={
                        latestReview.completedTasks.length > 0
                          ? fmtDelta(
                              latestReview.workDuration / latestReview.completedTasks.length,
                            )
                          : "—"
                      }
                    />
                  </div>
                </div>
              ) : (
                <div className="mt-5 rounded-[24px] border border-dashed border-white/[0.08] bg-white/[0.02] px-5 py-12 text-center">
                  <p className="text-[16px] font-semibold text-white/40">
                    Noch kein Focus abgeschlossen
                  </p>
                  <p className="mt-2 text-[13px] text-white/28">
                    Sobald du deine erste Session mit Review & Abschluss beendest,
                    erscheint sie hier.
                  </p>
                </div>
              )}
            </div>

            <div className="space-y-6">
              <div className="overflow-hidden rounded-[28px] border border-orange-500/15 bg-[radial-gradient(circle_at_top_left,rgba(249,115,22,0.14),rgba(255,255,255,0.03)_42%,rgba(255,255,255,0.02)_100%)] p-6">
                <div className="flex items-center justify-between gap-3">
                  <div>
                    <p className="text-[11px] font-bold uppercase tracking-[0.18em] text-orange-200/45">
                      Deep Work Streak
                    </p>
                    <p className="mt-1 text-sm text-white/45">
                      Gezählt aus abgeschlossenen Fokus-Sessions
                    </p>
                  </div>
                  <div className="flex h-10 w-10 items-center justify-center rounded-2xl bg-orange-500/12">
                    <Flame className="h-4 w-4 text-orange-300" />
                  </div>
                </div>

                <div className="mt-5 grid gap-3 sm:grid-cols-2">
                  <SessionMetric label="Aktuelle Serie" value={`${deepWorkStats.streak} Tage`} />
                  <SessionMetric label="Sessions" value={String(deepWorkStats.sessions)} />
                  <SessionMetric label="Gesamtarbeit" value={fmtMs(deepWorkStats.totalWorkDuration)} />
                  <SessionMetric label="Beste Session" value={fmtMs(deepWorkStats.bestWorkDuration)} />
                </div>

                <p className="mt-4 text-[12px] leading-relaxed text-white/34">
                  {deepWorkStats.streak > 0
                    ? "Ein Fokusblock heute hält die Kette am Leben."
                    : "Starte heute einen Fokusblock, dann beginnt deine Deep-Work-Serie."}
                </p>
              </div>

              <div className="rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-6">
                <div className="flex items-center justify-between gap-3">
                  <div>
                    <p className="text-[11px] font-bold uppercase tracking-[0.18em] text-white/25">
                      Letzte 3 Reviews
                    </p>
                    <p className="mt-1 text-sm text-white/45">
                      Dein kurzer Verlauf der letzten Fokus-Sessions
                    </p>
                  </div>
                  <Clock3 className="h-4 w-4 text-white/25" />
                </div>

                <div className="mt-5 space-y-3">
                  {focusReviewHistory.length === 0 ? (
                    <div className="rounded-2xl border border-dashed border-white/[0.08] bg-white/[0.02] px-4 py-6 text-center text-[13px] text-white/30">
                      Noch keine Review-Historie vorhanden.
                    </div>
                  ) : (
                    focusReviewHistory.slice(0, 3).map((review, index) => (
                      <button
                        key={review.id}
                        onClick={() => handleOpenReview(review.id)}
                        className="flex w-full items-center justify-between gap-4 rounded-2xl border border-white/[0.05] bg-white/[0.02] px-4 py-4 text-left transition-all hover:border-white/[0.09] hover:bg-white/[0.04]"
                      >
                        <div className="min-w-0">
                          <p className="text-[10px] font-bold uppercase tracking-[0.16em] text-white/22">
                            Review {index + 1}
                          </p>
                          <p className="mt-1 text-[14px] font-semibold text-white/88">
                            {formatReviewDate(review)}
                          </p>
                          <p className="mt-1 text-[12px] text-white/35">
                            {formatReviewTimeRange(review)}
                          </p>
                        </div>

                        <div className="shrink-0 text-right">
                          <p className="text-[16px] font-bold text-white">
                            {review.completedTasks.length}
                          </p>
                          <p className="text-[10px] uppercase tracking-[0.16em] text-white/22">
                            Tasks
                          </p>
                        </div>
                      </button>
                    ))
                  )}
                </div>
              </div>

              <div className="grid gap-4 rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-5 md:grid-cols-3 xl:grid-cols-1">
                <FocusTeaser
                  title="Tasks im Highlight"
                  description="Nur die Kernaufgaben, die jetzt wirklich wichtig sind."
                />
                <FocusTeaser
                  title="Termine live"
                  description="Mit Status wie Bald, Läuft und Beendet direkt im Blick."
                />
                <FocusTeaser
                  title="Zeitmessung"
                  description="Arbeitszeit und Task-Deltas laufen sauber in deiner Session mit."
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function FocusTeaser({
  description,
  title,
}: {
  description: string;
  title: string;
}) {
  return (
    <div className="rounded-[22px] border border-white/[0.04] bg-white/[0.02] p-4">
      <p className="text-[13px] font-semibold text-white">{title}</p>
      <p className="mt-2 text-[12px] leading-relaxed text-white/35">{description}</p>
    </div>
  );
}

function SessionMetric({
  label,
  value,
}: {
  label: string;
  value: string;
}) {
  return (
    <div className="rounded-[22px] border border-white/[0.05] bg-white/[0.03] p-4">
      <p className="text-[11px] font-bold uppercase tracking-[0.16em] text-white/24">
        {label}
      </p>
      <p className={cn("mt-2 text-[22px] font-bold tracking-tight text-white")}>
        {value}
      </p>
    </div>
  );
}

const BLOCK_PLAN = [
  { label: "Deep Work",    minutes: 90, color: "#7c3aed", bg: "rgba(124,58,237,0.65)" },
  { label: "Kurze Pause",  minutes: 15, color: "#059669", bg: "rgba(5,150,105,0.65)" },
  { label: "Deep Work",    minutes: 90, color: "#7c3aed", bg: "rgba(124,58,237,0.65)" },
  { label: "Lange Pause",  minutes: 30, color: "#0284c7", bg: "rgba(2,132,199,0.65)" },
];

function BlockPlan() {
  const total = BLOCK_PLAN.reduce((s, b) => s + b.minutes, 0); // 225 min = 3h 45m

  return (
    <div className="mt-8 rounded-[28px] border border-violet-500/15 bg-[linear-gradient(135deg,rgba(124,58,237,0.10),rgba(59,130,246,0.04))] p-6">
      <div className="flex items-start justify-between gap-4">
        <div className="flex items-center gap-3">
          <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl bg-violet-500/15">
            <Timer className="h-4 w-4 text-violet-300" />
          </div>
          <div>
            <p className="text-[11px] font-bold uppercase tracking-[0.18em] text-violet-200/55">
              Empfohlener Block-Plan
            </p>
            <p className="mt-0.5 text-[13px] text-white/45">
              Tief arbeiten in strukturierten Blöcken — im Focus Center anpassbar
            </p>
          </div>
        </div>
        <span className="shrink-0 text-[12px] text-white/28">
          ~{Math.floor(total / 60)}h {total % 60}min gesamt
        </span>
      </div>

      <div className="mt-5 space-y-3">
        {BLOCK_PLAN.map((block, i) => (
          <div key={i} className="flex items-center gap-4">
            <div className="w-32 shrink-0">
              <p className="text-[12px] font-semibold text-white/75">{block.label}</p>
              <p className="text-[11px] text-white/30">{block.minutes} min</p>
            </div>
            <div className="flex-1 h-5 overflow-hidden rounded-full bg-white/[0.04]">
              <div
                className="h-full rounded-full transition-all"
                style={{ width: `${(block.minutes / 90) * 100}%`, background: block.bg }}
              />
            </div>
          </div>
        ))}
      </div>

      <p className="mt-4 text-[11px] text-white/22">
        Starte den Focus Mode und nutze den integrierten Block-Timer — Dauer für jeden Block individuell einstellbar.
      </p>
    </div>
  );
}
