"use client";

import { useState, useEffect, useMemo } from "react";

interface JournalEntry {
  id: number;
  user_id: number;
  entry_date: string;
  provider_name: string | null;
  duration: string;
  mood: number;
  notes: string | null;
  created_at: string;
}

const MOOD_EMOJIS = ["", "\u{1F610}", "\u{1F60A}", "\u{1F604}", "\u{1F929}", "\u{1FAB7}"];
const MOOD_LABELS = ["", "Neutral", "Happy", "Great", "Amazing", "Magical"];
const DURATIONS = ["1 hour", "2 hours", "3 hours", "Overnight", "Weekend"];

function toLocalDateString(date: Date): string {
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, "0");
  const d = String(date.getDate()).padStart(2, "0");
  return `${y}-${m}-${d}`;
}

export default function JournalPage() {
  const [entries, setEntries] = useState<JournalEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [expandedId, setExpandedId] = useState<number | null>(null);
  const [deletingId, setDeletingId] = useState<number | null>(null);

  // Form state
  const [entryDate, setEntryDate] = useState(toLocalDateString(new Date()));
  const [providerName, setProviderName] = useState("");
  const [duration, setDuration] = useState("1 hour");
  const [mood, setMood] = useState(0);
  const [notes, setNotes] = useState("");

  useEffect(() => {
    fetchEntries();
  }, []);

  async function fetchEntries() {
    try {
      const res = await fetch("/api/journal");
      if (res.ok) {
        const data = await res.json();
        setEntries(data.entries || []);
      }
    } finally {
      setLoading(false);
    }
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (mood === 0) return;
    setSaving(true);
    try {
      const res = await fetch("/api/journal", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          entry_date: entryDate,
          provider_name: providerName.trim() || null,
          duration,
          mood,
          notes: notes.trim() || null,
        }),
      });
      if (res.ok) {
        // Reset form
        setProviderName("");
        setDuration("1 hour");
        setMood(0);
        setNotes("");
        setEntryDate(toLocalDateString(new Date()));
        await fetchEntries();
      }
    } finally {
      setSaving(false);
    }
  }

  async function handleDelete(id: number) {
    setDeletingId(id);
    try {
      const res = await fetch(`/api/journal?id=${id}`, { method: "DELETE" });
      if (res.ok) {
        setEntries((prev) => prev.filter((e) => e.id !== id));
        if (expandedId === id) setExpandedId(null);
      }
    } finally {
      setDeletingId(null);
    }
  }

  // Year-end summary
  const yearSummary = useMemo(() => {
    const currentYear = new Date().getFullYear();
    const yearEntries = entries.filter(
      (e) => new Date(e.entry_date).getFullYear() === currentYear
    );
    if (yearEntries.length === 0) return null;

    const total = yearEntries.length;

    // Most common mood
    const moodCounts: Record<number, number> = {};
    yearEntries.forEach((e) => {
      moodCounts[e.mood] = (moodCounts[e.mood] || 0) + 1;
    });
    const topMood = Object.entries(moodCounts).sort(
      (a, b) => b[1] - a[1]
    )[0][0];

    // Average duration (map to hours for average)
    const durationHours: Record<string, number> = {
      "1 hour": 1,
      "2 hours": 2,
      "3 hours": 3,
      Overnight: 12,
      Weekend: 48,
    };
    const totalHours = yearEntries.reduce(
      (sum, e) => sum + (durationHours[e.duration] || 1),
      0
    );
    const avgHours = totalHours / total;

    let avgDurationLabel: string;
    if (avgHours < 1.5) avgDurationLabel = "~1 hour";
    else if (avgHours < 2.5) avgDurationLabel = "~2 hours";
    else if (avgHours < 6) avgDurationLabel = "~3 hours";
    else if (avgHours < 30) avgDurationLabel = "~Overnight";
    else avgDurationLabel = "~Weekend";

    return {
      total,
      topMood: parseInt(topMood),
      avgDuration: avgDurationLabel,
    };
  }, [entries]);

  return (
    <div className="max-w-3xl mx-auto">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-3xl font-bold text-text">My Experience Journal</h1>
          <p className="text-text-muted text-sm mt-1 flex items-center gap-1.5">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-4 w-4"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={2}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"
              />
            </svg>
            Private &amp; Encrypted
          </p>
        </div>
      </div>

      {/* Year-end Summary */}
      {yearSummary && (
        <div className="bg-gradient-to-r from-primary/10 to-gold/10 border border-primary/20 rounded-xl p-5 mb-8">
          <h2 className="text-sm font-semibold text-primary mb-3 uppercase tracking-wide">
            {new Date().getFullYear()} Summary
          </h2>
          <div className="grid grid-cols-3 gap-4">
            <div className="text-center">
              <p className="text-2xl font-bold text-text">{yearSummary.total}</p>
              <p className="text-xs text-text-muted mt-0.5">Experiences</p>
            </div>
            <div className="text-center">
              <p className="text-2xl">{MOOD_EMOJIS[yearSummary.topMood]}</p>
              <p className="text-xs text-text-muted mt-0.5">Most Common</p>
            </div>
            <div className="text-center">
              <p className="text-lg font-bold text-text">{yearSummary.avgDuration}</p>
              <p className="text-xs text-text-muted mt-0.5">Avg Duration</p>
            </div>
          </div>
        </div>
      )}

      {/* Add Entry Form */}
      <div className="bg-surface rounded-xl border border-surface-light p-6 mb-8">
        <h2 className="text-lg font-semibold text-text mb-4">Add Entry</h2>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-text mb-1">Date</label>
              <input
                type="date"
                value={entryDate}
                onChange={(e) => setEntryDate(e.target.value)}
                max={toLocalDateString(new Date())}
                className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-primary"
                required
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-text mb-1">
                Provider Username
              </label>
              <input
                type="text"
                value={providerName}
                onChange={(e) => setProviderName(e.target.value)}
                placeholder="Optional — leave blank for anonymous"
                className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-primary"
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-text mb-1">Duration</label>
            <select
              value={duration}
              onChange={(e) => setDuration(e.target.value)}
              className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-primary"
            >
              {DURATIONS.map((d) => (
                <option key={d} value={d}>
                  {d}
                </option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-text mb-2">Mood</label>
            <div className="flex gap-2">
              {[1, 2, 3, 4, 5].map((m) => (
                <button
                  key={m}
                  type="button"
                  onClick={() => setMood(m)}
                  className={`w-12 h-12 rounded-xl text-2xl transition-all ${
                    mood === m
                      ? "bg-primary/20 border-2 border-primary scale-110 shadow-lg shadow-primary/20"
                      : "bg-background border border-surface-light hover:border-primary/50 hover:scale-105"
                  }`}
                  title={MOOD_LABELS[m]}
                >
                  {MOOD_EMOJIS[m]}
                </button>
              ))}
            </div>
            {mood === 0 && (
              <p className="text-xs text-text-muted mt-1">Select a mood to continue</p>
            )}
          </div>

          <div>
            <label className="block text-sm font-medium text-text mb-1">
              Private Notes
            </label>
            <textarea
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              placeholder="How was your experience?"
              rows={3}
              className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-primary resize-none"
            />
          </div>

          <button
            type="submit"
            disabled={saving || mood === 0}
            className="bg-primary hover:bg-primary-dark text-white px-6 py-2.5 rounded-lg font-semibold transition-colors disabled:opacity-50"
          >
            {saving ? "Saving..." : "Save Entry"}
          </button>
        </form>
      </div>

      {/* Entries List */}
      <div>
        <h2 className="text-lg font-semibold text-text mb-4">Your Entries</h2>
        {loading ? (
          <div className="text-text-muted text-center py-8">Loading entries...</div>
        ) : entries.length === 0 ? (
          <div className="bg-surface rounded-xl border border-surface-light p-12 text-center">
            <svg
              className="w-16 h-16 mx-auto mb-4 text-text-muted/30"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={1.5}
                d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
              />
            </svg>
            <p className="text-text-muted">
              No journal entries yet. Add your first experience above.
            </p>
          </div>
        ) : (
          <div className="space-y-3">
            {entries.map((entry) => {
              const isExpanded = expandedId === entry.id;
              const displayDate = new Date(entry.entry_date).toLocaleDateString(undefined, {
                day: "numeric",
                month: "short",
                year: "numeric",
              });

              return (
                <div
                  key={entry.id}
                  className="bg-surface rounded-xl border border-surface-light overflow-hidden"
                >
                  <button
                    onClick={() => setExpandedId(isExpanded ? null : entry.id)}
                    className="w-full text-left p-4 hover:bg-surface-light/50 transition-colors"
                  >
                    <div className="flex items-center gap-3">
                      <span className="text-2xl shrink-0">{MOOD_EMOJIS[entry.mood]}</span>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 flex-wrap">
                          <span className="text-sm font-medium text-text">
                            {displayDate}
                          </span>
                          <span className="text-xs px-2 py-0.5 rounded-full bg-primary/10 text-primary border border-primary/20">
                            {entry.duration}
                          </span>
                        </div>
                        <p className="text-sm text-text-muted mt-0.5">
                          {entry.provider_name || "Anonymous"}
                          {entry.notes && !isExpanded && (
                            <span className="ml-2 text-text-muted/60">
                              &mdash;{" "}
                              {entry.notes.length > 100
                                ? entry.notes.slice(0, 100) + "..."
                                : entry.notes}
                            </span>
                          )}
                        </p>
                      </div>
                      <svg
                        className={`w-5 h-5 text-text-muted shrink-0 transition-transform ${
                          isExpanded ? "rotate-180" : ""
                        }`}
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M19 9l-7 7-7-7"
                        />
                      </svg>
                    </div>
                  </button>

                  {isExpanded && (
                    <div className="px-4 pb-4 border-t border-surface-light pt-3">
                      {entry.notes ? (
                        <p className="text-sm text-text whitespace-pre-wrap mb-4">
                          {entry.notes}
                        </p>
                      ) : (
                        <p className="text-sm text-text-muted italic mb-4">
                          No notes for this entry.
                        </p>
                      )}
                      <div className="flex items-center justify-between">
                        <span className="text-xs text-text-muted">
                          Mood: {MOOD_LABELS[entry.mood]}
                        </span>
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            handleDelete(entry.id);
                          }}
                          disabled={deletingId === entry.id}
                          className="text-xs text-red-400 hover:text-red-300 transition-colors disabled:opacity-50"
                        >
                          {deletingId === entry.id ? "Deleting..." : "Delete Entry"}
                        </button>
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}
