import React, { useEffect, useMemo, useState } from "react";
import ReactDOM from "react-dom/client";
import { Calendar, Map as MapIcon, Plus, Navigation } from "lucide-react";
import { MainTab, TaskCategory, TaskItem, ViewScope } from "./types";
import { PRESET_ORIGINS, buildRouteSummary } from "./geo";
import { MapViewport } from "./MapViewport";
import "./index.css";

const STORAGE_KEY = "geoplan_ts_tasks_v1";

function toISO(d: Date): string {
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(
    d.getDate()
  ).padStart(2, "0")}`;
}

function fromISO(iso: string): Date {
  const [y, m, d] = iso.split("-").map(Number);
  return new Date(y, (m || 1) - 1, d || 1);
}

function getWeekStart(d: Date): Date {
  const copy = new Date(d.getFullYear(), d.getMonth(), d.getDate());
  copy.setDate(copy.getDate() - copy.getDay());
  return copy;
}

const DEFAULT_TASKS: TaskItem[] = [
  {
    id: "t-1",
    title: "平和記念公園 現地視察",
    date: toISO(new Date()),
    time: "10:00",
    category: "現地訪問・視察",
    address: "広島県広島市中区中島町1-1",
    notes: "導線と休憩スペースを確認",
  },
  {
    id: "t-2",
    title: "八丁堀オフィス 定例ミーティング",
    date: toISO(new Date()),
    time: "14:30",
    category: "商談・打合せ",
    address: "広島県広島市中区八丁堀14-1",
    customOrigin: "広島県広島市中区中島町1-1",
    notes: "スケジュールと公開手順の確認",
  },
  {
    id: "t-3",
    title: "広島城 二の丸会場 下見",
    date: toISO(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 3)),
    time: "11:30",
    category: "イベント・会場",
    address: "広島県広島市中区基町21-1",
    notes: "搬入経路と受付位置を確認",
  },
];

const App: React.FC = () => {
  const [tasks, setTasks] = useState<TaskItem[]>(() => {
    try {
      const saved = localStorage.getItem(STORAGE_KEY);
      return saved ? (JSON.parse(saved) as TaskItem[]) : DEFAULT_TASKS;
    } catch {
      return DEFAULT_TASKS;
    }
  });

  const [tab, setTab] = useState<MainTab>("schedule");
  const [scope, setScope] = useState<ViewScope>("month");
  const [anchorDate, setAnchorDate] = useState<Date>(() => new Date());
  const [selectedDate, setSelectedDate] = useState<string>(() => toISO(new Date()));
  const [selectedTaskId, setSelectedTaskId] = useState<string | null>(() => DEFAULT_TASKS[0]?.id ?? null);
  const [originKey, setOriginKey] = useState<string>("hiroshima_station");

  const [title, setTitle] = useState("");
  const [date, setDate] = useState(() => toISO(new Date()));
  const [time, setTime] = useState("10:00");
  const [category, setCategory] = useState<TaskCategory>("商談・打合せ");
  const [address, setAddress] = useState("");
  const [customOrigin, setCustomOrigin] = useState("");
  const [notes, setNotes] = useState("");

  useEffect(() => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks));
  }, [tasks]);

  const globalOrigin = PRESET_ORIGINS[originKey] ?? PRESET_ORIGINS.hiroshima_station;

  const scopedTasks = useMemo(() => {
    return tasks.filter((t) => {
      const dt = fromISO(t.date);
      if (scope === "year") return dt.getFullYear() === anchorDate.getFullYear();
      if (scope === "month")
        return dt.getFullYear() === anchorDate.getFullYear() && dt.getMonth() === anchorDate.getMonth();
      if (scope === "week") {
        const s = getWeekStart(anchorDate);
        const e = new Date(s.getFullYear(), s.getMonth(), s.getDate() + 6, 23, 59, 59);
        return dt >= s && dt <= e;
      }
      return t.date === toISO(anchorDate);
    });
  }, [tasks, scope, anchorDate]);

  const activeRoute = useMemo(() => {
    const target = scopedTasks.find((t) => t.id === selectedTaskId) ?? scopedTasks[0] ?? null;
    return target ? buildRouteSummary(target, globalOrigin) : null;
  }, [scopedTasks, selectedTaskId, globalOrigin]);

  const handleAddTask = (e: React.FormEvent) => {
    e.preventDefault();
    if (!title.trim() || !address.trim()) return;
    const newItem: TaskItem = {
      id: `t-${Date.now()}`,
      title: title.trim(),
      date,
      time,
      category,
      address: address.trim(),
      customOrigin: customOrigin.trim() || undefined,
      notes: notes.trim() || undefined,
    };
    setTasks((prev) => [...prev, newItem]);
    setSelectedDate(date);
    setSelectedTaskId(newItem.id);
    setTitle("");
    setAddress("");
    setCustomOrigin("");
    setNotes("");
  };

  const stepPeriod = (dir: number) => {
    const d = anchorDate;
    if (scope === "year") setAnchorDate(new Date(d.getFullYear() + dir, d.getMonth(), 1));
    else if (scope === "month") setAnchorDate(new Date(d.getFullYear(), d.getMonth() + dir, 1));
    else if (scope === "week") setAnchorDate(new Date(d.getFullYear(), d.getMonth(), d.getDate() + dir * 7));
    else {
      const next = new Date(d.getFullYear(), d.getMonth(), d.getDate() + dir);
      setAnchorDate(next);
      setSelectedDate(toISO(next));
    }
  };

  const periodLabel = useMemo(() => {
    if (scope === "year") return `${anchorDate.getFullYear()}年`;
    if (scope === "month") return `${anchorDate.getFullYear()}年${anchorDate.getMonth() + 1}月`;
    if (scope === "week") {
      const s = getWeekStart(anchorDate);
      const e = new Date(s.getFullYear(), s.getMonth(), s.getDate() + 6);
      return `${s.getMonth() + 1}/${s.getDate()} 〜 ${e.getMonth() + 1}/${e.getDate()}`;
    }
    return toISO(anchorDate);
  }, [scope, anchorDate]);

  const monthDays = useMemo(() => {
    const y = anchorDate.getFullYear();
    const m = anchorDate.getMonth();
    const firstWeekday = new Date(y, m, 1).getDay();
    const total = new Date(y, m + 1, 0).getDate();
    const cells: { iso: string | null; day: number | null }[] = [];
    for (let i = 0; i < firstWeekday; i++) cells.push({ iso: null, day: null });
    for (let d = 1; d <= total; d++) {
      cells.push({
        iso: `${y}-${String(m + 1).padStart(2, "0")}-${String(d).padStart(2, "0")}`,
        day: d,
      });
    }
    return cells;
  }, [anchorDate]);

  return (
    <div className="min-h-screen flex flex-col">
      <header className="bg-white border-b border-slate-200 px-4 py-3 flex flex-wrap items-center justify-between gap-3">
        <div className="flex items-center gap-2">
          <span className="font-bold text-lg text-slate-900">GeoPlan TS</span>
          <span className="text-xs px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200">
            APIキー不要・TypeScript
          </span>
        </div>

        <div className="flex items-center gap-1 bg-slate-100 p-1 rounded-xl">
          {(["year", "month", "week", "day"] as ViewScope[]).map((sc) => (
            <button
              key={sc}
              type="button"
              onClick={() => setScope(sc)}
              className={`px-3 py-1 rounded-lg text-xs font-semibold ${
                scope === sc ? "bg-indigo-600 text-white" : "text-slate-600 hover:text-slate-900"
              }`}
            >
              {sc === "year" ? "年間" : sc === "month" ? "月間" : sc === "week" ? "週" : "1日"}
            </button>
          ))}
        </div>

        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={() => setTab("schedule")}
            className={`px-3 py-1.5 rounded-xl text-xs font-semibold flex items-center gap-1 ${
              tab === "schedule" ? "bg-indigo-600 text-white" : "bg-slate-100 text-slate-700"
            }`}
          >
            <Calendar className="w-3.5 h-3.5" /> スケジュール
          </button>
          <button
            type="button"
            onClick={() => setTab("map")}
            className={`px-3 py-1.5 rounded-xl text-xs font-semibold flex items-center gap-1 ${
              tab === "map" ? "bg-indigo-600 text-white" : "bg-slate-100 text-slate-700"
            }`}
          >
            <MapIcon className="w-3.5 h-3.5" /> マップ
          </button>
        </div>
      </header>

      <div className="bg-slate-100/80 border-b border-slate-200 px-4 py-2 flex flex-wrap items-center justify-between gap-2 text-xs">
        <div className="flex items-center gap-2">
          <button type="button" onClick={() => stepPeriod(-1)} className="px-2.5 py-1 bg-white border rounded-lg font-bold">
            ‹
          </button>
          <button
            type="button"
            onClick={() => {
              const now = new Date();
              setAnchorDate(now);
              setSelectedDate(toISO(now));
            }}
            className="px-2.5 py-1 bg-white border rounded-lg font-semibold"
          >
            今日
          </button>
          <button type="button" onClick={() => stepPeriod(1)} className="px-2.5 py-1 bg-white border rounded-lg font-bold">
            ›
          </button>
          <span className="font-bold text-sm text-slate-800 ml-1">{periodLabel}</span>
          <span className="text-indigo-700 font-semibold ml-1">（表示中 {scopedTasks.length} 件）</span>
        </div>

        <div className="flex items-center gap-2">
          <span className="text-slate-600 font-medium">基準出発地:</span>
          <select
            value={originKey}
            onChange={(e) => setOriginKey(e.target.value)}
            className="bg-white border border-slate-200 rounded-lg px-2.5 py-1 text-slate-800"
          >
            {Object.entries(PRESET_ORIGINS).map(([k, v]) => (
              <option key={k} value={k}>
                {v.label}
              </option>
            ))}
          </select>
        </div>
      </div>

      <main className="flex-1 max-w-7xl w-full mx-auto p-4 grid grid-cols-1 lg:grid-cols-12 gap-5">
        <section className="lg:col-span-8 space-y-4">
          {tab === "schedule" ? (
            <div className="bg-white rounded-2xl border border-slate-200 p-4 shadow-sm">
              <div className="grid grid-cols-7 gap-1.5">
                {monthDays.map((cell, idx) => {
                  if (!cell.iso || !cell.day) {
                    return <div key={`empty-${idx}`} className="h-20 rounded-xl bg-slate-50/50" />;
                  }
                  const dayCount = tasks.filter((t) => t.date === cell.iso).length;
                  const active = cell.iso === selectedDate;
                  return (
                    <button
                      key={cell.iso}
                      type="button"
                      onClick={() => {
                        setSelectedDate(cell.iso!);
                        setDate(cell.iso!);
                      }}
                      className={`h-20 p-1.5 rounded-xl border text-left flex flex-col justify-between ${
                        active ? "border-indigo-600 bg-indigo-50/60" : "border-slate-100 hover:border-slate-300"
                      }`}
                    >
                      <span className="text-xs font-bold text-slate-700">{cell.day}</span>
                      {dayCount > 0 && (
                        <span className="text-[11px] font-semibold text-indigo-700 bg-indigo-100 px-1.5 py-0.5 rounded w-fit">
                          {dayCount}件
                        </span>
                      )}
                    </button>
                  );
                })}
              </div>
            </div>
          ) : (
            <MapViewport
              tasks={scopedTasks}
              selectedTaskId={selectedTaskId}
              globalOrigin={globalOrigin}
              onSelectTask={(id) => setSelectedTaskId(id)}
            />
          )}

          <form onSubmit={handleAddTask} className="bg-white rounded-2xl border border-slate-200 p-4 shadow-sm space-y-3">
            <div className="text-sm font-bold text-slate-900 flex items-center gap-1.5">
              <Plus className="w-4 h-4 text-indigo-600" /> 住所付きタスク・予定を追加
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-2.5 text-xs">
              <input
                type="text"
                required
                placeholder="予定名（例: 紙屋町 打合せ）"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                className="border border-slate-200 rounded-xl px-3 py-2"
              />
              <input
                type="date"
                required
                value={date}
                onChange={(e) => setDate(e.target.value)}
                className="border border-slate-200 rounded-xl px-3 py-2"
              />
              <input
                type="time"
                value={time}
                onChange={(e) => setTime(e.target.value)}
                className="border border-slate-200 rounded-xl px-3 py-2"
              />
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-2.5 text-xs">
              <input
                type="text"
                required
                placeholder="住所・場所（例: 広島市中区紙屋町1丁目）"
                value={address}
                onChange={(e) => setAddress(e.target.value)}
                className="sm:col-span-2 border border-slate-200 rounded-xl px-3 py-2"
              />
              <select
                value={category}
                onChange={(e) => setCategory(e.target.value as TaskCategory)}
                className="border border-slate-200 rounded-xl px-3 py-2"
              >
                <option value="商談・打合せ">商談・打合せ</option>
                <option value="現地訪問・視察">現地訪問・視察</option>
                <option value="イベント・会場">イベント・会場</option>
                <option value="個人・その他">個人・その他</option>
              </select>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5 text-xs">
              <input
                type="text"
                placeholder="個別出発地（任意・未入力なら基準出発地）"
                value={customOrigin}
                onChange={(e) => setCustomOrigin(e.target.value)}
                className="border border-slate-200 rounded-xl px-3 py-2"
              />
              <input
                type="text"
                placeholder="メモ（任意）"
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                className="border border-slate-200 rounded-xl px-3 py-2"
              />
            </div>
            <div className="flex justify-end">
              <button
                type="submit"
                className="px-4 py-2 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-semibold"
              >
                登録する
              </button>
            </div>
          </form>
        </section>

        <aside className="lg:col-span-4 space-y-4">
          <div className="bg-white rounded-2xl border border-slate-200 p-4 shadow-sm space-y-2">
            <div className="text-sm font-bold text-slate-900 flex items-center gap-1.5">
              <Navigation className="w-4 h-4 text-rose-600" /> 出発地〜ピン ルート情報
            </div>
            {activeRoute ? (
              <div className="text-xs space-y-1 text-slate-700">
                <div>出発: <strong>{activeRoute.origin.label}</strong></div>
                <div>目的地: <strong>{activeRoute.destination.label}</strong></div>
                <div className="pt-1 font-semibold text-indigo-700">
                  距離目安 {activeRoute.distanceKm.toFixed(1)} km / 車 約{activeRoute.carMinutes}分・徒歩 約{activeRoute.walkMinutes}分
                </div>
              </div>
            ) : (
              <p className="text-xs text-slate-500">表示スコープ内に予定がありません。</p>
            )}
          </div>

          <div className="bg-white rounded-2xl border border-slate-200 p-4 shadow-sm space-y-2.5">
            <h2 className="text-sm font-bold text-slate-900">表示スコープ内の予定（{scopedTasks.length}件）</h2>
            <div className="space-y-2">
              {scopedTasks.map((t) => (
                <div
                  key={t.id}
                  onClick={() => {
                    setSelectedTaskId(t.id);
                    setTab("map");
                  }}
                  className={`p-3 rounded-xl border cursor-pointer text-xs space-y-1 ${
                    selectedTaskId === t.id ? "border-indigo-600 bg-indigo-50/50" : "border-slate-200 hover:border-slate-300"
                  }`}
                >
                  <div className="font-bold text-indigo-700">
                    {t.date} {t.time} ・ {t.category}
                  </div>
                  <div className="font-bold text-slate-900">{t.title}</div>
                  <div className="text-slate-600">📍 {t.address}</div>
                </div>
              ))}
            </div>
          </div>
        </aside>
      </main>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);