'use client';

import { useState, useEffect } from 'react';
import { Undo2, Redo2, Download, Film, Loader2, CheckCircle2, FilePlus2, Save, Folder, Pencil, Trash2, Share2, Type, LayoutTemplate, LogIn, User, LogOut, Cloud, HardDrive } from 'lucide-react';
import { useEditor } from '@/store/editor';
import { exportProject } from '@/lib/ffmpeg';
import { formatTimeShort } from '@/lib/media';
import { usePersistence } from '@/lib/storage/usePersistence';
import { encodeShareable, buildShareUrl } from '@/lib/share/url-share';
import { useAuth } from '@/store/auth';
import { AuthModal } from './AuthModal';

export function TopBar() {
  const undo = useEditor((s) => s.undo);
  const redo = useEditor((s) => s.redo);
  const canUndo = useEditor((s) => s.canUndo());
  const canRedo = useEditor((s) => s.canRedo());
  const exportSettings = useEditor((s) => s.exportSettings);
  const setToast = useEditor((s) => s.setToast);
  const persistence = usePersistence();
  const clipsCount = useEditor((s) => s.clips.length);
  const subtitles = useEditor((s) => s.subtitles);
  const subtitleStyle = useEditor((s) => s.subtitleStyle);
  const projectName = useEditor((s) => s.projectName);
  const setProjectName = useEditor((s) => s.setProjectName);
  const loadProjectById = useEditor((s) => s.loadProjectById);
  const newProject = useEditor((s) => s.newProject);
  const deleteCurrentProject = useEditor((s) => s.deleteCurrentProject);
  const [showProjects, setShowProjects] = useState(false);
  const [showTemplates, setShowTemplates] = useState(false);
  const [editingName, setEditingName] = useState(false);
  const [nameDraft, setNameDraft] = useState(projectName);

  const [exporting, setExporting] = useState(false);
  const [progress, setProgress] = useState(0);
  const [progressLog, setProgressLog] = useState('');
  const authUser = useAuth((s) => s.user);
  const authLogout = useAuth((s) => s.logout);
  const authInitialized = useAuth((s) => s.initialized);
  const storageMode = useAuth((s) => s.storageMode);
  const setStorageMode = useAuth((s) => s.setStorageMode);
  const [showAuth, setShowAuth] = useState(false);
  const [showUserMenu, setShowUserMenu] = useState(false);

  // Refresh project list when auth user changes (login/logout).
  useEffect(() => {
    if (authInitialized) {
      void persistence.refreshProjects();
      if (authUser) {
        setToast({
          message: `ยินดีต้อนรับ ${authUser.username} — โหลดโปรเจกต์จากคลาวด์`,
          level: 'success',
        });
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [authUser?.id]);

  async function handleShare() {
    const state = useEditor.getState();
    if (state.clips.length === 0) {
      setToast({ message: 'ไม่มีคลิปในโปรเจกต์ — เพิ่มก่อนแชร์', level: 'error' });
      return;
    }
    try {
      const encoded = await encodeShareable({
        name: state.projectName,
        tracks: state.tracks,
        clips: state.clips,
        subtitles: state.subtitles,
        silenceSegments: state.silenceSegments,
        subtitleStyle: state.subtitleStyle,
        exportSettings: state.exportSettings,
      });
      const url = buildShareUrl(window.location.origin + window.location.pathname, encoded);
      try {
        await navigator.clipboard.writeText(url);
        setToast({ message: 'คัดลอกลิงค์แชร์แล้ว — ส่งให้เพื่อนได้เลย', level: 'success' });
      } catch {
        prompt('คัดลอกลิงค์แชร์นี้:', url);
      }
    } catch (err) {
      const msg = err instanceof Error ? err.message : 'สร้างลิงค์ไม่สำเร็จ';
      setToast({ message: msg, level: 'error' });
    }
  }

  async function handleExport() {
    const state = useEditor.getState();
    if (state.clips.length === 0) {
      setToast({ message: 'ยังไม่มีคลิปบนไทม์ไลน์', level: 'error' });
      return;
    }
    setExporting(true);
    setProgress(0);
    setProgressLog('กำลังเตรียม FFmpeg.wasm …');
    try {
      // Apply silence removal to a snapshot before export if requested
      let clips = state.clips;
      let silSegments = state.silenceSegments;
      if (exportSettings.removeSilence && silSegments.length > 0) {
        const orig = useEditor.getState().clips;
        useEditor.getState().applySilenceRemoval();
        clips = useEditor.getState().clips;
        silSegments = [];
        // Restore later by undoing
        setTimeout(() => {
          // After export we restore — but we have no signal back here. Instead, do the export
          // off the temporary clips without mutating store.
          // Reset by reloading orig via setState? Simpler: undo will restore.
        }, 50);
        // The store is now mutated — we will restore after export by undoing
        const restore = () => {
          // best-effort undo until we get back to original clip count
          // (history size = 1 push for applySilenceRemoval)
          const hist = useEditor.getState().history;
          const cur = useEditor.getState().historyIndex;
          if (hist.length > 0 && cur >= 0) useEditor.getState().undo();
        };
        try {
          const blob = await exportProject({
            assets: state.assets,
            tracks: state.tracks,
            clips,
            settings: exportSettings,
            subtitles,
            subtitleStyle,
            textOverlays: state.textOverlays,
            onProgress: (pct, log) => {
              setProgress(pct);
              if (log) setProgressLog(log);
            },
          });
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          const ts = new Date().toISOString().slice(0, 19).replace(/[:T]/g, '-');
          a.download = `capcut-export-${ts}.mp4`;
          document.body.appendChild(a);
          a.click();
          a.remove();
          URL.revokeObjectURL(url);
          setToast({ message: 'ส่งออก mp4 เรียบร้อย', level: 'success' });
        } finally {
          restore();
        }
        return;
      }

      const blob = await exportProject({
        assets: state.assets,
        tracks: state.tracks,
        clips,
        settings: exportSettings,
        textOverlays: state.textOverlays,
        subtitles,
        subtitleStyle,
        onProgress: (pct, log) => {
          setProgress(pct);
          if (log) setProgressLog(log);
        },
      });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      const ts = new Date().toISOString().slice(0, 19).replace(/[:T]/g, '-');
      a.download = `capcut-export-${ts}.mp4`;
      document.body.appendChild(a);
      a.click();
      a.remove();
      URL.revokeObjectURL(url);
      setToast({ message: 'ส่งออก mp4 เรียบร้อย', level: 'success' });
    } catch (err) {
      const message = err instanceof Error ? err.message : 'การส่งออกล้มเหลว';
      setToast({ message: `ส่งออกล้มเหลว: ${message}`, level: 'error' });
    } finally {
      setExporting(false);
      setTimeout(() => {
        setProgress(0);
        setProgressLog('');
      }, 1200);
    }
  }

  return (
    <header className="h-14 px-5 flex items-center justify-between border-b border-capcut-border bg-capcut-dark/80 glass shrink-0 gap-4">
      <div className="flex items-center gap-3 min-w-0">
        <div className="relative w-9 h-9 rounded-xl bg-gradient-to-br from-capcut-blue via-capcut-purple to-capcut-orange flex items-center justify-center shrink-0 shadow-glow-blue">
          <Film size={18} className="text-white drop-shadow" />
          <span className="absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 bg-capcut-green rounded-full ring-2 ring-capcut-dark" />
        </div>
        <div className="flex flex-col min-w-0">
          <h1 className="text-sm font-semibold tracking-wide truncate text-capcut-text">
            ตัดต่อวิดีโอออนไลน์
            <span className="ml-2 text-[10px] font-normal text-capcut-muted uppercase tracking-wider">CapCut Web</span>
          </h1>
          {editingName ? (
            <input
              autoFocus
              value={nameDraft}
              onChange={(e) => setNameDraft(e.target.value)}
              onBlur={() => {
                if (nameDraft.trim()) setProjectName(nameDraft.trim());
                else setNameDraft(projectName);
                setEditingName(false);
              }}
              onKeyDown={(e) => {
                if (e.key === 'Enter') (e.target as HTMLInputElement).blur();
                if (e.key === 'Escape') {
                  setNameDraft(projectName);
                  setEditingName(false);
                }
              }}
              className="text-xs bg-capcut-surface border border-capcut-blue rounded px-1 outline-none"
              style={{ width: `${Math.max(8, nameDraft.length)}ch` }}
            />
          ) : (
            <button
              type="button"
              onClick={() => { setNameDraft(projectName); setEditingName(true); }}
              className="text-xs text-capcut-muted hover:text-capcut-text flex items-center gap-1 truncate"
              data-tip="คลิกเพื่อเปลี่ยนชื่อโปรเจกต์"
            >
              <Folder size={10} /> {projectName}
              <Pencil size={10} className="opacity-50" />
            </button>
          )}
        </div>
      </div>

      <div className="relative">
        <button
          type="button"
          data-tip="โปรเจกต์ทั้งหมด"
          onClick={() => setShowProjects(!showProjects)}
          className="text-[11px] px-2 py-1 rounded bg-capcut-surface border border-capcut-border hover:border-capcut-blue/40 flex items-center gap-1"
        >
          <Folder size={12} />
          {persistence.projects.length > 0 ? persistence.projects.length : ''} โปรเจกต์
        </button>
        {showProjects && (
          <div className="absolute left-0 top-full mt-1 w-72 bg-capcut-panel border border-capcut-border rounded-md shadow-xl z-50 p-2 max-h-96 overflow-y-auto">
            <div className="flex items-center justify-between mb-2">
              <span className="text-[11px] font-semibold text-capcut-muted uppercase">โปรเจกต์ที่บันทึกไว้</span>
              <button
                type="button"
                onClick={async () => {
                  const name = prompt('ชื่อโปรเจกต์ใหม่:');
                  if (name && name.trim()) {
                    await newProject(name.trim());
                    await persistence.refreshProjects();
                    setShowProjects(false);
                  }
                }}
                className="text-[11px] text-capcut-blue hover:underline flex items-center gap-1"
              >
                <FilePlus2 size={12} /> สร้างใหม่
              </button>
            </div>
            {persistence.projects.length === 0 ? (
              <p className="text-xs text-capcut-muted p-3 text-center">ยังไม่มีโปรเจกต์ที่บันทึก</p>
            ) : (
              persistence.projects.map((p) => (
                <div
                  key={p.id}
                  className={`group flex items-center gap-2 p-2 rounded hover:bg-capcut-surface ${
                    p.id === projectName ? 'bg-capcut-blue/10' : ''
                  }`}
                >
                  <button
                    type="button"
                    onClick={async () => {
                      await loadProjectById(p.id);
                      await persistence.refreshProjects();
                      setShowProjects(false);
                    }}
                    className="flex-1 text-left min-w-0"
                  >
                    <div className="text-xs font-medium truncate">{p.name}</div>
                    <div className="text-[10px] text-capcut-muted">
                      {p.clipCount} คลิป · {new Date(p.updatedAt).toLocaleString('th-TH')}
                    </div>
                  </button>
                  <button
                    type="button"
                    onClick={async (e) => {
                      e.stopPropagation();
                      if (!confirm(`ลบโปรเจกต์ "${p.name}"?`)) return;
                      const { deleteProject } = await import('@/lib/storage/persistence');
                      await deleteProject(p.id);
                      await persistence.refreshProjects();
                    }}
                    className="opacity-0 group-hover:opacity-100 w-7 h-7 rounded hover:bg-capcut-border text-capcut-muted hover:text-capcut-red flex items-center justify-center"
                    data-tip="ลบ"
                  >
                    <Trash2 size={12} />
                  </button>
                </div>
              ))
            )}
            {projectName !== 'โปรเจกต์ใหม่' && (
              <div className="border-t border-capcut-border mt-2 pt-2">
                <button
                  type="button"
                  onClick={async () => {
                    if (!confirm(`ลบโปรเจกต์ "${projectName}" ปัจจุบัน?`)) return;
                    await deleteCurrentProject();
                    await persistence.refreshProjects();
                    setShowProjects(false);
                  }}
                  className="w-full text-xs text-capcut-red hover:bg-capcut-red/10 p-2 rounded flex items-center gap-2"
                >
                  <Trash2 size={12} /> ลบโปรเจกต์ปัจจุบัน
                </button>
              </div>
            )}
          </div>
        )}
      </div>

      <div className="flex items-center gap-2">
        <button
          type="button"
          data-tip="ย้อนกลับ (Ctrl+Z)"
          onClick={undo}
          disabled={!canUndo}
          className="tip w-9 h-9 rounded-lg bg-capcut-surface/60 hover:bg-capcut-surface border border-capcut-border/60 hover:border-capcut-borderLight text-capcut-muted hover:text-capcut-text flex items-center justify-center disabled:opacity-40 transition-base"
        >
          <Undo2 size={16} />
        </button>
        <button
          type="button"
          data-tip="ทำซ้ำ (Ctrl+Shift+Z)"
          onClick={redo}
          disabled={!canRedo}
          className="tip w-9 h-9 rounded-lg bg-capcut-surface/60 hover:bg-capcut-surface border border-capcut-border/60 hover:border-capcut-borderLight text-capcut-muted hover:text-capcut-text flex items-center justify-center disabled:opacity-40 transition-base"
        >
          <Redo2 size={16} />
        </button>

        <div className="w-px h-6 bg-capcut-border mx-1" />

        <button
          type="button"
          data-tip="แชร์โปรเจกต์ (copy URL)"
          onClick={handleShare}
          disabled={clipsCount === 0}
          className="tip w-9 h-9 rounded-lg bg-capcut-surface/60 hover:bg-capcut-surface border border-capcut-border/60 hover:border-capcut-borderLight text-capcut-muted hover:text-capcut-text flex items-center justify-center disabled:opacity-40 transition-base"
        >
          <Share2 size={16} />
        </button>

        {clipsCount > 0 && (
          <>
            <button
              type="button"
              data-tip="บันทึกตอนนี้"
              onClick={async () => {
                // Force-save current state by triggering a no-op subscription tick.
                // Simpler: directly invoke the persistence save path through a small re-export.
                // Easiest UX: just toast and rely on debounced save; user sees "บันทึกแล้ว" within ~3s.
                setToast({ message: persistence.saving ? 'กำลังบันทึก...' : 'บันทึกอัตโนมัติทุก 3 วินาที', level: 'info' });
              }}
              className="tip w-9 h-9 rounded-md bg-capcut-surface hover:bg-capcut-border border border-capcut-border text-capcut-text flex items-center justify-center transition-colors"
            >
              <Save size={16} />
            </button>
            <button
              type="button"
              data-tip="เริ่มโปรเจกต์ใหม่"
              onClick={async () => {
                if (!confirm('ลบโปรเจกต์ปัจจุบันทั้งหมด (รวมไฟล์ที่บันทึกไว้) และเริ่มใหม่?')) return;
                await persistence.clearAll();
              }}
              className="tip w-9 h-9 rounded-md bg-capcut-surface hover:bg-capcut-border border border-capcut-border text-capcut-text flex items-center justify-center transition-colors"
            >
              <FilePlus2 size={16} />
            </button>
          </>
        )}

        {/* Text Overlay button — adds a floating text to current timeline */}
        <button
          type="button"
          data-tip="เพิ่มข้อความลอย"
          onClick={() => {
            const t = useEditor.getState();
            const start = t.currentTime;
            const id = t.addTextOverlay({
              trackId: 'overlay',
              text: 'ข้อความใหม่',
              start,
              duration: 3,
              fontFamily: 'sans-serif',
              fontSize: 48,
              bold: true,
              italic: false,
              color: '#ffffff',
              backgroundColor: '#000000',
              opacity: 1,
              xRatio: 0.5,
              yRatio: 0.85,
              animation: 'fade',
            });
            t.setSelection({ textOverlayId: id } as any);
            t.setToast({ message: 'เพิ่มข้อความลอย', level: 'success' });
          }}
          className="tip w-9 h-9 rounded-lg bg-capcut-orange/15 hover:bg-capcut-orange/25 border border-capcut-orange/40 text-capcut-orange flex items-center justify-center transition-base shadow-glow-orange"
        >
          <Type size={16} />
        </button>

        {/* Template library */}
        <button
          type="button"
          data-tip="เทมเพลต (Template Library)"
          onClick={() => {
            setShowTemplates((v) => !v);
            setShowProjects(false);
          }}
          className="tip w-9 h-9 rounded-md bg-capcut-surface hover:bg-capcut-border border border-capcut-border text-capcut-text flex items-center justify-center transition-colors"
        >
          <LayoutTemplate size={16} />
        </button>

        <div className="w-px h-6 bg-capcut-border mx-1" />

        {/* Auth: login button OR user chip */}
        {authUser ? (
          <div className="relative">
            <button
              type="button"
              data-tip={`storage mode: ${storageMode}`}
              onClick={() => setShowUserMenu(!showUserMenu)}
              className="h-9 px-3 rounded-lg bg-gradient-to-br from-capcut-blue/20 to-capcut-purple/15 border border-capcut-blue/40 hover:border-capcut-blue/70 flex items-center gap-2 text-xs text-white transition-base"
            >
              <span className="w-5 h-5 rounded-full bg-gradient-to-br from-capcut-blue to-capcut-purple flex items-center justify-center text-[10px] font-bold">
                {authUser.username.charAt(0).toUpperCase()}
              </span>
              <span className="font-medium">{authUser.username}</span>
              <Cloud size={12} className="text-capcut-blue" />
            </button>
            {showUserMenu && (
              <div
                className="absolute right-0 top-full mt-1 w-64 bg-capcut-panel border border-capcut-border rounded-md shadow-xl z-50 p-2"
                onMouseLeave={() => setShowUserMenu(false)}
              >
                <div className="px-2 py-1.5 border-b border-capcut-border mb-1">
                  <div className="text-xs font-semibold text-capcut-text">
                    {authUser.displayName}
                  </div>
                  <div className="text-[10px] text-capcut-muted">
                    สมัครเมื่อ {new Date(authUser.createdAt).toLocaleDateString('th-TH')}
                  </div>
                </div>
                <div className="px-2 py-1.5">
                  <div className="text-[10px] text-capcut-muted uppercase mb-1">ที่เก็บข้อมูล</div>
                  <div className="space-y-0.5">
                    <button
                      type="button"
                      onClick={() => setStorageMode('server')}
                      className={`w-full text-xs flex items-center gap-2 px-2 py-1 rounded ${
                        storageMode === 'server'
                          ? 'bg-capcut-blue/15 text-capcut-blue'
                          : 'hover:bg-capcut-surface text-capcut-text'
                      }`}
                    >
                      <Cloud size={12} /> คลาวด์ (เซิร์ฟเวอร์)
                    </button>
                    <button
                      type="button"
                      onClick={() => setStorageMode('local')}
                      className={`w-full text-xs flex items-center gap-2 px-2 py-1 rounded ${
                        storageMode === 'local'
                          ? 'bg-capcut-blue/15 text-capcut-blue'
                          : 'hover:bg-capcut-surface text-capcut-text'
                      }`}
                    >
                      <HardDrive size={12} /> บนเครื่อง (IndexedDB)
                    </button>
                    <button
                      type="button"
                      onClick={() => setStorageMode('auto')}
                      className={`w-full text-xs flex items-center gap-2 px-2 py-1 rounded ${
                        storageMode === 'auto'
                          ? 'bg-capcut-blue/15 text-capcut-blue'
                          : 'hover:bg-capcut-surface text-capcut-text'
                      }`}
                    >
                      <User size={12} /> อัตโนมัติ (คลาวด์เมื่อ login)
                    </button>
                  </div>
                </div>
                <button
                  type="button"
                  onClick={async () => {
                    await authLogout();
                    setShowUserMenu(false);
                    await persistence.refreshProjects();
                  }}
                  className="w-full text-xs text-capcut-red hover:bg-capcut-red/10 px-2 py-1.5 rounded flex items-center gap-2 mt-1 border-t border-capcut-border"
                >
                  <LogOut size={12} /> ออกจากระบบ
                </button>
              </div>
            )}
          </div>
        ) : (
          <button
            type="button"
            data-tip="เข้าสู่ระบบ / สมัครสมาชิก"
            onClick={() => setShowAuth(true)}
            className="tip h-9 px-3 rounded-lg bg-capcut-surface/60 hover:bg-capcut-surface border border-capcut-border/60 hover:border-capcut-blue/40 text-capcut-text hover:text-white text-xs flex items-center gap-1.5 transition-base"
          >
            <LogIn size={14} />
            <span className="hidden sm:inline">เข้าสู่ระบบ</span>
          </button>
        )}

        <button
          type="button"
          onClick={handleExport}
          disabled={exporting}
          className="h-9 px-4 rounded-lg bg-gradient-to-b from-capcut-blue to-capcut-blueDark hover:from-capcut-blueLight hover:to-capcut-blue text-white text-sm font-semibold flex items-center gap-2 disabled:opacity-60 transition-base shadow-glow-blue border border-capcut-blue/40"
        >
          {exporting ? <Loader2 size={16} className="animate-spin" /> : <Download size={16} />}
          {exporting ? `กำลังส่งออก ${progress}%` : 'ส่งออก mp4'}
        </button>
      </div>

      {exporting && (
        <div className="absolute top-12 left-1/2 -translate-x-1/2 mt-2 bg-capcut-panel border border-capcut-border rounded-md px-3 py-2 text-xs shadow-lg min-w-[320px]">
          <div className="flex items-center gap-2 mb-1">
            {progress >= 100 ? <CheckCircle2 size={14} className="text-capcut-green" /> : <Loader2 size={14} className="animate-spin text-capcut-blue" />}
            <span>{progressLog || 'กำลังเรนเดอร์วิดีโอ…'}</span>
          </div>
          <div className="h-1 bg-capcut-surface rounded overflow-hidden">
            <div className="h-full bg-capcut-blue transition-all" style={{ width: `${progress}%` }} />
          </div>
        </div>
      )}

      {/* Template Library dropdown */}
      {showTemplates && (
        <div className="absolute right-4 top-12 mt-1 w-80 bg-capcut-panel border border-capcut-border rounded-lg shadow-2xl z-50 p-3 max-h-[28rem] overflow-y-auto">
          <div className="text-[11px] font-semibold text-capcut-muted uppercase tracking-wider mb-2">
            เทมเพลต (Template Library)
          </div>
          <p className="text-[10px] text-capcut-muted mb-3">
            เลือกเทมเพลตเพื่อเริ่มต้น — แทนที่ tracks/clips/overlays ปัจจุบันด้วยโครงสร้างเทมเพลต
          </p>
          <div className="space-y-2">
            {[
              { id: 'blank', name: 'โปรเจกต์เปล่า', emoji: '📄', desc: 'เริ่มจากศูนย์ · 5 tracks' },
              { id: 'intro', name: 'อินโทร YouTube', emoji: '🎬', desc: '15s + Title overlay' },
              { id: 'beat-drop', name: 'Beat Drop', emoji: '🥁', desc: '8s + BEAT + DROP' },
              { id: 'outro', name: 'เอาท์โทร YouTube', emoji: '👋', desc: '10s + Subscribe' },
              { id: 'split-pip', name: 'หน้าจอแยก PIP', emoji: '🖼️', desc: '3 video tracks' },
            ].map((t) => (
              <button
                key={t.id}
                type="button"
                onClick={async () => {
                  const { applyTemplate } = await import('@/lib/templates');
                  const { uid } = await import('@/store/editor/types');
                  const newId = uid();
                  const now = Date.now();
                  applyTemplate(t.id, (tracks, clips, textOverlays) => {
                    useEditor.setState({
                      tracks,
                      clips,
                      textOverlays,
                      currentTime: 0,
                      selection: {},
                      history: [],
                      historyIndex: -1,
                    });
                  });
                  useEditor.getState().setToast({
                    message: `ใช้เทมเพลต: ${t.name}`,
                    level: 'success',
                  });
                  setShowTemplates(false);
                  void newId; void now;
                }}
                className="w-full bg-capcut-surface hover:bg-capcut-border border border-capcut-border rounded p-2 text-left flex items-start gap-2"
              >
                <span className="text-2xl">{t.emoji}</span>
                <div className="min-w-0">
                  <div className="text-xs font-medium">{t.name}</div>
                  <div className="text-[10px] text-capcut-muted">{t.desc}</div>
                </div>
              </button>
            ))}
          </div>
        </div>
      )}

      <AuthModal open={showAuth} onClose={() => setShowAuth(false)} />
    </header>
  );
}