import React, { useEffect, useState } from 'react';
import {
    generateMusicLyrics,
    getSavedLyrics,
    saveLyrics,
    updateLyrics,
    deleteLyrics,
} from '../../../api';

/* ─────────────────────────────────────────────
   Lyrics Tab
───────────────────────────────────────────── */
const LyricsTab = ({ onUseInCreate }) => {
    const [lyrPrompt, setLyrPrompt]     = useState('');
    const [lyrLoading, setLyrLoading]   = useState(false);
    const [lyrError, setLyrError]       = useState(null);
    const [copied, setCopied]           = useState(null);  // id
    const [saved, setSaved]             = useState([]);     // DB에 저장된 가사
    const [loadingSaved, setLoadingSaved] = useState(true);
    const [editingId, setEditingId]     = useState(null);
    const [editTitle, setEditTitle]     = useState('');
    const [editText, setEditText]       = useState('');

    /* ── 저장된 가사 로드 ── */
    useEffect(() => {
        setLoadingSaved(true);
        getSavedLyrics()
            .then((data) => setSaved(data.lyrics ?? []))
            .catch(() => {})
            .finally(() => setLoadingSaved(false));
    }, []);

    /* ── AI 생성 → 즉시 저장 ── */
    const handleGenerate = async () => {
        if (!lyrPrompt.trim() || lyrLoading) return;
        setLyrLoading(true);
        setLyrError(null);
        try {
            const res = await generateMusicLyrics(lyrPrompt.trim());
            if (res?.text) {
                const record = await saveLyrics({
                    title: res.title || '',
                    text: res.text,
                    prompt: lyrPrompt.trim(),
                });
                setSaved((prev) => [record, ...prev]);
            } else {
                setLyrError('가사 생성 결과가 없습니다');
            }
        } catch (e) {
            setLyrError(e.message || '가사 생성에 실패했습니다');
        } finally {
            setLyrLoading(false);
        }
    };

    /* ── 복사 ── */
    const handleCopy = (text, id) => {
        navigator.clipboard.writeText(text).then(() => {
            setCopied(id);
            setTimeout(() => setCopied(null), 2000);
        });
    };

    /* ── 삭제 ── */
    const handleDelete = async (id) => {
        try {
            await deleteLyrics(id);
            setSaved((prev) => prev.filter((l) => l.id !== id));
        } catch {}
    };

    /* ── 수정 시작 ── */
    const startEdit = (item) => {
        setEditingId(item.id);
        setEditTitle(item.title);
        setEditText(item.text);
    };

    /* ── 수정 저장 ── */
    const handleSaveEdit = async () => {
        if (editingId == null) return;
        try {
            const updated = await updateLyrics(editingId, { title: editTitle, text: editText });
            setSaved((prev) => prev.map((l) => l.id === editingId ? updated : l));
            setEditingId(null);
        } catch {}
    };

    /* ── 수정 취소 ── */
    const cancelEdit = () => setEditingId(null);

    return (
        <div className="ms-lyrics-tab">
            <div className="ms-lyrics-tab__form">
                <div className="ms-lyrics-tab__head">
                    <h2 className="ms-lyrics-tab__title">AI Lyrics Generator</h2>
                    <p className="ms-lyrics-tab__desc">
                        원하는 분위기, 주제, 스타일을 설명하면 AI가 가사를 작성합니다.
                    </p>
                </div>

                <div className="ms-lyrics-tab__input-wrap">
                    <textarea
                        className="ms-lyrics-tab__input"
                        placeholder="예: 비 오는 밤, 혼자 걷는 도시의 거리를 배경으로 한 감성적인 발라드 가사"
                        value={lyrPrompt}
                        onChange={(e) => setLyrPrompt(e.target.value)}
                        rows={3}
                        maxLength={200}
                        onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleGenerate(); } }}
                    />
                    <div className="ms-lyrics-tab__input-footer">
                        <span className="ms-lyrics-tab__count">{lyrPrompt.length}/200</span>
                        <button
                            type="button"
                            className={`ms-btn ms-btn--accent ${lyrLoading ? 'is-loading' : ''}`}
                            onClick={handleGenerate}
                            disabled={!lyrPrompt.trim() || lyrLoading}
                        >
                            {lyrLoading ? (
                                <><span className="ms-btn__spinner" /> 생성 중...</>
                            ) : (
                                '✨ 가사 생성'
                            )}
                        </button>
                    </div>
                </div>

                {lyrError && (
                    <div className="ms-error-banner">
                        <span>⚠ {lyrError}</span>
                    </div>
                )}
            </div>

            {lyrLoading && (
                <div className="ms-lyrics-tab__loading">
                    <div className="ms-lyrics-tab__loading-bar" />
                    <p>AI가 가사를 작성하고 있습니다...</p>
                </div>
            )}

            {/* 저장된 가사 목록 */}
            {loadingSaved && (
                <div className="ms-lyrics-tab__loading">
                    <div className="ms-lyrics-tab__loading-bar" />
                    <p>저장된 가사를 불러오는 중...</p>
                </div>
            )}

            {!loadingSaved && saved.length === 0 && !lyrLoading && (
                <div className="ms-lyrics-tab__empty">
                    <span className="ms-lyrics-tab__empty-icon">🎤</span>
                    <p>저장된 가사가 없습니다</p>
                    <p className="ms-lyrics-tab__empty-hint">
                        프롬프트를 입력하면 AI가 [Verse], [Chorus] 등 섹션이 포함된 가사를 작성합니다
                    </p>
                </div>
            )}

            <div className="ms-lyrics-tab__results">
                {saved.map((item) => (
                    <div key={item.id} className={`ms-lyrics-card ${editingId === item.id ? 'is-editing' : ''}`}>
                        <div className="ms-lyrics-card__header">
                            {editingId === item.id ? (
                                <input
                                    className="ms-lyrics-card__title-input"
                                    value={editTitle}
                                    onChange={(e) => setEditTitle(e.target.value)}
                                    placeholder="제목"
                                />
                            ) : (
                                <>
                                    {item.title && <h3 className="ms-lyrics-card__title">{item.title}</h3>}
                                    <span className="ms-lyrics-card__prompt">{item.prompt}</span>
                                </>
                            )}
                            <span className="ms-lyrics-card__date">
                                {item.created_at ? new Date(item.created_at).toLocaleDateString('ko-KR') : ''}
                            </span>
                        </div>

                        {editingId === item.id ? (
                            <textarea
                                className="ms-lyrics-card__text-input"
                                value={editText}
                                onChange={(e) => setEditText(e.target.value)}
                                rows={12}
                            />
                        ) : (
                            <pre className="ms-lyrics-card__text">{item.text}</pre>
                        )}

                        <div className="ms-lyrics-card__actions">
                            {editingId === item.id ? (
                                <>
                                    <button type="button" className="ms-btn ms-btn--accent ms-btn--sm" onClick={handleSaveEdit}>
                                        ✓ 저장
                                    </button>
                                    <button type="button" className="ms-btn ms-btn--ghost ms-btn--sm" onClick={cancelEdit}>
                                        취소
                                    </button>
                                </>
                            ) : (
                                <>
                                    <button
                                        type="button"
                                        className="ms-btn ms-btn--ghost ms-btn--sm"
                                        onClick={() => handleCopy(item.text, item.id)}
                                    >
                                        {copied === item.id ? '✓ 복사됨' : '📋 복사'}
                                    </button>
                                    <button
                                        type="button"
                                        className="ms-btn ms-btn--ghost ms-btn--sm"
                                        onClick={() => onUseInCreate(item.text)}
                                    >
                                        🎵 Create에서 사용
                                    </button>
                                    <button
                                        type="button"
                                        className="ms-btn ms-btn--ghost ms-btn--sm"
                                        onClick={() => startEdit(item)}
                                    >
                                        ✏️ 수정
                                    </button>
                                    <button
                                        type="button"
                                        className="ms-btn ms-btn--ghost ms-btn--sm ms-btn--danger-text"
                                        onClick={() => handleDelete(item.id)}
                                    >
                                        🗑 삭제
                                    </button>
                                </>
                            )}
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
};

export default LyricsTab;
