"use client";

import { useState, useRef, useCallback } from "react";
import { SectionEditor } from "../_components/SectionEditor";
import { InputField } from "../_components/FormField";
import { adminFetch } from "@/lib/csrf";
import { Upload, X, Loader2, Smartphone, Monitor, Star } from "lucide-react";

interface HeroData {
  headline: string;
  subheadline: string;
  ctaText: string;
  ctaHref: string;
  videos?: string[];
}

const SLOTS = [
  { key: "left", label: "Левое", sublabel: "Диагональ слева" },
  { key: "center", label: "Центр", sublabel: "Главное видео" },
  { key: "right", label: "Правое", sublabel: "Диагональ справа" },
] as const;

function VideoSlot({
  label,
  sublabel,
  src,
  isCenter,
  onUpload,
  onRemove,
  uploading,
}: {
  label: string;
  sublabel: string;
  src: string | null;
  isCenter: boolean;
  onUpload: (file: File) => void;
  onRemove: () => void;
  uploading: boolean;
}) {
  const fileRef = useRef<HTMLInputElement>(null);

  return (
    <div className="space-y-2">
      {/* Label */}
      <div className="flex items-center gap-2">
        <span className="text-sm font-medium text-neutral-300">{label}</span>
        {isCenter && (
          <span className="inline-flex items-center gap-1 rounded-full bg-[#c9a96e]/15 px-2 py-0.5 text-[10px] font-medium text-[#c9a96e]">
            <Smartphone size={10} />
            мобильная версия
          </span>
        )}
      </div>
      <p className="text-xs text-neutral-500">{sublabel}</p>

      {/* Slot */}
      {src ? (
        <div className={`group relative overflow-hidden rounded-lg border ${
          isCenter ? "border-[#c9a96e]/40 ring-1 ring-[#c9a96e]/20" : "border-neutral-700"
        }`}>
          <video
            src={src}
            muted
            loop
            playsInline
            autoPlay
            className="aspect-[9/16] w-full object-cover bg-black"
          />
          <div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-2">
            <p className="truncate text-xs text-neutral-400">
              {src.split("/").pop()}
            </p>
          </div>
          {isCenter && (
            <div className="absolute top-2 left-1/2 -translate-x-1/2 flex items-center gap-1 rounded-full bg-[#c9a96e]/90 px-2 py-0.5 text-[10px] font-bold text-black">
              <Star size={10} fill="currentColor" />
              MAIN
            </div>
          )}
          <button
            onClick={onRemove}
            className="absolute top-2 right-2 rounded-full bg-black/70 p-1.5 text-neutral-400 opacity-0 transition-opacity hover:text-red-400 group-hover:opacity-100"
            title="Удалить"
          >
            <X size={14} />
          </button>
        </div>
      ) : (
        <button
          onClick={() => fileRef.current?.click()}
          disabled={uploading}
          className={`flex aspect-[9/16] w-full items-center justify-center rounded-lg border-2 border-dashed transition-colors disabled:opacity-50 ${
            isCenter
              ? "border-[#c9a96e]/30 text-[#c9a96e]/50 hover:border-[#c9a96e]/60 hover:text-[#c9a96e]"
              : "border-neutral-700 text-neutral-500 hover:border-neutral-500 hover:text-neutral-300"
          }`}
        >
          {uploading ? (
            <Loader2 size={24} className="animate-spin" />
          ) : (
            <div className="flex flex-col items-center gap-2">
              <Upload size={24} />
              <span className="text-xs font-medium">Загрузить</span>
              <span className="text-[10px] opacity-60">MP4, до 50МБ</span>
            </div>
          )}
        </button>
      )}

      <input
        ref={fileRef}
        type="file"
        accept="video/mp4,video/webm"
        className="hidden"
        onChange={(e) => {
          const file = e.target.files?.[0];
          if (file) onUpload(file);
          if (fileRef.current) fileRef.current.value = "";
        }}
      />
    </div>
  );
}

