"use client";

import { useState, useEffect } from "react";

export default function MissionBriefsPage() {
  const [morningBriefs, setMorningBriefs] = useState<any[]>([]);
  const [eodBriefs, setEodBriefs] = useState<any[]>([]);
  const [amunBriefs, setAmunBriefs] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeView, setActiveView] = useState<"mission" | "morning" | "eod" | "amun">("mission");

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

  const fetchAllBriefs = async () => {
    setLoading(true);
    try {
      const [mRes, eRes, aRes] = await Promise.all([
        fetch("/api/morning"),
        fetch("/api/eod"),
        fetch("/api/amun")
      ]);
      const [mData, eData, aData] = await Promise.all([
        mRes.json(),
        eRes.json(),
        aRes.json()
      ]);
      setMorningBriefs(Array.isArray(mData) ? mData : []);
      setEodBriefs(Array.isArray(eData) ? eData : []);
      setAmunBriefs(Array.isArray(aData) ? aData : []);
    } catch (e) {
      console.error(e);
    }
    setLoading(false);
  };

  const formatMorning = (data: any) => `☀️ MORNING - ${data.date}

🌤️ ${data.weather || ''}

📊 BTC: $${data.market?.BTC} (${data.market?.btcChange})
   ETH: $${data.market?.ETH} (${data.market?.ethChange})
   SOL: $${data.market?.SOL} (${data.market?.solChange})

🎯 ${data.priorities?.map((p: string, i: number) => `${i + 1}. ${p}`).join('\n   ') || ''}

💰 ${data.goal || ''}`;

  const formatEOD = (data: any) => `🌙 EOD - ${data.date}

✅ ${data.completed?.map((c: string) => `- ${c}`).join('\n') || ''}

📊 ${Object.entries(data.progress || {}).map(([k, v]) => `${k}: ${v}`).join('\n') || ''}

🧠 ${Object.entries(data.council || {}).map(([k, v]) => `- ${k}: ${v}`).join('\n') || ''}`;

  const formatAmun = (data: any) => `👑 AMUN - ${data.date}

🔍 ${data.tests?.map((t: string) => `- ${t}`).join('\n') || ''}

🐛 ${data.bugs?.map((b: string) => `- ${b}`).join('\n') || ''}

📊 ${data.quality || ''}

💡 ${data.recommendations?.map((r: string) => `- ${r}`).join('\n') || ''}`;

  const getLatest = () => {
    const latestMorning = morningBriefs[0];
    const latestEOD = eodBriefs[0];
    const latestAmun = amunBriefs[0];
    
    return { latestMorning, latestEOD, latestAmun };
  };

  const { latestMorning, latestEOD, latestAmun } = getLatest();

  return (
    <div className="p-6">
      <h1 className="text-2xl font-bold mb-6">📋 Mission Control Briefs</h1>
      
      {/* Navigation */}
      <div className="flex gap-2 mb-6 flex-wrap">
        <button
          onClick={() => setActiveView("mission")}
          className={`px-4 py-2 rounded-lg font-medium ${
            activeView === "mission" ? "bg-brand-pink text-white" : "bg-white/10 text-white/70 hover:bg-white/20"
          }`}
        >
          🎯 Mission
        </button>
        <button
          onClick={() => setActiveView("morning")}
          className={`px-4 py-2 rounded-lg font-medium ${
            activeView === "morning" ? "bg-brand-pink text-white" : "bg-white/10 text-white/70 hover:bg-white/20"
          }`}
        >
          ☀️ Morning ({morningBriefs.length})
        </button>
        <button
          onClick={() => setActiveView("eod")}
          className={`px-4 py-2 rounded-lg font-medium ${
            activeView === "eod" ? "bg-brand-pink text-white" : "bg-white/10 text-white/70 hover:bg-white/20"
          }`}
        >
          🌙 EOD ({eodBriefs.length})
        </button>
        <button
          onClick={() => setActiveView("amun")}
          className={`px-4 py-2 rounded-lg font-medium ${
            activeView === "amun" ? "bg-brand-pink text-white" : "bg-white/10 text-white/70 hover:bg-white/20"
          }`}
        >
          👑 Amun ({amunBriefs.length})
        </button>
      </div>

      {loading ? (
        <div className="text-white/50">Loading...</div>
      ) : (
        <>
          {/* Mission View - Latest from all */}
          {activeView === "mission" && (
            <div className="space-y-4">
              <h2 className="text-xl font-semibold">🎯 Latest Overview</h2>
              
              {latestMorning && (
                <div className="bg-white/10 rounded-lg p-4">
                  <h3 className="text-lg font-medium mb-2">☀️ Latest Morning</h3>
                  <pre className="whitespace-pre-wrap text-sm">{formatMorning(latestMorning)}</pre>
                </div>
              )}
              
              {latestEOD && (
                <div className="bg-white/10 rounded-lg p-4">
                  <h3 className="text-lg font-medium mb-2">🌙 Latest EOD</h3>
                  <pre className="whitespace-pre-wrap text-sm">{formatEOD(latestEOD)}</pre>
                </div>
              )}
              
              {latestAmun && (
                <div className="bg-white/10 rounded-lg p-4">
                  <h3 className="text-lg font-medium mb-2">👑 Latest Amun</h3>
                  <pre className="whitespace-pre-wrap text-sm">{formatAmun(latestAmun)}</pre>
                </div>
              )}
              
              {!latestMorning && !latestEOD && !latestAmun && (
                <div className="text-white/50">No briefs yet. POST to /api/morning, /api/eod, or /api/amun</div>
              )}
            </div>
          )}

          {/* Morning Briefs */}
          {activeView === "morning" && (
            <div className="space-y-4">
              <h2 className="text-xl font-semibold">☀️ Morning Briefs</h2>
              {morningBriefs.length === 0 ? (
                <div className="text-white/50">No morning briefs yet</div>
              ) : (
                morningBriefs.map((brief: any, i: number) => (
                  <div key={i} className="bg-white/10 rounded-lg p-4">
                    <pre className="whitespace-pre-wrap text-sm">{formatMorning(brief)}</pre>
                  </div>
                ))
              )}
            </div>
          )}

          {/* EOD Briefs */}
          {activeView === "eod" && (
            <div className="space-y-4">
              <h2 className="text-xl font-semibold">🌙 End of Day Briefs</h2>
              {eodBriefs.length === 0 ? (
                <div className="text-white/50">No EOD briefs yet</div>
              ) : (
                eodBriefs.map((brief: any, i: number) => (
                  <div key={i} className="bg-white/10 rounded-lg p-4">
                    <pre className="whitespace-pre-wrap text-sm">{formatEOD(brief)}</pre>
                  </div>
                ))
              )}
            </div>
          )}

          {/* Amun Sessions */}
          {activeView === "amun" && (
            <div className="space-y-4">
              <h2 className="text-xl font-semibold">👑 Amun QA Sessions</h2>
              {amunBriefs.length === 0 ? (
                <div className="text-white/50">No Amun sessions yet</div>
              ) : (
                amunBriefs.map((brief: any, i: number) => (
                  <div key={i} className="bg-white/10 rounded-lg p-4">
                    <pre className="whitespace-pre-wrap text-sm">{formatAmun(brief)}</pre>
                  </div>
                ))
              )}
            </div>
          )}
        </>
      )}
    </div>
  );
}
