"use client";

import { useState } from "react";
import { X, Sparkles, Loader2 } from "lucide-react";
import Modal from "@/components/Modal";
import Button from "@/components/Button";
import PoiSearchField from "@/components/PoiSearchField";
import type { PlanItem, WeekendPlanData } from "@/types";

interface AltSuggestion {
  activity: string;
  poi: string;
  address: string;
  lat: number;
  lng: number;
  reason: string;
}

interface PlanItemEditModalProps {
  open: boolean;
  editingItem: { dayIndex: number; itemIndex: number } | null;
  draft: PlanItem | null;
  days: WeekendPlanData[];
  location?: string;
  onDraftChange: (draft: PlanItem) => void;
  onSave: () => void;
  onClose: () => void;
  onMoveToDayIndex: (targetDayIndex: number) => void;
}

export default function PlanItemEditModal({
  open,
  editingItem,
  draft,
  days,
  location,
  onDraftChange,
  onSave,
  onClose,
  onMoveToDayIndex,
}: PlanItemEditModalProps) {
  const [suggestingAlt, setSuggestingAlt] = useState(false);
  const [altSuggestions, setAltSuggestions] = useState<AltSuggestion[]>([]);

  async function handleSuggestAlt() {
    if (!draft || suggestingAlt) return;
    setSuggestingAlt(true);
    try {
      const res = await fetch("/api/blindbox/plan/suggest-item", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ activity: draft.activity, time: draft.time, location }),
      });
      if (!res.ok) return;
      const data = await res.json();
      setAltSuggestions(data.suggestions ?? []);
    } finally {
      setSuggestingAlt(false);
    }
  }

  function handleClose() {
    setAltSuggestions([]);
    onClose();
  }

  return (
    <Modal open={open} onClose={handleClose} variant="sheet">
      {draft && editingItem && (
        <div className="flex flex-col gap-4">
          <div className="flex items-center justify-between">
            <h3 className="text-sm font-bold text-heading">编辑活动</h3>
            <button onClick={handleClose} aria-label="关闭" className="text-muted active:text-foreground">
              <X size={16} />
            </button>
          </div>

          <div className="flex flex-col gap-3">
            <label className="flex flex-col gap-1">
              <span className="text-[11px] font-medium text-muted">活动名称</span>
              <input
                type="text"
                value={draft.activity}
                onChange={(e) => onDraftChange({ ...draft, activity: e.target.value })}
                className="h-9 rounded-lg bg-elevated px-3 text-sm text-foreground outline-none ring-1 ring-border focus:ring-purple-600"
              />
            </label>

            <div className="flex gap-2">
              <label className="flex flex-1 flex-col gap-1">
                <span className="text-[11px] font-medium text-muted">时间</span>
                <input
                  type="time"
                  value={draft.time}
                  onChange={(e) => onDraftChange({ ...draft, time: e.target.value })}
                  className="h-9 rounded-lg bg-elevated px-3 text-sm text-foreground outline-none ring-1 ring-border focus:ring-purple-600"
                />
              </label>
              <label className="flex flex-1 flex-col gap-1">
                <span className="text-[11px] font-medium text-muted">时长（分钟）</span>
                <input
                  type="number"
                  step={15}
                  min={15}
                  value={draft.duration}
                  onChange={(e) => onDraftChange({ ...draft, duration: Number(e.target.value) })}
                  className="h-9 rounded-lg bg-elevated px-3 text-sm text-foreground outline-none ring-1 ring-border focus:ring-purple-600"
                />
              </label>
            </div>

            <PoiSearchField
              key={`${editingItem.dayIndex}-${editingItem.itemIndex}`}
              poi={draft.poi}
              address={draft.address}
              location={location}
              onSelect={(s) => onDraftChange({ ...draft, poi: s.name, address: s.address, lat: s.lat, lng: s.lng })}
            />

            {/* AI alternative suggestions */}
            {altSuggestions.length === 0 ? (
              <button
                onClick={handleSuggestAlt}
                disabled={suggestingAlt}
                className="flex items-center gap-1.5 self-start text-xs font-medium text-purple-400/70 active:text-purple-400 disabled:opacity-40"
              >
                {suggestingAlt
                  ? <><Loader2 size={12} className="animate-spin" /> 正在推荐...</>
                  : <><Sparkles size={12} /> AI 推荐替代方案</>}
              </button>
            ) : (
              <div className="flex flex-col gap-1.5">
                <span className="text-[11px] font-medium text-muted">选一个替代方案</span>
                {altSuggestions.map((alt, i) => (
                  <button
                    key={i}
                    onClick={() => {
                      onDraftChange({ ...draft, ...alt });
                      setAltSuggestions([]);
                    }}
                    className="rounded-lg bg-elevated px-3 py-2 text-left ring-1 ring-border active:ring-purple-500"
                  >
                    <p className="text-xs font-bold text-heading">{alt.activity}</p>
                    <p className="truncate text-[10px] text-muted">{alt.poi}</p>
                    <p className="text-[10px] text-dim italic">{alt.reason}</p>
                  </button>
                ))}
                <button onClick={() => setAltSuggestions([])} className="self-start text-[10px] text-dim">取消</button>
              </div>
            )}

            {days.length > 1 && (
              <label className="flex flex-col gap-1">
                <span className="text-[11px] font-medium text-muted">移动到其他天</span>
                <select
                  value={editingItem.dayIndex}
                  onChange={(e) => onMoveToDayIndex(Number(e.target.value))}
                  className="h-9 rounded-lg bg-elevated px-3 text-sm text-foreground outline-none ring-1 ring-border focus:ring-purple-600"
                >
                  {days.map((day, i) => (
                    <option key={day.date} value={i}>
                      {day.date}
                      {i === editingItem.dayIndex ? "（当前）" : ""}
                    </option>
                  ))}
                </select>
              </label>
            )}
          </div>

          <Button onClick={onSave} variant="purple" shape="pill">
            保存
          </Button>
        </div>
      )}
    </Modal>
  );
}
