"use client";

import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  Package,
  Loader2,
  Pencil,
  Trash2,
  Check,
  X,
  UtensilsCrossed,
  TreePine,
  Film,
  ShoppingBag,
  Dumbbell,
  Landmark,
  Coffee,
} from "lucide-react";
import type { IdeaCategory } from "@/types";

export interface MyIdea {
  id: string;
  content: string;
  createdAt: string;
  category?: string | null;
  timeSlot?: string | null;
  estimatedMinutes?: number | null;
  outdoor?: boolean | null;
  searchQuery?: string | null;
  searchType?: string | null;
}

const CATEGORY_CONFIG: Record<
  IdeaCategory,
  { icon: typeof UtensilsCrossed; color: string; label: string }
> = {
  dining: { icon: UtensilsCrossed, color: "text-orange-400", label: "美食" },
  outdoor: { icon: TreePine, color: "text-emerald-400", label: "户外" },
  entertainment: { icon: Film, color: "text-sky-400", label: "娱乐" },
  shopping: { icon: ShoppingBag, color: "text-pink-400", label: "购物" },
  sports: { icon: Dumbbell, color: "text-amber-400", label: "运动" },
  culture: { icon: Landmark, color: "text-violet-400", label: "文化" },
  relaxation: { icon: Coffee, color: "text-teal-400", label: "休闲" },
};

function CategoryBadge({ category }: { category?: string | null }) {
  if (!category) return <span className="text-sm">💡</span>;
  const cfg = CATEGORY_CONFIG[category as IdeaCategory];
  if (!cfg) return <span className="text-sm">💡</span>;
  const Icon = cfg.icon;
  return <Icon size={14} className={`shrink-0 ${cfg.color}`} />;
}

function DurationLabel({ minutes }: { minutes?: number | null }) {
  if (!minutes) return null;
  const display = minutes >= 60 ? `${(minutes / 60).toFixed(minutes % 60 === 0 ? 0 : 1)}h` : `${minutes}min`;
  return (
    <span className="shrink-0 rounded-md bg-elevated px-1.5 py-0.5 text-[10px] font-medium text-dim">
      ~{display}
    </span>
  );
}

function MyIdeaItem({
  idea,
  onEdit,
  onDelete,
}: {
  idea: MyIdea;
  onEdit: (id: string, content: string) => Promise<void>;
  onDelete: (id: string) => Promise<void>;
}) {
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState(idea.content);
  const [saving, setSaving] = useState(false);

  const handleSave = async () => {
    if (!draft.trim() || saving) return;
    setSaving(true);
    await onEdit(idea.id, draft);
    setSaving(false);
    setEditing(false);
  };

  return (
    <motion.div
      layout
      className="flex items-center gap-2 rounded-xl bg-surface/60 px-3 py-2.5 ring-1 ring-border/80"
      initial={{ opacity: 0, y: -8 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, x: -20 }}
    >
      {editing ? (
        <>
          <input
            type="text"
            value={draft}
            onChange={(e) => setDraft(e.target.value.slice(0, 200))}
            onKeyDown={(e) => { if (e.key === "Enter") handleSave(); if (e.key === "Escape") { setEditing(false); setDraft(idea.content); } }}
            maxLength={200}
            autoFocus
            className="h-8 min-w-0 flex-1 rounded-lg bg-elevated px-2.5 text-sm text-foreground outline-none ring-1 ring-border focus:ring-2 focus:ring-purple-600/50"
          />
          <button
            onClick={handleSave}
            disabled={saving || !draft.trim()}
            className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-purple-600 text-white disabled:opacity-40"
          >
            {saving ? <Loader2 size={12} className="animate-spin" /> : <Check size={12} />}
          </button>
          <button
            onClick={() => { setEditing(false); setDraft(idea.content); }}
            className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-elevated text-muted"
          >
            <X size={12} />
          </button>
        </>
      ) : (
        <>
          <CategoryBadge category={idea.category} />
          <p className="min-w-0 flex-1 truncate text-sm text-secondary">{idea.content}</p>
          <DurationLabel minutes={idea.estimatedMinutes} />
          <button
            onClick={() => setEditing(true)}
            className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg text-muted transition-colors active:bg-elevated active:text-purple-400"
          >
            <Pencil size={12} />
          </button>
          <button
            onClick={() => onDelete(idea.id)}
            className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg text-muted transition-colors active:bg-elevated active:text-rose-400"
          >
            <Trash2 size={12} />
          </button>
        </>
      )}
    </motion.div>
  );
}

export default function BlindboxMyIdeas({
  ideas,
  onEdit,
  onDelete,
}: {
  ideas: MyIdea[];
  onEdit: (id: string, content: string) => Promise<void>;
  onDelete: (id: string) => Promise<void>;
}) {
  return (
    <motion.div
      className="mt-6 w-full max-w-sm"
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ delay: 0.2 }}
    >
      <div className="mb-2 flex items-center gap-2">
        <Package size={13} className="text-purple-400" />
        <h3 className="text-xs font-bold tracking-wider text-muted">
          我投入的想法（{ideas.length}）
        </h3>
        <div className="h-px flex-1 bg-border" />
      </div>
      <div className="flex flex-col gap-1.5">
        <AnimatePresence>
          {ideas.map((idea) => (
            <MyIdeaItem key={idea.id} idea={idea} onEdit={onEdit} onDelete={onDelete} />
          ))}
        </AnimatePresence>
      </div>
    </motion.div>
  );
}

export { CATEGORY_CONFIG, CategoryBadge, DurationLabel };
