import { useState, useEffect, useCallback, useContext, useRef } from "react";
import { AuthContext } from "./AuthContext";
import { Search } from "lucide-react";

// Import pages/views
import Login from "./pages/Login";
import Register from "./pages/Register";
import ProfilePage from "./pages/ProfilePage";

// Import refactored components
import CreateModal from "./components/CreateModal";
import BeanForm from "./components/BeanForm";
import BrewForm from "./components/BrewForm";
import BeanDetail from "./components/BeanDetail";
import BrewCard from "./components/BrewCard";
import BottomNav from "./components/BottomNav";
import IosPromptModal from "./components/IosPromptModal";
import UpdatePrompt from "./components/UpdatePrompt";
import SyncIndicator from "./components/SyncIndicator";


// Import constants
import { METHODS, METHOD_LABELS, METHOD_ICONS, METHOD_COLORS } from "./constants";

// ─── Storage helpers ───
const STORAGE_KEY = "coffee-logbook-data";
const defaultData = { beans: [], brewLogs: [], lastSyncedAt: null };

const storage = {
  get: async (key) => {
    try {
      const val = localStorage.getItem(key);
      return val ? { value: val } : null;
    } catch { return null; }
  },
  set: async (key, val) => {
    try { localStorage.setItem(key, val); } catch (e) { console.error("Storage set failed:", e); }
  }
};

async function loadData() {
  try {
    const result = await storage.get(STORAGE_KEY);
    if (result) {
      const parsed = JSON.parse(result.value);
      return { beans: parsed.beans || [], brewLogs: parsed.brewLogs || [], lastSyncedAt: parsed.lastSyncedAt || null };
    }
    return defaultData;
  } catch { return defaultData; }
}

async function saveData(data) {
  try { await storage.set(STORAGE_KEY, JSON.stringify(data)); }
  catch (e) { console.error("Save failed:", e); }
}

const uid = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 7);

const LoadingScreen = () => (
  <div className="w-full max-w-[480px] mx-auto min-h-screen border-x border-[#E8DFD3] dark:border-[#3B2217] bg-[#FAF6F1] dark:bg-[#150B07] max-sm:border-x-0 flex items-center justify-center transition-colors duration-200">
    <div className="text-center text-[#9C8B7A] dark:text-[#C8B9A6]"><div className="text-4xl">☕</div><div className="mt-2 text-sm">Loading…</div></div>
  </div>
);

