"use client";

import { useState, useEffect } from 'react';

export default function Home() {
  const [posts, setPosts] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  
  // State untuk form input Setor Materi
  const [shopeeLink, setShopeeLink] = useState('');
  const [productImage, setProductImage] = useState<File | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  
  // State untuk tombol Upload Video
  const [uploadingId, setUploadingId] = useState<string | null>(null);

  // Mengambil data dari API
  const fetchPosts = async () => {
    setIsLoading(true);
    try {
      const res = await fetch('/api/posts');
      const result = await res.json();
      if (result.success) setPosts(result.data);
    } catch (error) {
      console.error("Gagal mengambil data:", error);
    } finally {
      setIsLoading(false);
    }
  };

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

  // FUNGSI 1: Eksekusi Setor Materi (Upload Gambar & Simpan DB)
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!shopeeLink) return alert('Link Shopee wajib diisi!');
    setIsSubmitting(true);
    
    try {
      let imageUrl = '';
      
      // Jika ada file SS/Gambar, upload dulu ke Google Drive
      if (productImage) {
        const formData = new FormData();
        formData.append('file', productImage);
        
        const uploadRes = await fetch('/api/upload', {
          method: 'POST',
          body: formData,
        });
        const uploadResult = await uploadRes.json();
        
        if (uploadResult.success) {
          // Format ID Drive menjadi link gambar agar bisa dirender di layar PC
          imageUrl = `https://drive.google.com/uc?id=${uploadResult.fileId}`;
        } else {
          throw new Error(uploadResult.message || "Gagal mengunggah gambar ke Drive");
        }
      }

      // Kirim link Shopee dan URL Gambar ke database
      const res = await fetch('/api/posts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ shopee_link: shopeeLink, product_image_url: imageUrl }),
      });
      
      const result = await res.json();
      if (result.success) {
        // Kosongkan form jika berhasil
        setShopeeLink(''); 
        setProductImage(null);
        const fileInput = document.getElementById('image-upload') as HTMLInputElement;
        if (fileInput) fileInput.value = '';
        
        fetchPosts(); // Refresh otomatis
      } else {
        alert(result.message);
      }
    } catch (error: any) {
      alert('Terjadi kesalahan: ' + error.message);
    } finally {
      setIsSubmitting(false);
    }
  };

  // FUNGSI 2: Pekerja PC Mengunggah Video & Mengubah Status
  const handleUploadVideo = async (postId: string, file: File | null) => {
    if (!file) return;
    setUploadingId(postId);

    try {
      // Tembak video ke Google Drive
      const formData = new FormData();
      formData.append('file', file);
      
      const uploadRes = await fetch('/api/upload', {
        method: 'POST',
        body: formData,
      });
      const uploadResult = await uploadRes.json();

      if (!uploadResult.success) throw new Error(uploadResult.message);

      // Ubah status di database menjadi Ready
      const updateRes = await fetch('/api/posts', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          post_id: postId,
          drive_file_id: uploadResult.fileId,
        }),
      });
      
      const updateResult = await updateRes.json();
      if (updateResult.success) {
        alert('Video berhasil di-upload ke Drive & Siap di-posting HP!');
        fetchPosts();
      }
    } catch (error: any) {
      alert("Gagal Upload: " + error.message);
    } finally {
      setUploadingId(null);
    }
  };

  const requestedPosts = posts.filter(p => p.status === 'Requested');
  const readyPosts = posts.filter(p => p.status === 'Ready');
  const postedPosts = posts.filter(p => p.status === 'Posted');

  return (
    <main className="min-h-screen bg-slate-50 p-4 md:p-8 font-sans text-slate-800">
      <header className="mb-8 border-b border-slate-200 pb-6">
        <h1 className="text-3xl font-extrabold bg-clip-text text-transparent bg-gradient-to-r from-blue-600 to-indigo-600">
          BotFarm Shopee
        </h1>
        <p className="text-sm text-slate-500 mt-1 font-medium">Sistem Otomasi Manajemen Konten</p>
      </header>

      {/* FORM INPUT: SETOR MATERI */}
      <section className="mb-10 bg-white p-6 rounded-2xl shadow-sm border border-slate-100">
        <h2 className="text-lg font-bold text-slate-800 mb-4 flex items-center gap-2"><span>✨</span> Setor Materi Baru</h2>
        <form onSubmit={handleSubmit} className="flex flex-col md:flex-row gap-4">
          <input 
            type="url" 
            placeholder="Tempel Link Shopee..." 
            className="flex-1 px-4 py-3 rounded-xl bg-slate-50 border border-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" 
            value={shopeeLink} 
            onChange={(e) => setShopeeLink(e.target.value)} 
            required 
          />
          {/* UBAHAN BARU: Input File Gambar SS */}
          <div className="flex-1 bg-slate-50 border border-slate-200 rounded-xl flex items-center px-4 py-2">
            <span className="text-sm text-slate-500 mr-2">📷 Upload SS:</span>
            <input 
              id="image-upload"
              type="file" 
              accept="image/*"
              className="w-full text-sm text-slate-600 file:mr-4 file:py-1 file:px-3 file:rounded-lg file:border-0 file:text-xs file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100 cursor-pointer"
              onChange={(e) => setProductImage(e.target.files ? e.target.files[0] : null)}
            />
          </div>
          <button type="submit" disabled={isSubmitting} className={`px-8 py-3 rounded-xl font-bold text-white shadow-md transition-all ${isSubmitting ? 'bg-slate-400' : 'bg-blue-600 hover:bg-blue-700'}`}>
            {isSubmitting ? 'Mengirim...' : '🚀 Setor'}
          </button>
        </form>
      </section>

      {/* INDIKATOR LOADING */}
      {isLoading ? (
        <div className="text-center py-20 text-slate-400 animate-pulse font-medium">Memuat antrean konten...</div>
      ) : (
        <section className="grid grid-cols-1 md:grid-cols-3 gap-6">
          
          {/* KOLOM REQUESTED (UNTUK PC) */}
          <div className="bg-slate-100 p-5 rounded-2xl border border-slate-200">
            <h2 className="text-base font-bold mb-5 text-slate-700 flex justify-between">
              MENUNGGU VIDEO <span className="bg-slate-200 px-3 py-1 rounded-full text-xs">{requestedPosts.length}</span>
            </h2>
            <div className="flex flex-col gap-4">
              {requestedPosts.map(post => (
                <div key={post.post_id} className="bg-white p-5 rounded-xl shadow-sm border border-slate-200 hover:shadow-md transition">
                  <a href={post.shopee_link} target="_blank" className="text-blue-600 font-semibold text-sm line-clamp-1 hover:underline mb-2">{post.shopee_link}</a>
                  
                  {/* Tampilkan SS Gambar jika ada */}
                  {post.product_image_url && (
                    <div className="w-full h-32 bg-slate-100 rounded-lg overflow-hidden border border-slate-100 mb-3">
                      <img src={post.product_image_url} alt="SS Produk" className="w-full h-full object-cover" />
                    </div>
                  )}

                  {/* TOMBOL UPLOAD VIDEO DARI PC */}
                  <div className="mt-4">
                    <input 
                      type="file" 
                      accept="video/*"
                      id={`upload-${post.post_id}`} 
                      className="hidden" 
                      onChange={(e) => handleUploadVideo(post.post_id, e.target.files ? e.target.files[0] : null)}
                    />
                    <label 
                      htmlFor={`upload-${post.post_id}`} 
                      className={`block w-full text-center border font-bold py-2.5 rounded-lg transition-all cursor-pointer ${uploadingId === post.post_id ? 'bg-slate-200 text-slate-500 border-slate-300' : 'bg-blue-50 text-blue-600 border-blue-200 hover:bg-blue-600 hover:text-white'}`}
                    >
                      {uploadingId === post.post_id ? '⏳ Mengunggah...' : '⬆️ Upload Video (PC)'}
                    </label>
                  </div>
                </div>
              ))}
              {requestedPosts.length === 0 && <p className="text-sm text-center text-slate-400 py-4">Belum ada request baru.</p>}
            </div>
          </div>

          {/* KOLOM READY (UNTUK ANDROID) */}
          <div className="bg-blue-50/50 p-5 rounded-2xl border border-blue-100">
            <h2 className="text-base font-bold mb-5 text-blue-800 flex justify-between">
              SIAP POSTING (HP) <span className="bg-blue-100 px-3 py-1 rounded-full text-xs">{readyPosts.length}</span>
            </h2>
            <div className="flex flex-col gap-4">
              {readyPosts.map(post => (
                <div key={post.post_id} className="bg-white p-5 rounded-xl shadow-sm border border-blue-200 border-l-4 border-l-blue-500">
                  <a href={post.shopee_link} target="_blank" className="text-sm font-bold text-slate-800 hover:text-blue-600 line-clamp-1 block mb-2">Link Shopee Affiliate</a>
                  <span className="text-xs font-bold text-blue-600 bg-blue-50 px-2 py-1 rounded mb-2 inline-block border border-blue-100">File ID: {post.drive_file_id?.substring(0,8)}...</span>
                  <p className="text-sm text-slate-500 mt-2 italic bg-slate-50 p-3 rounded-lg border border-slate-100">{post.caption}</p>
                  
                  {/* Tombol Eksekusi HP */}
                  <div className="mt-4 flex flex-col gap-2">
                     <button className="w-full bg-blue-600 text-white font-bold py-3 rounded-xl shadow-sm hover:bg-blue-700 active:scale-95 transition">⬇️ Unduh Video</button>
                     <button className="w-full bg-slate-800 text-white font-bold py-3 rounded-xl shadow-sm hover:bg-slate-900 active:scale-95 transition">📋 Salin Teks</button>
                     <button className="w-full bg-emerald-500 text-white font-bold py-3 rounded-xl shadow-sm hover:bg-emerald-600 active:scale-95 transition mt-2">✅ Tandai Selesai</button>
                  </div>
                </div>
              ))}
              {readyPosts.length === 0 && <p className="text-sm text-center text-slate-400 py-4">Tidak ada antrean.</p>}
            </div>
          </div>

          {/* KOLOM POSTED (RIWAYAT) */}
          <div className="bg-emerald-50/50 p-5 rounded-2xl border border-emerald-100">
            <h2 className="text-base font-bold mb-5 text-emerald-800 flex justify-between">
              SELESAI <span className="bg-emerald-100 px-3 py-1 rounded-full text-xs">{postedPosts.length}</span>
            </h2>
             <div className="flex flex-col gap-4">
              {postedPosts.map(post => (
                <div key={post.post_id} className="bg-white p-4 rounded-xl shadow-sm border border-emerald-200 opacity-70">
                  <span className="text-xs font-bold text-emerald-600 flex items-center gap-1"><span>✓</span> Sukses tayang</span>
                </div>
              ))}
              {postedPosts.length === 0 && <p className="text-sm text-center text-slate-400 py-4">Belum ada tayangan hari ini.</p>}
            </div>
          </div>

        </section>
      )}
    </main>
  );
}