import { useState } from 'react';

const emptyIntro = { title: '', content: '', is_main: 0 };

export default function IntroTab({ introductions, editing, api, onRefresh }) {
    const [form, setForm] = useState(null);
    const [copiedId, setCopiedId] = useState(null);

    const save = async () => {
        if (form.id) {
            await api.editIntro(form.id, { title: form.title, content: form.content });
        } else {
            await api.addIntro(form);
        }
        setForm(null);
        onRefresh();
    };

    const remove = async (id) => {
        await api.removeIntro(id);
        onRefresh();
    };

    const setMain = async (id) => {
        await api.setMainIntro(id);
        onRefresh();
    };

    const copyToClipboard = async (intro) => {
        try {
            await navigator.clipboard.writeText(intro.content);
            setCopiedId(intro.id);
            setTimeout(() => setCopiedId(null), 1500);
        } catch {
            /* 무시 */
        }
    };

    return (
        <div className="pf-intro-tab">
            {editing && (
                <div className="pf-intro-tab__toolbar">
                    <button className="button primary" onClick={() => setForm({...emptyIntro})}>+ 새 글 작성</button>
                </div>
            )}

            {/* 작성/수정 폼 */}
            {form && (
                <div className="pf-edit-form">
                    <label>버전명 <input value={form.title} placeholder="예: 이직용 짧은 버전" onChange={(e) => setForm(f => ({...f, title: e.target.value}))} /></label>
                    <label>본문 <textarea value={form.content} rows={8} onChange={(e) => setForm(f => ({...f, content: e.target.value}))} /></label>
                    <div className="pf-edit-form__actions">
                        <button className="button ghost" onClick={() => setForm(null)}>취소</button>
                        <button className="button primary" onClick={save}>저장</button>
                    </div>
                </div>
            )}

            {/* 자기소개 목록 */}
            <div className="pf-intro-list">
                {introductions.length === 0 && <p className="pf-empty">자기소개 글이 없습니다.</p>}
                {introductions.map(intro => (
                    <div key={intro.id} className={`pf-intro-card${intro.is_main ? ' is-main' : ''}`}>
                        <div className="pf-intro-card__header">
                            <span className="pf-intro-card__title">
                                {intro.is_main ? <span className="pf-intro-card__badge">MAIN</span> : null}
                                {intro.title || '제목 없음'}
                            </span>
                            <span className="pf-intro-card__date">
                                {intro.updated_at ? new Date(intro.updated_at).toLocaleDateString('ko-KR') : ''}
                            </span>
                        </div>
                        <p className="pf-intro-card__preview">{intro.content}</p>
                        <div className="pf-intro-card__actions">
                            <button
                                className="button ghost"
                                onClick={() => copyToClipboard(intro)}
                            >
                                {copiedId === intro.id ? '복사됨!' : '복사'}
                            </button>
                            {editing && (
                                <>
                                    <button className="button ghost" onClick={() => setForm({...intro})}>수정</button>
                                    {!intro.is_main && <button className="button ghost" onClick={() => setMain(intro.id)}>메인 지정</button>}
                                    <button className="button ghost" onClick={() => remove(intro.id)}>삭제</button>
                                </>
                            )}
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
}