// ─── Main App ───
export default function CoffeeLogbook() {
  const { token, user, loading, logout } = useContext(AuthContext);
  const [authView, setAuthView] = useState("login");
  const [data, setData] = useState(null);
  const [view, setView] = useState("dashboard");
  const [modal, setModal] = useState(null);
  const [createOpen, setCreateOpen] = useState(false);
  const [selectedBean, setSelectedBean] = useState(null);
  const [brewFilter, setBrewFilter] = useState("all");
  const [editingBean, setEditingBean] = useState(null);
  const [brewSearchQuery, setBrewSearchQuery] = useState("");

  const [isOnline, setIsOnline] = useState(navigator.onLine);
  const [syncing, setSyncing] = useState(false);
  const [showSyncedStatus, setShowSyncedStatus] = useState(false);

  useEffect(() => { loadData().then(setData); }, []);
  useEffect(() => { setBrewSearchQuery(""); }, [view]);

  const dataRef = useRef(data);
  dataRef.current = data;

  const syncData = useCallback(async (currentData = dataRef.current) => {
    if (!token || !currentData) return;
    if (!navigator.onLine) { setIsOnline(false); setShowSyncedStatus(true); return; }
    setIsOnline(true); setSyncing(true); setShowSyncedStatus(true);
    try {
      const { beans = [], brewLogs = [], lastSyncedAt = null } = currentData;
      const res = await fetch('/api/sync', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
        body: JSON.stringify({ lastSyncedAt, beans, brewLogs })
      });
      if (!res.ok) throw new Error('Sync failed');
      const { serverTime, beans: serverBeans, brewLogs: serverLogs } = await res.json();
      const mergedBeans = [...beans];
      serverBeans.forEach(sb => { const i = mergedBeans.findIndex(b => b.id === sb.id); i >= 0 ? (new Date(sb.updatedAt) > new Date(mergedBeans[i].updatedAt || 0) && (mergedBeans[i] = sb)) : mergedBeans.push(sb); });
      const mergedLogs = [...brewLogs];
      serverLogs.forEach(sl => { const i = mergedLogs.findIndex(l => l.id === sl.id); i >= 0 ? (new Date(sl.updatedAt) > new Date(mergedLogs[i].updatedAt || 0) && (mergedLogs[i] = sl)) : mergedLogs.push(sl); });
      const nextData = {
        beans: mergedBeans.filter(b => !(b.isDeleted && new Date(b.updatedAt) <= new Date(serverTime))),
        brewLogs: mergedLogs.filter(l => !(l.isDeleted && new Date(l.updatedAt) <= new Date(serverTime))),
        lastSyncedAt: serverTime
      };
      setData(nextData); await saveData(nextData);
    } catch (err) { console.error('Failed to sync data:', err); }
    finally {
      setSyncing(false);
      if (navigator.onLine) setTimeout(() => setShowSyncedStatus(false), 2500);
      else setShowSyncedStatus(true);
    }
  }, [token]);

  useEffect(() => {
    const handleOnline = () => { setIsOnline(true); syncData(); };
    const handleOffline = () => { setIsOnline(false); setShowSyncedStatus(true); };
    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);
    if (token && data) syncData();
    const interval = setInterval(() => { if (token && data) syncData(); }, 30000);
    return () => { window.removeEventListener('online', handleOnline); window.removeEventListener('offline', handleOffline); clearInterval(interval); };
  }, [token, data === null, syncData]);

  const persist = useCallback(async (newData) => {
    setData(newData); await saveData(newData); syncData(newData);
  }, [syncData]);


  if (loading) return <LoadingScreen />;

  if (!token || !user) {
    return (
      <div className="w-full max-w-[480px] mx-auto min-h-screen border-x border-[#E8DFD3] dark:border-[#3B2217] bg-[#FAF6F1] dark:bg-[#150B07] max-sm:border-x-0 transition-colors duration-200">
        {authView === "login" ? (
          <>
            <Login onLoginSuccess={() => {}} />
            <div className="text-center mt-5 px-5">
              <p className="text-[#9C8B7A] dark:text-[#C8B9A6] text-sm">Don't have an account?{' '}
                <button onClick={() => setAuthView("register")} className="border-none bg-transparent text-[#8B6914] dark:text-[#D4A325] cursor-pointer underline text-sm">Register</button>
              </p>
            </div>
          </>
        ) : (
          <>
            <Register onRegisterSuccess={() => setAuthView("login")} />
            <div className="text-center mt-5 px-5">
              <p className="text-[#9C8B7A] dark:text-[#C8B9A6] text-sm">Already have an account?{' '}
                <button onClick={() => setAuthView("login")} className="border-none bg-transparent text-[#8B6914] dark:text-[#D4A325] cursor-pointer underline text-sm">Login</button>
              </p>
            </div>
          </>
        )}
      </div>
    );
  }

  if (!data) return <LoadingScreen />;

  const allBeans = data.beans || [];
  const allLogs = data.brewLogs || [];
  const beans = allBeans.filter(b => !b.isDeleted);
  const brewLogs = allLogs.filter(l => !l.isDeleted);

  const addBean = (form) => { persist({ ...data, beans: [...allBeans, { id: uid(), ...form, updatedAt: new Date().toISOString(), isDeleted: false }] }); setModal(null); };
  const updateBean = (form) => {
    const now = new Date().toISOString();
    persist({ ...data, beans: allBeans.map(b => b.id === editingBean.id ? { ...b, ...form, updatedAt: now } : b) });
    setModal(null); setEditingBean(null);
    if (selectedBean?.id === editingBean.id) setSelectedBean({ ...selectedBean, ...form, updatedAt: now });
  };
  const deleteBean = (id) => {
    const now = new Date().toISOString();
    persist({ ...data, beans: allBeans.map(b => b.id === id ? { ...b, isDeleted: true, updatedAt: now } : b), brewLogs: allLogs.map(l => l.beanId === id ? { ...l, isDeleted: true, updatedAt: now } : l) });
    setSelectedBean(null);
  };
  const addBrew = (form) => { persist({ ...data, brewLogs: [...allLogs, { id: uid(), createdAt: Date.now(), ...form, updatedAt: new Date().toISOString(), isDeleted: false }] }); setModal(null); };

  const getBeanName = (id) => allBeans.find(b => b.id === id)?.name || "Unknown Bean";
  const filteredLogs = (brewFilter === "all" ? brewLogs : brewLogs.filter(l => l.method === brewFilter))
    .filter(log => {
      if (!brewSearchQuery) return true;
      const dateObj = new Date(log.createdAt);
      const weekday = dateObj.toLocaleDateString("en-US", { weekday: "long" }).toLowerCase();
      const month = dateObj.toLocaleDateString("en-US", { month: "long" }).toLowerCase();
      const monthShort = dateObj.toLocaleDateString("en-US", { month: "short" }).toLowerCase();
      const dateNum = dateObj.getDate().toString();
      const year = dateObj.getFullYear().toString();

      const searchableText = [
        getBeanName(log.beanId).toLowerCase(),
        METHOD_LABELS[log.method]?.toLowerCase() || "",
        log.recipeDetails?.toLowerCase() || "",
        log.tasteNotes?.toLowerCase() || "",
        log.notes?.toLowerCase() || "",
        log.grindSize?.toLowerCase() || log.grind?.toLowerCase() || "",
        log.waterTemp?.toLowerCase() || "",
        log.brewRatio?.toLowerCase() || log.ratio?.toLowerCase() || "",
        log.brewTime?.toLowerCase() || log.time?.toLowerCase() || "",
        weekday,
        month,
        monthShort,
        dateNum,
        year
      ].join(" ");

      const queryWords = brewSearchQuery.trim().toLowerCase().split(/\s+/);
      return queryWords.every(word => searchableText.includes(word));
    })
    .sort((a, b) => b.createdAt - a.createdAt);
  const methodCounts = { pourover: 0, espresso: 0, coldbrew: 0 };
  brewLogs.forEach(l => { if (methodCounts[l.method] !== undefined) methodCounts[l.method]++; });

  const filterPillCls = (active) => `px-3.5 py-1.5 rounded-full border text-xs font-medium whitespace-nowrap cursor-pointer transition-all ${active ? "bg-[#2C1810] text-[#FAF6F1] border-[#2C1810] dark:bg-[#FAF6F1] dark:text-[#2C1810] dark:border-[#FAF6F1]" : "bg-white border-[#E8DFD3] text-[#6B5744] dark:bg-[#22120B] dark:border-[#3B2217] dark:text-[#C8B9A6]"}`;

  // Page title per view
  const pageTitles = { dashboard: "Brew Journal", beans: "Bean Recipes", brews: "Brew Logs", profile: "Profile" };
  const pageSubtitles = { dashboard: "Coffee Logbook", beans: "Your Collection", brews: "All Sessions", profile: "Account" };

  return (
    <div className="w-full max-w-[480px] mx-auto min-h-screen bg-[#FAF6F1] dark:bg-[#150B07] border-x border-[#E8DFD3] dark:border-[#3B2217] shadow-[0_0_30px_rgba(44,24,16,0.05)] dark:shadow-none max-sm:border-x-0 max-sm:shadow-none font-sans relative text-[#2C1810] dark:text-[#FAF6F1] transition-colors duration-200">

      {/* Header */}
      <div className="px-5 pt-6 pb-4 flex items-center justify-between sticky top-0 bg-[#FAF6F1]/95 dark:bg-[#150B07]/95 backdrop-blur-sm z-50 border-b border-[#E8DFD3] dark:border-[#3B2217] transition-colors duration-200">
        <div>
          <div className="text-[10px] text-[#9C8B7A] dark:text-[#C8B9A6] font-semibold tracking-[1.5px] uppercase">{pageSubtitles[view] || "Coffee Logbook"}</div>
          <h1 className="font-serif text-[21px] font-semibold tracking-tight text-[#2C1810] dark:text-[#FAF6F1] mt-0.5">{pageTitles[view] || "Brew Journal"}</h1>
        </div>
        <SyncIndicator isOnline={isOnline} syncing={syncing} showSyncedStatus={showSyncedStatus} />
      </div>

      {/* Content */}
      <div className="px-5 pt-4 pb-36">

        {/* ── Dashboard ── */}
        {/* ── Dashboard ── */}
        {view === "dashboard" && (
          <div className="animate-page-enter">
            <div className="flex gap-2 mb-5">
              {[{ num: beans.length, label: "Beans" }, { num: brewLogs.length, label: "Brews" }, { num: new Set(brewLogs.map(l => l.beanId)).size, label: "Tried" }].map(s => (
                <div key={s.label} className="flex-1 bg-white dark:bg-[#22120B] border border-[#E8DFD3] dark:border-[#3B2217] rounded-2xl p-3.5 text-center transition-colors duration-200">
                  <div className="font-serif text-2xl font-bold text-[#2C1810] dark:text-[#FAF6F1]">{s.num}</div>
                  <div className="text-[10px] text-[#9C8B7A] dark:text-[#C8B9A6] uppercase tracking-widest mt-0.5">{s.label}</div>
                </div>
              ))}
            </div>
            <div className="text-[13px] font-semibold text-[#6B5744] dark:text-[#C8B9A6] uppercase tracking-widest mb-3">By Method</div>
            <div className="flex gap-2 mb-6">
              {METHODS.map(m => (
                <div key={m} className="flex-1 bg-white dark:bg-[#22120B] border border-[#E8DFD3] dark:border-[#3B2217] rounded-2xl p-3 text-center transition-colors duration-200" style={{ borderTop: `3px solid ${METHOD_COLORS[m]}` }}>
                  <div className="text-xl mb-1">{METHOD_ICONS[m]}</div>
                  <div className="font-serif text-xl font-bold text-[#2C1810] dark:text-[#FAF6F1]">{methodCounts[m]}</div>
                  <div className="text-[10px] text-[#9C8B7A] dark:text-[#C8B9A6] uppercase tracking-widest mt-0.5">{METHOD_LABELS[m]}</div>
                </div>
              ))}
            </div>
            <div className="text-[13px] font-semibold text-[#6B5744] dark:text-[#C8B9A6] uppercase tracking-widest mb-3">Recent Brews</div>
            {brewLogs.length === 0 ? (
              <div className="text-center py-12 text-[#9C8B7A] dark:text-[#C8B9A6]">
                <div className="text-4xl mb-3 opacity-50 dark:opacity-80">📝</div>
                <h3 className="text-base mb-1.5 font-serif text-[#6B5744] dark:text-[#FAF6F1]">No brews yet</h3>
                <p className="text-[13px] leading-relaxed">Tap the + button to log your first brew.</p>
              </div>
            ) : brewLogs.sort((a, b) => b.createdAt - a.createdAt).slice(0, 5).map(log => (
              <BrewCard key={log.id} log={log} beanName={getBeanName(log.beanId)} />
            ))}
          </div>
        )}

        {/* ── Bean Library ── */}
        {view === "beans" && !selectedBean && (
          <div className="animate-page-enter">
            <div className="text-[13px] font-semibold text-[#6B5744] dark:text-[#C8B9A6] uppercase tracking-widest mb-3">Your Beans ({beans.length})</div>
            {beans.length === 0 ? (
              <div className="text-center py-12 text-[#9C8B7A] dark:text-[#C8B9A6]">
                <div className="text-4xl mb-3 opacity-50 dark:opacity-80">🫘</div>
                <h3 className="text-base mb-1.5 font-serif text-[#6B5744] dark:text-[#FAF6F1]">Library is empty</h3>
                <p className="text-[13px] leading-relaxed">Tap + to add your first coffee bean.</p>
              </div>
            ) : beans.map(bean => {
              const count = brewLogs.filter(l => l.beanId === bean.id).length;
              const roastTagCls = bean.roastType?.toLowerCase().includes("dark") 
                ? "bg-[#E0D0BD] text-[#4A3520] dark:bg-[#2F1E12] dark:text-[#BCA38A]" 
                : bean.roastType?.toLowerCase().includes("medium") 
                  ? "bg-[#F0E0C8] text-[#6B4E2A] dark:bg-[#402A14] dark:text-[#D9AC7B]" 
                  : "bg-[#FFF3D6] text-[#8B6914] dark:bg-[#4A3912] dark:text-[#E6B640]";
              return (
                <div key={bean.id}
                  className="bg-white dark:bg-[#22120B] rounded-2xl shadow-[0_1px_3px_rgba(44,24,16,0.06),0_4px_12px_rgba(44,24,16,0.04)] dark:shadow-[0_4px_12px_rgba(0,0,0,0.2)] p-[18px] mb-3 border border-[#E8DFD3] dark:border-[#3B2217] cursor-pointer transition-all hover:shadow-[0_4px_16px_rgba(44,24,16,0.08)] dark:hover:shadow-[0_4px_16px_rgba(0,0,0,0.35)] active:scale-[0.99]"
                  onClick={() => setSelectedBean(bean)}>
                  <div className="flex justify-between items-start gap-3 mb-2">
                    {bean.image && <img src={bean.image} alt="" className="w-14 h-14 rounded-xl object-cover flex-shrink-0" />}
                    <div className="flex-1 min-w-0">
                      <div className="font-serif text-[17px] font-semibold text-[#2C1810] dark:text-[#FAF6F1]">{bean.name}</div>
                      {bean.roastery && <div className="text-[13px] text-[#6B5744] dark:text-[#C8B9A6] mt-0.5">{bean.roastery}</div>}
                    </div>
                    <span className="text-[11px] px-2.5 py-1 rounded-full bg-[#F3EDE4] dark:bg-[#2C1810] text-[#6B5744] dark:text-[#C8B9A6] font-medium flex-shrink-0">{count} brew{count !== 1 ? "s" : ""}</span>
                  </div>
                  {bean.tastingNotes && <div className="text-[13px] text-[#6B5744] dark:text-[#C8B9A6] italic mt-1.5 leading-snug">👅 {bean.tastingNotes}</div>}
                  <div className="flex gap-2 mt-2.5 flex-wrap">
                    {bean.roastType && <span className={`text-[11px] px-2.5 py-1 rounded-full font-medium ${roastTagCls}`}>{bean.roastType}</span>}
                    {bean.roastDate && <span className="text-[11px] px-2.5 py-1 rounded-full bg-[#F3EDE4] dark:bg-[#2C1810] text-[#6B5744] dark:text-[#C8B9A6] font-medium">Roasted {bean.roastDate}</span>}
                  </div>
                </div>
              );
            })}
          </div>
        )}

        {/* ── Bean Detail ── */}
        {view === "beans" && selectedBean && (
          <div className="animate-page-enter">
            <BeanDetail bean={selectedBean} logs={brewLogs}
              onBack={() => setSelectedBean(null)}
              onEdit={() => { setEditingBean(selectedBean); setModal("editBean"); }}
              onDelete={() => { if (confirm("Delete this bean and all its brew logs?")) deleteBean(selectedBean.id); }}
            />
          </div>
        )}

        {/* ── Brew Logs ── */}
        {view === "brews" && (
          <div className="animate-page-enter">
            {/* Search Bar */}
            <div className="mb-4 relative">
              <input
                type="text"
                value={brewSearchQuery}
                onChange={(e) => setBrewSearchQuery(e.target.value)}
                placeholder="Search brews (e.g. June, espresso, floral...)"
                className="w-full pl-10 pr-10 py-3.5 bg-white dark:bg-[#22120B] border border-[#E8DFD3] dark:border-[#3B2217] rounded-2xl text-xs placeholder-[#9C8B7A] dark:placeholder-[#C8B9A6] text-[#2C1810] dark:text-[#FAF6F1] shadow-[0_1px_3px_rgba(44,24,16,0.04)] dark:shadow-none focus:outline-none focus:border-[#8B6914] dark:focus:border-[#D4A325] transition-all"
              />
              {/* Search Icon */}
              <div className="absolute left-3.5 top-1/2 -translate-y-1/2 text-[#9C8B7A] dark:text-[#C8B9A6] flex items-center pointer-events-none">
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" className="opacity-70">
                  <circle cx="11" cy="11" r="8" />
                  <line x1="21" y1="21" x2="16.65" y2="16.65" />
                </svg>
              </div>
              {/* Clear button */}
              {brewSearchQuery && (
                <button
                  onClick={() => setBrewSearchQuery("")}
                  className="absolute right-3.5 top-1/2 -translate-y-1/2 w-6 h-6 flex items-center justify-center rounded-full text-[#9C8B7A] dark:text-[#C8B9A6] hover:text-[#2C1810] dark:hover:text-[#FAF6F1] border-none bg-transparent cursor-pointer text-base font-bold transition-colors"
                >
                  &times;
                </button>
              )}
            </div>

            <div className="flex gap-1.5 mb-4 overflow-x-auto pb-1">
              <button className={filterPillCls(brewFilter === "all")} onClick={() => setBrewFilter("all")}>All</button>
              {METHODS.map(m => (
                <button key={m} className={filterPillCls(brewFilter === m)} onClick={() => setBrewFilter(m)}>
                  {METHOD_ICONS[m]} {METHOD_LABELS[m]}
                </button>
              ))}
            </div>
            {filteredLogs.length === 0 ? (
              <div className="text-center py-12 text-[#9C8B7A] dark:text-[#C8B9A6]">
                <div className="flex justify-center mb-3 text-[#9C8B7A] dark:text-[#C8B9A6] opacity-60">
                  {brewSearchQuery ? <Search size={36} strokeWidth={2} /> : <span className="text-4xl">📋</span>}
                </div>
                <h3 className="text-base mb-1.5 font-serif text-[#6B5744] dark:text-[#FAF6F1]">
                  {brewSearchQuery ? "No search results" : `No logs ${brewFilter !== "all" ? `for ${METHOD_LABELS[brewFilter]}` : "yet"}`}
                </h3>
                <p className="text-[13px] leading-relaxed">
                  {brewSearchQuery ? "Try refining your search terms or filters." : "Start brewing and log your recipes here."}
                </p>
              </div>
            ) : filteredLogs.map(log => (
              <BrewCard key={log.id} log={log} beanName={getBeanName(log.beanId)} />
            ))}
          </div>
        )}

        {/* ── Profile ── */}
        {view === "profile" && (
          <div className="animate-page-enter">
            <ProfilePage user={user} isOnline={isOnline} syncing={syncing} showSyncedStatus={showSyncedStatus} />
          </div>
        )}
      </div>

      {/* Floating Bottom Navigation */}
      <BottomNav
        view={view}
        setView={setView}
        setSelectedBean={setSelectedBean}
        onCreatePress={() => setCreateOpen(true)}
      />

      {/* Create Modal */}
      {createOpen && (
        <CreateModal
          onClose={() => setCreateOpen(false)}
          onAddBean={() => setModal("addBean")}
          onAddBrew={() => setModal("addBrew")}
        />
      )}

      {/* Modals */}
      {modal === "addBean" && <BeanForm onSave={addBean} onClose={() => setModal(null)} />}
      {modal === "editBean" && editingBean && <BeanForm initial={editingBean} onSave={updateBean} onClose={() => { setModal(null); setEditingBean(null); }} />}
      {modal === "addBrew" && <BrewForm beans={beans} onSave={addBrew} onClose={() => setModal(null)} />}
      
      {/* iOS/iPadOS PWA Install Prompt */}
      <IosPromptModal />

      {/* PWA Update Prompt */}
      <UpdatePrompt />
    </div>
  );
}
