"use client";

import { useEffect, useState } from "react";
import { Plus } from "lucide-react";
import { api } from "@/lib/api";
import type { FeishuSession } from "@/lib/types";
import SessionTable from "@/components/SessionTable";

export default function SessionsPage() {
  const [sessions, setSessions] = useState<FeishuSession[]>([]);
  const [title, setTitle] = useState("大本营周三答疑测试场次");
  const [teachers, setTeachers] = useState("院长, 辅导老师");
  const [sourceText, setSourceText] = useState("");

  async function load() {
    const data = await api.get<FeishuSession[]>("/sessions");
    setSessions(data);
  }

  async function createSession() {
    await api.post<FeishuSession>("/sessions", {
      title,
      teachers,
      source_text: sourceText || undefined,
      source_file_name: sourceText ? "manual_transcript.txt" : undefined
    });
    setSourceText("");
    await load();
  }

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

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-semibold text-ink">答疑场次</h1>
      </div>

      <div className="rounded-md border border-line bg-white p-4">
        <div className="grid gap-3 md:grid-cols-3">
          <label className="text-sm">
            <span className="mb-1 block text-slate-500">标题</span>
            <input
              value={title}
              onChange={(event) => setTitle(event.target.value)}
              className="h-10 w-full rounded-md border border-line px-3 outline-none focus:border-jade"
            />
          </label>
          <label className="text-sm">
            <span className="mb-1 block text-slate-500">老师</span>
            <input
              value={teachers}
              onChange={(event) => setTeachers(event.target.value)}
              className="h-10 w-full rounded-md border border-line px-3 outline-none focus:border-jade"
            />
          </label>
          <div className="flex items-end">
            <button
              onClick={createSession}
              className="inline-flex h-10 items-center gap-2 rounded-md bg-jade px-4 text-sm font-medium text-white hover:bg-teal-800"
            >
              <Plus className="h-4 w-4" aria-hidden />
              创建测试场次
            </button>
          </div>
        </div>
        <label className="mt-3 block text-sm">
          <span className="mb-1 block text-slate-500">转写稿</span>
          <textarea
            value={sourceText}
            onChange={(event) => setSourceText(event.target.value)}
            rows={5}
            className="w-full rounded-md border border-line px-3 py-2 outline-none focus:border-jade"
          />
        </label>
      </div>

      <SessionTable sessions={sessions} onChanged={load} />
    </div>
  );
}

