import { useEffect, useRef, useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { loginSlideApi } from '../../api/endpoints';
import { ApiRequestError } from '../../api/client';
import type { LoginSlideDto } from '../../api/types';
import { Button } from '../../components/ui/Button';
import { EmptyState, ErrorState, Skeleton } from '../../components/ui/States';
import { IconImage, IconPlus } from '../../components/ui/icons';
import './admin.css';

/**
 * 관리자 — 로그인 슬라이드 관리 (M18 · /admin/login-slides).
 * 로그인 화면 좌측 캐러셀에 노출할 이미지+문구를 등록·수정·삭제·활성 토글한다.
 * 공개 노출 규칙: 활성 슬라이드 중 최신 등록순(created_at DESC) 최대 5건.
 */
export function LoginSlideAdminPage() {
  const { t } = useTranslation();
  const [slides, setSlides] = useState<LoginSlideDto[] | null>(null);
  const [loadError, setLoadError] = useState<string | null>(null);

  // 추가 폼 상태
  const [file, setFile] = useState<File | null>(null);
  const [preview, setPreview] = useState<string | null>(null);
  const [title, setTitle] = useState('');
  const [caption, setCaption] = useState('');
  const [formError, setFormError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [busyId, setBusyId] = useState<number | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  async function load() {
    setLoadError(null);
    setSlides(null);
    try {
      setSlides(await loginSlideApi.adminList());
    } catch (err) {
      setSlides([]);
      setLoadError(err instanceof ApiRequestError ? err.message : t('slide.listError'));
    }
  }

  useEffect(() => {
    void load();
  }, []);

  // 파일 선택 → 미리보기 URL 관리(누수 방지 revoke)
  useEffect(() => {
    if (!file) {
      setPreview(null);
      return;
    }
    const url = URL.createObjectURL(file);
    setPreview(url);
    return () => URL.revokeObjectURL(url);
  }, [file]);

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    setFormError(null);
    if (!file) {
      setFormError(t('slide.errImage'));
      return;
    }
    if (!title.trim()) {
      setFormError(t('slide.errTitle'));
      return;
    }
    setSubmitting(true);
    try {
      const created = await loginSlideApi.create(file, title.trim(), caption.trim());
      setSlides((prev) => [created, ...(prev ?? [])]); // 최신 등록이 맨 위(공개 로테이션 첫 슬라이드)
      setFile(null);
      setTitle('');
      setCaption('');
      if (fileInputRef.current) fileInputRef.current.value = '';
    } catch (err) {
      setFormError(err instanceof ApiRequestError ? err.message : t('slide.createFail'));
    } finally {
      setSubmitting(false);
    }
  }

  async function handleToggleActive(slide: LoginSlideDto) {
    setBusyId(slide.id);
    try {
      const updated = await loginSlideApi.update(slide.id, {
        title: slide.title,
        caption: slide.caption,
        sortOrder: slide.sortOrder,
        active: !slide.active,
      });
      setSlides((prev) => (prev ?? []).map((s) => (s.id === slide.id ? updated : s)));
    } catch (err) {
      setLoadError(err instanceof ApiRequestError ? err.message : t('slide.updateFail'));
    } finally {
      setBusyId(null);
    }
  }

  async function handleDelete(slide: LoginSlideDto) {
    if (!window.confirm(t('slide.deleteConfirm', { title: slide.title }))) return;
    setBusyId(slide.id);
    try {
      await loginSlideApi.remove(slide.id);
      setSlides((prev) => (prev ?? []).filter((s) => s.id !== slide.id));
    } catch (err) {
      setLoadError(err instanceof ApiRequestError ? err.message : t('slide.deleteFail'));
    } finally {
      setBusyId(null);
    }
  }

  const activeCount = (slides ?? []).filter((s) => s.active).length;

  return (
    <div className="kx-admin">
      <header className="kx-admin__head">
        <div>
          <h1 className="kx-admin__title">{t('slide.title')}</h1>
          <p className="kx-admin__subtitle">
            <Trans i18nKey="slide.subtitle" components={[<strong key="s" />]} />
          </p>
        </div>
      </header>

      {/* 새 슬라이드 추가 */}
      <section className="kx-card kx-slideadm__form-card" aria-label={t('slide.addAria')}>
        <div className="kx-card__head">
          <h2><IconPlus className="kx-title-ic" size={18} />{t('slide.addTitle')}</h2>
        </div>
        <form className="kx-slideadm__form" onSubmit={handleCreate}>
          <div className="kx-slideadm__form-grid">
            <div className="kx-slideadm__upload">
              <label className="kx-slideadm__label" htmlFor="slide-image">
                {t('slide.imageLabel')}
              </label>
              <input
                id="slide-image"
                ref={fileInputRef}
                type="file"
                accept="image/png,image/jpeg,image/webp"
                onChange={(e) => setFile(e.target.files?.[0] ?? null)}
              />
              <div
                className={`kx-slideadm__preview ${preview ? 'has-image' : ''}`}
                style={preview ? { backgroundImage: `url(${preview})` } : undefined}
              >
                {!preview && <span>{t('slide.preview')}</span>}
              </div>
            </div>
            <div className="kx-slideadm__fields">
              <div className="kx-adm-field">
                <label htmlFor="slide-title">{t('slide.titleLabel')}</label>
                <input
                  id="slide-title"
                  type="text"
                  maxLength={200}
                  placeholder={t('slide.titlePh')}
                  value={title}
                  onChange={(e) => setTitle(e.target.value)}
                  required
                />
              </div>
              <div className="kx-adm-field">
                <label htmlFor="slide-caption">{t('slide.captionLabel')}</label>
                <input
                  id="slide-caption"
                  type="text"
                  maxLength={500}
                  placeholder={t('slide.captionPh')}
                  value={caption}
                  onChange={(e) => setCaption(e.target.value)}
                />
              </div>
              {formError && (
                <p className="kx-slideadm__error" role="alert">
                  {formError}
                </p>
              )}
              <div className="kx-slideadm__form-actions">
                <Button type="submit" disabled={submitting}>
                  {submitting ? t('slide.submitting') : t('slide.submit')}
                </Button>
              </div>
            </div>
          </div>
        </form>
      </section>

      {/* 목록 */}
      <section className="kx-card kx-slideadm__list-card" aria-label={t('slide.listAria')}>
        <div className="kx-card__head">
          <h2>
            <IconImage className="kx-title-ic" size={18} />
            {t('slide.registered')}{' '}
            {slides && (
              <span className="kx-slideadm__count tnum">
                {t('slide.countActive', { total: slides.length, active: activeCount })}
              </span>
            )}
          </h2>
        </div>

        {loadError && <ErrorState message={loadError} onRetry={() => void load()} />}

        {slides === null ? (
          <div className="kx-slideadm__skeletons">
            <Skeleton height={64} />
            <Skeleton height={64} />
            <Skeleton height={64} />
          </div>
        ) : slides.length === 0 && !loadError ? (
          <EmptyState
            title={t('slide.emptyTitle')}
            description={t('slide.emptyDesc')}
          />
        ) : (
          <ul className="kx-slideadm__list">
            {slides.map((s, i) => (
              <li key={s.id} className={`kx-slideadm__row ${s.active ? '' : 'is-inactive'}`}>
                <div
                  className="kx-slideadm__thumb"
                  style={{ backgroundImage: `url(${s.imageUrl})` }}
                  aria-hidden="true"
                />
                <div className="kx-slideadm__body">
                  <div className="kx-slideadm__row-top">
                    <strong className="kx-slideadm__row-title">{s.title}</strong>
                    {s.active && i < 5 && <span className="kx-slideadm__live-badge">{t('slide.live')}</span>}
                    {!s.active && <span className="kx-slideadm__off-badge">{t('slide.inactive')}</span>}
                  </div>
                  {s.caption && <p className="kx-slideadm__row-caption">{s.caption}</p>}
                  <p className="kx-slideadm__row-meta tnum">{t('slide.registeredAt', { date: s.createdAt })}</p>
                </div>
                <div className="kx-slideadm__actions">
                  <label className="kx-slideadm__toggle">
                    <input
                      type="checkbox"
                      checked={s.active}
                      disabled={busyId === s.id}
                      onChange={() => void handleToggleActive(s)}
                    />
                    <span>{t('slide.active')}</span>
                  </label>
                  <Button
                    variant="danger"
                    type="button"
                    disabled={busyId === s.id}
                    onClick={() => void handleDelete(s)}
                  >
                    {t('slide.delete')}
                  </Button>
                </div>
              </li>
            ))}
          </ul>
        )}
      </section>
    </div>
  );
}
