"use client";

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

type Record = {
  record_id: string;
  category: string;
  content: string;
  confidentiality_level: string;
  created_at: string;
};

type Analysis = {
  analysis_id: string;
  query_date: string;
  result: string;
  model_used: string;
  created_at: string;
};

type Message = {
  role: "user" | "assistant";
  content: string;
};

export default function Home() {
  const [tab, setTab] = useState<"chat" | "data" | "analysis">("chat");
  const [records, setRecords] = useState<Record[]>([]);
  const [analyses, setAnalyses] = useState<Analysis[]>([]);
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [dataLoading, setDataLoading] = useState(false);
  const chatEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (tab === "data" || tab === "analysis") {
      fetchRecords();
    }
  }, [tab]);

  useEffect(() => {
    chatEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  async function fetchRecords() {
    setDataLoading(true);
    try {
      const res = await fetch("/api/records");
      const data = await res.json();
      if (data.records) setRecords(data.records);
      if (data.analyses) setAnalyses(data.analyses);
    } catch {
      console.error("データ取得エラー");
    }
    setDataLoading(false);
  }

  async function sendMessage(e: React.FormEvent) {
    e.preventDefault();
    if (!input.trim() || loading) return;

    const question = input.trim();
    setInput("");
    setMessages((prev) => [...prev, { role: "user", content: question }]);
    setLoading(true);

    try {
      const res = await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ question }),
      });
      const data = await res.json();
      setMessages((prev) => [
        ...prev,
        { role: "assistant", content: data.answer || data.error },
      ]);
    } catch {
      setMessages((prev) => [
        ...prev,
        { role: "assistant", content: "エラーが発生しました" },
      ]);
    }
    setLoading(false);
  }

  return (
    <div className="max-w-5xl mx-auto p-4">
      <header className="mb-6">
        <h1 className="text-2xl font-bold text-white">
          Confidential AI Dashboard
        </h1>
        <p className="text-gray-400 text-sm mt-1">
          社内極秘データ分析 - BigQuery + Gemini
        </p>
      </header>

      <nav className="flex gap-1 mb-6 border-b border-gray-800">
        {(
          [
            ["chat", "AI に質問"],
            ["data", "データ一覧"],
            ["analysis", "分析履歴"],
          ] as const
        ).map(([key, label]) => (
          <button
            key={key}
            onClick={() => setTab(key)}
            className={`px-4 py-2 text-sm font-medium rounded-t transition-colors ${
              tab === key
                ? "bg-gray-800 text-white border-b-2 border-blue-500"
                : "text-gray-400 hover:text-gray-200"
            }`}
          >
            {label}
          </button>
        ))}
      </nav>

      {tab === "chat" && (
        <div className="flex flex-col h-[calc(100vh-200px)]">
          <div className="flex-1 overflow-y-auto space-y-4 mb-4">
            {messages.length === 0 && (
              <div className="text-center text-gray-500 mt-20">
                <p className="text-lg mb-2">
                  BigQuery のデータについて質問できます
                </p>
                <div className="flex flex-wrap gap-2 justify-center mt-4">
                  {[
                    "売上の状況を教えて",
                    "最も注目すべきポイントは？",
                    "コストに関する懸念事項は？",
                    "全体のサマリーを作成して",
                  ].map((q) => (
                    <button
                      key={q}
                      onClick={() => setInput(q)}
                      className="px-3 py-1.5 bg-gray-800 text-gray-300 rounded-lg text-sm hover:bg-gray-700 transition-colors"
                    >
                      {q}
                    </button>
                  ))}
                </div>
              </div>
            )}
            {messages.map((msg, i) => (
              <div
                key={i}
                className={`flex ${msg.role === "user" ? "justify-end" : "justify-start"}`}
              >
                <div
                  className={`max-w-[80%] rounded-lg px-4 py-3 ${
                    msg.role === "user"
                      ? "bg-blue-600 text-white"
                      : "bg-gray-800 text-gray-100"
                  }`}
                >
                  <pre className="whitespace-pre-wrap text-sm font-sans">
                    {msg.content}
                  </pre>
                </div>
              </div>
            ))}
            {loading && (
              <div className="flex justify-start">
                <div className="bg-gray-800 rounded-lg px-4 py-3 text-gray-400">
                  <span className="animate-pulse">分析中...</span>
                </div>
              </div>
            )}
            <div ref={chatEndRef} />
          </div>

          <form onSubmit={sendMessage} className="flex gap-2">
            <input
              type="text"
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder="データについて質問を入力..."
              className="flex-1 bg-gray-800 border border-gray-700 rounded-lg px-4 py-3 text-white placeholder-gray-500 focus:outline-none focus:border-blue-500"
              disabled={loading}
            />
            <button
              type="submit"
              disabled={loading || !input.trim()}
              className="bg-blue-600 text-white px-6 py-3 rounded-lg font-medium hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              送信
            </button>
          </form>
        </div>
      )}

      {tab === "data" && (
        <div>
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold">
              格納データ ({records.length}件)
            </h2>
            <button
              onClick={fetchRecords}
              className="text-sm text-blue-400 hover:text-blue-300"
            >
              更新
            </button>
          </div>
          {dataLoading ? (
            <p className="text-gray-400 animate-pulse">読み込み中...</p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-gray-800 text-gray-400">
                    <th className="text-left py-2 px-3">ID</th>
                    <th className="text-left py-2 px-3">カテゴリ</th>
                    <th className="text-left py-2 px-3">内容</th>
                    <th className="text-left py-2 px-3">機密レベル</th>
                    <th className="text-left py-2 px-3">日時</th>
                  </tr>
                </thead>
                <tbody>
                  {records.map((r) => (
                    <tr
                      key={r.record_id}
                      className="border-b border-gray-900 hover:bg-gray-900/50"
                    >
                      <td className="py-2 px-3 text-gray-400 font-mono text-xs">
                        {r.record_id}
                      </td>
                      <td className="py-2 px-3">
                        <span className="bg-gray-800 text-gray-300 px-2 py-0.5 rounded text-xs">
                          {r.category}
                        </span>
                      </td>
                      <td className="py-2 px-3 max-w-md truncate">
                        {r.content}
                      </td>
                      <td className="py-2 px-3">
                        <span className="bg-red-900/30 text-red-400 px-2 py-0.5 rounded text-xs">
                          {r.confidentiality_level}
                        </span>
                      </td>
                      <td className="py-2 px-3 text-gray-400 text-xs">
                        {r.created_at}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {records.length === 0 && (
                <p className="text-gray-500 text-center py-8">
                  データがありません
                </p>
              )}
            </div>
          )}
        </div>
      )}

      {tab === "analysis" && (
        <div>
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold">
              分析履歴 ({analyses.length}件)
            </h2>
            <button
              onClick={fetchRecords}
              className="text-sm text-blue-400 hover:text-blue-300"
            >
              更新
            </button>
          </div>
          {dataLoading ? (
            <p className="text-gray-400 animate-pulse">読み込み中...</p>
          ) : (
            <div className="space-y-4">
              {analyses.map((a) => (
                <div key={a.analysis_id} className="bg-gray-900 rounded-lg p-4">
                  <div className="flex items-center gap-3 mb-3">
                    <span className="text-xs text-gray-400">
                      {a.created_at}
                    </span>
                    <span className="bg-gray-800 text-gray-400 px-2 py-0.5 rounded text-xs">
                      {a.model_used}
                    </span>
                  </div>
                  <pre className="whitespace-pre-wrap text-sm text-gray-200 font-sans leading-relaxed">
                    {a.result}
                  </pre>
                </div>
              ))}
              {analyses.length === 0 && (
                <p className="text-gray-500 text-center py-8">
                  分析履歴がありません
                </p>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  );
}