function VideoManager({
  videos,
  onChange,
}: {
  videos: string[];
  onChange: (videos: string[]) => void;
}) {
  const [slots, setSlots] = useState<(string | null)[]>(() => [
    videos[0] || null,
    videos[1] || null,
    videos[2] || null,
  ]);
  const [uploadingIdx, setUploadingIdx] = useState<number | null>(null);

  const syncToParent = useCallback(
    (updated: (string | null)[]) => {
      setSlots(updated);
      // Only propagate when all 3 are filled
      if (updated.every((s) => s !== null)) {
        onChange(updated as string[]);
      }
    },
    [onChange]
  );

  async function handleUpload(idx: number, file: File) {
    setUploadingIdx(idx);
    try {
      const form = new FormData();
      form.append("file", file);
      form.append("folder", "hero");
      const res = await adminFetch("/api/admin/upload", {
        method: "POST",
        body: form,
      });
      if (!res.ok) {
        const err = await res.json();
        alert(err.error || "Ошибка загрузки");
        return;
      }
      const { path } = await res.json();
      const updated = [...slots];
      updated[idx] = path;
      syncToParent(updated);
    } finally {
      setUploadingIdx(null);
    }
  }

  function handleRemove(idx: number) {
    const updated = [...slots];
    updated[idx] = null;
    setSlots(updated);
    // Don't propagate incomplete state — keep old saved videos in DB
  }

  const allFilled = slots.every((s) => s !== null);
  const filledCount = slots.filter((s) => s !== null).length;

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-3">
        <label className="text-sm font-medium text-neutral-300">
          Видео на главном экране
        </label>
        {!allFilled && (
          <span className="inline-flex items-center gap-1 rounded bg-amber-500/10 px-2 py-0.5 text-[11px] text-amber-400">
            Загружено {filledCount}/3 — загрузите все для сохранения
          </span>
        )}
        {allFilled && (
          <span className="inline-flex items-center gap-1 rounded bg-emerald-500/10 px-2 py-0.5 text-[11px] text-emerald-400">
            ✓ Все видео загружены
          </span>
        )}
      </div>

      <div className="grid gap-4 sm:grid-cols-3">
        {SLOTS.map((slot, i) => (
          <VideoSlot
            key={slot.key}
            label={slot.label}
            sublabel={slot.sublabel}
            src={slots[i]}
            isCenter={i === 1}
            uploading={uploadingIdx === i}
            onUpload={(file) => handleUpload(i, file)}
            onRemove={() => handleRemove(i)}
          />
        ))}
      </div>

      <div className="flex gap-4 rounded-lg bg-neutral-800/50 p-3 text-xs text-neutral-500">
        <div className="flex items-center gap-1.5">
          <Monitor size={13} />
          <span>ПК — диагональный сплит из 3 видео</span>
        </div>
        <div className="flex items-center gap-1.5">
          <Smartphone size={13} />
          <span>Телефон — только центральное видео</span>
        </div>
      </div>
    </div>
  );
}

export default function HeroEditorPage() {
  return (
    <SectionEditor<HeroData> sectionKey="hero" title="Главный экран">
      {(data, update) => (
        <>
          <VideoManager
            videos={data.videos || []}
            onChange={(videos) => update({ ...data, videos })}
          />

          <InputField
            label="Заголовок"
            value={data.headline}
            onChange={(v) => update({ ...data, headline: v })}
          />
          <InputField
            label="Подзаголовок"
            value={data.subheadline}
            onChange={(v) => update({ ...data, subheadline: v })}
          />
          <InputField
            label="Текст кнопки"
            value={data.ctaText}
            onChange={(v) => update({ ...data, ctaText: v })}
          />
          <InputField
            label="Ссылка кнопки"
            value={data.ctaHref}
            onChange={(v) => update({ ...data, ctaHref: v })}
            type="url"
          />
        </>
      )}
    </SectionEditor>
  );
}
