"use client";
import React, { useState } from 'react';

export function QuoteEditor({ initialData }: { initialData: any }) {
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [formData, setFormData] = useState({
    quoteText: initialData?.quoteText || "Konsistensi adalah kunci keberhasilan.",
    quoteAuthor: initialData?.quoteAuthor || "Anonim",
  });

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setSuccess(false);

    try {
      const res = await fetch('/api/admin/quote', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData)
      });
      if (res.ok) {
        setSuccess(true);
        setTimeout(() => setSuccess(false), 3000);
      } else {
        alert('Gagal menyimpan kata-kata hari ini.');
      }
    } catch (e) {
      alert('Terjadi kesalahan.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="bg-white p-8 rounded-2xl shadow-sm border border-gray-200">
      <h2 className="text-xl font-bold text-gray-900 mb-6">Kata-Kata Hari Ini (Quote of the Day)</h2>
      
      {success && (
        <div className="mb-6 p-4 bg-green-50 text-green-700 border border-green-200 rounded-xl flex items-center gap-3">
          <span className="text-xl">✅</span> Berhasil diperbarui!
        </div>
      )}
      
      <form onSubmit={handleSubmit} className="space-y-6">
        <div>
          <label className="block text-sm font-semibold text-gray-700 mb-2">Teks Kata-Kata</label>
          <textarea
            name="quoteText"
            value={formData.quoteText}
            onChange={handleChange}
            required
            className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:bg-white transition-colors"
            rows={3}
          />
        </div>
        
        <div>
          <label className="block text-sm font-semibold text-gray-700 mb-2">Penulis / Tokoh</label>
          <input
            type="text"
            name="quoteAuthor"
            value={formData.quoteAuthor}
            onChange={handleChange}
            required
            className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:bg-white transition-colors"
          />
        </div>
        
        <button
          type="submit"
          disabled={loading}
          className="w-full bg-gray-900 hover:bg-black text-white font-bold py-4 rounded-xl transition-colors disabled:opacity-50"
        >
          {loading ? 'Menyimpan...' : 'Simpan Kata-Kata'}
        </button>
      </form>
    </div>
  );
}
