'use client';

import { useCallback, useEffect, useState } from 'react';
import { api } from '@/lib/api';
import { Save, Type, AlignLeft } from 'lucide-react';
import { useAuthStore } from '@/store/authStore';

export default function AdminCmsPage() {
  const [contentBlocks, setContentBlocks] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [savingKey, setSavingKey] = useState<string | null>(null);
  const [locale, setLocale] = useState('vi');
  const token = useAuthStore(s => s.token);

  const fetchContent = useCallback(async () => {
    if (!token) return;
    setLoading(true);
    try {
      const res = await api.get('/admin/cms', {
        params: { locale }
      });
      const blocks = Array.isArray(res.data) ? res.data : [];
      setContentBlocks(
        blocks.length > 0
          ? blocks
          : [
              { key: 'home.hero.title', content: '', locale },
              { key: 'home.hero.subtitle', content: '', locale },
              { key: 'auth.login.title', content: '', locale },
            ]
      );
    } catch {
      setContentBlocks([
        { key: 'home.hero.title', content: '', locale },
        { key: 'home.hero.subtitle', content: '', locale },
        { key: 'auth.login.title', content: '', locale },
      ]);
    } finally {
      setLoading(false);
    }
  }, [locale, token]);

  useEffect(() => {
    const timer = window.setTimeout(() => { void fetchContent(); }, 0);
    return () => window.clearTimeout(timer);
  }, [fetchContent]);

  const handleContentChange = (index: number, newContent: string) => {
    const updated = [...contentBlocks];
    updated[index].content = newContent;
    setContentBlocks(updated);
  };

  const handleSave = async (block: any) => {
    if (!token) return;
    setSavingKey(block.key);
    try {
      await api.put(`/admin/cms/${block.key}`, { content: block.content, locale });
      alert('Đã lưu nội dung!');
    } catch {
      alert('Lỗi khi lưu!');
    } finally {
      setSavingKey(null);
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Quản lý Nội dung (CMS)</h1>
          <p className="text-gray-500 text-sm mt-1">Thay đổi văn bản trên website mà không cần sửa code</p>
        </div>
        <div className="flex items-center gap-2 bg-[#141414] border border-white/5 rounded-xl p-1">
          <button
            onClick={() => setLocale('vi')}
            className={`px-4 py-2 rounded-lg text-sm font-bold transition-all ${locale === 'vi' ? 'bg-red-500 text-white' : 'text-gray-400 hover:text-white'}`}
          >
            Tiếng Việt
          </button>
          <button
            onClick={() => setLocale('en')}
            className={`px-4 py-2 rounded-lg text-sm font-bold transition-all ${locale === 'en' ? 'bg-red-500 text-white' : 'text-gray-400 hover:text-white'}`}
          >
            English
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {loading ? (
          <div className="text-gray-500 col-span-full py-10">Đang tải nội dung...</div>
        ) : contentBlocks.map((block, index) => (
          <div key={block.key} className="bg-[#141414] border border-white/5 rounded-2xl p-5 flex flex-col group">
            <div className="flex items-center gap-2 mb-3">
              {block.content.length > 50 ? <AlignLeft className="w-4 h-4 text-gray-500" /> : <Type className="w-4 h-4 text-gray-500" />}
              <span className="text-sm font-bold text-white font-mono">{block.key}</span>
            </div>

            {block.content.length > 50 ? (
              <textarea
                value={block.content}
                onChange={(e) => handleContentChange(index, e.target.value)}
                rows={4}
                className="w-full bg-black/30 border border-white/5 rounded-xl px-3 py-2 text-gray-300 text-sm focus:outline-none focus:border-red-500/50 resize-none flex-1 mb-4"
              />
            ) : (
              <input
                type="text"
                value={block.content}
                onChange={(e) => handleContentChange(index, e.target.value)}
                className="w-full bg-black/30 border border-white/5 rounded-xl px-3 py-2 text-gray-300 text-sm focus:outline-none focus:border-red-500/50 flex-1 mb-4"
              />
            )}

            <div className="mt-auto flex justify-end opacity-0 group-hover:opacity-100 transition-opacity">
              <button
                onClick={() => handleSave(block)}
                disabled={savingKey === block.key}
                className="text-red-400 hover:bg-red-500/10 px-3 py-1.5 rounded-lg text-sm font-bold flex items-center gap-1.5 transition-colors"
              >
                <Save className="w-4 h-4" />
                {savingKey === block.key ? 'Đang lưu...' : 'Lưu lại'}
              </button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
