'use client';

import { useEffect, useState } from 'react';
import { Clock, RotateCcw, X, Loader2, Save, CheckCircle2 } from 'lucide-react';
import { useEditor } from '@/store/editor';
import { usePersistence } from '@/lib/storage/usePersistence';

export function RestoreBanner() {
  const editorState = useEditor((s) => ({
    clips: s.clips,
    subtitles: s.subtitles,
    assets: s.assets,
  }));
  const persistence = usePersistence();
  const setToast = useEditor((s) => s.setToast);
  const [restoring, setRestoring] = useState(false);
  const [showSavedFlash, setShowSavedFlash] = useState(false);

  // Show "saved" flash whenever lastSavedAt updates.
  useEffect(() => {
    if (!persistence.lastSavedAt) return;
    setShowSavedFlash(true);
    const t = setTimeout(() => setShowSavedFlash(false), 1200);
    return () => clearTimeout(t);
  }, [persistence.lastSavedAt]);

  // Don't show anything if user just dismissed restore and has no work yet.
  if (!persistence.restoreAvailable && editorState.clips.length === 0 && editorState.assets.length === 0) {
    return null;
  }

  async function handleRestore() {
    setRestoring(true);
    try {
      await persistence.restoreProject();
    } finally {
      setRestoring(false);
    }
  }

  async function handleClearAll() {
    if (!confirm('ลบโปรเจกต์ที่บันทึกไว้ทั้งหมด และเริ่มใหม่?')) return;
    await persistence.clearAll();
  }

  return (
    <>
      {persistence.restoreAvailable && (
        <div className="absolute top-14 left-1/2 -translate-x-1/2 z-40 bg-capcut-panel border border-capcut-orange/40 rounded-lg shadow-xl px-4 py-3 flex items-center gap-3 max-w-[92%]">
          <RotateCcw size={18} className="text-capcut-orange shrink-0" />
          <div className="flex-1 min-w-0">
            <div className="text-sm font-medium">เจอโปรเจกต์ที่บันทึกไว้</div>
            <div className="text-xs text-capcut-muted">
              บันทึกล่าสุดเมื่อ {persistence.restorePayload?.savedAt ? formatRelativeTime(persistence.restorePayload.savedAt) : 'ไม่ทราบ'}
            </div>
          </div>
          <button
            type="button"
            onClick={handleRestore}
            disabled={restoring}
            className="px-3 py-1.5 text-sm rounded-md bg-capcut-orange hover:bg-capcut-orange/90 text-white font-medium flex items-center gap-1.5 disabled:opacity-60"
          >
            {restoring ? <Loader2 size={14} className="animate-spin" /> : <RotateCcw size={14} />}
            เปิดต่อ
          </button>
          <button
            type="button"
            onClick={persistence.dismissRestore}
            className="px-3 py-1.5 text-sm rounded-md bg-capcut-surface hover:bg-capcut-border text-capcut-text flex items-center gap-1.5"
          >
            <X size={14} />
            เริ่มใหม่
          </button>
        </div>
      )}

      {/* Auto-save status pill (bottom-left, beside timeline) */}
      {(persistence.lastSavedAt || persistence.saving) && editorState.clips.length > 0 && (
        <div className="absolute bottom-3 left-3 z-30 bg-capcut-panel/90 border border-capcut-border rounded-full px-3 py-1 text-xs flex items-center gap-1.5 shadow-md">
          {persistence.saving ? (
            <>
              <Loader2 size={12} className="animate-spin text-capcut-blue" />
              <span className="text-capcut-muted">กำลังบันทึก...</span>
            </>
          ) : showSavedFlash ? (
            <>
              <CheckCircle2 size={12} className="text-capcut-green" />
              <span className="text-capcut-muted">บันทึกแล้ว</span>
            </>
          ) : (
            <>
              <Save size={12} className="text-capcut-muted" />
              <span className="text-capcut-muted">
                Auto-saved · {persistence.lastSavedAt ? formatRelativeTime(persistence.lastSavedAt) : ''}
              </span>
            </>
          )}
        </div>
      )}
    </>
  );
}

function formatRelativeTime(ts: number): string {
  const diff = Date.now() - ts;
  if (diff < 60_000) return `${Math.max(1, Math.floor(diff / 1000))} วินาทีที่แล้ว`;
  if (diff < 3_600_000) return `${Math.floor(diff / 60_000)} นาทีที่แล้ว`;
  if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)} ชั่วโมงที่แล้ว`;
  return new Date(ts).toLocaleString('th-TH');
}