"use client";

import {
  useState,
  useEffect,
  useRef,
  useCallback,
  DragEvent,
  ChangeEvent,
} from "react";
import Image from "next/image";
import Cookies from "js-cookie";
import {
  Film,
  Music2,
  Zap,
  Radio,
  Mic2,
  ImageIcon,
  Headphones,
  Upload,
  CheckCircle2,
  AlertCircle,
  X,
  Plus,
  ChevronDown,
  Columns3Cog,
} from "lucide-react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchCategories } from "@/store/slices/categorySlice";
import {
  uploadService,
  uploadImage,
  type Language,
  type PodcastItem,
  type UploadProgressCallback,
} from "@/services/uploadService";

/* ── Content type config ────────────────────────────────────────────────────── */

const TYPES = [
  {
    id: "video",
    label: "Video",
    icon: Film,
    color: "#fc0000",
    accept: "video/*",
  },
  {
    id: "music",
    label: "Music",
    icon: Music2,
    color: "#22d3ee",
    accept: "audio/*",
  },
  {
    id: "reels",
    label: "Reels",
    icon: Zap,
    color: "#a855f7",
    accept: "video/*",
  },
  {
    id: "radio",
    label: "Radio",
    icon: Radio,
    color: "#f59e0b",
    accept: "audio/*",
  },
  {
    id: "episode",
    label: "Episode",
    icon: Mic2,
    color: "#10b981",
    accept: "audio/*,video/*",
  },
  {
    id: "feed",
    label: "Feed",
    icon: ImageIcon,
    color: "#f43f5e",
    accept: "image/*,video/*",
  },
  {
    id: "podcast",
    label: "Podcast",
    icon: Headphones,
    color: "#8b5cf6",
    accept: "image/*",
  },
] as const;

type ContentType = (typeof TYPES)[number]["id"];

function getTypeCfg(id: ContentType) {
  return TYPES.find((t) => t.id === id)!;
}

/* ── Reusable UI atoms ──────────────────────────────────────────────────────── */

function Toggle({
  value,
  onChange,
  color = "var(--accent)",
}: {
  value: boolean;
  onChange: (v: boolean) => void;
  color?: string;
}) {
  return (
    <button
      type="button"
      className="relative flex-shrink-0 transition-all duration-200"
      style={{
        width: 36,
        height: 20,
        borderRadius: 999,
        background: value ? color : "var(--border)",
      }}
      onClick={() => onChange(!value)}
    >
      <span
        className="absolute top-[2px] left-[2px] w-4 h-4 rounded-full bg-white transition-all duration-200"
        style={{ transform: value ? "translateX(16px)" : "translateX(0)" }}
      />
    </button>
  );
}

function FieldLabel({
  children,
  required,
}: {
  children: React.ReactNode;
  required?: boolean;
}) {
  return (
    <label
      className="block text-[11px] font-semibold mb-1.5"
      style={{ color: "#aaa" }}
    >
      {children}
      {required && (
        <span className="ml-0.5" style={{ color: "#f43f5e" }}>
          *
        </span>
      )}
    </label>
  );
}

function Field({
  label,
  required,
  error,
  children,
}: {
  label: string;
  required?: boolean;
  error?: string;
  children: React.ReactNode;
}) {
  return (
    <div className="flex flex-col gap-0">
      <FieldLabel required={required}>{label}</FieldLabel>
      {children}
      {error && (
        <p className="text-[10px] mt-1" style={{ color: "#f43f5e" }}>
          {error}
        </p>
      )}
    </div>
  );
}

function Input({
  value,
  onChange,
  placeholder,
  type = "text",
  error,
}: {
  value: string;
  onChange: (v: string) => void;
  placeholder?: string;
  type?: string;
  error?: boolean;
}) {
  return (
    <input
      type={type}
      className="w-full h-9 px-3 rounded-lg text-[12px] outline-none transition-all"
      style={{
        background: "var(--btn-ghost)",
        border: `1px solid ${error ? "#f43f5e60" : "var(--border)"}`,
        color: "var(--text-primary)",
      }}
      placeholder={placeholder}
      value={value}
      onChange={(e) => onChange(e.target.value)}
      onFocus={(e) => {
        e.currentTarget.style.borderColor = error
          ? "#f43f5e"
          : "rgba(var(--accent-rgb),0.5)";
      }}
      onBlur={(e) => {
        e.currentTarget.style.borderColor = error
          ? "#f43f5e60"
          : "var(--border)";
      }}
    />
  );
}

function Textarea({
  value,
  onChange,
  placeholder,
  rows = 3,
  error,
}: {
  value: string;
  onChange: (v: string) => void;
  placeholder?: string;
  rows?: number;
  error?: boolean;
}) {
  return (
    <textarea
      className="w-full px-3 py-2 rounded-lg text-[12px] outline-none resize-none transition-all"
      style={{
        background: "var(--btn-ghost)",
        border: `1px solid ${error ? "#f43f5e60" : "var(--border)"}`,
        color: "var(--text-primary)",
      }}
      placeholder={placeholder}
      value={value}
      rows={rows}
      onChange={(e) => onChange(e.target.value)}
      onFocus={(e) => {
        e.currentTarget.style.borderColor = error
          ? "#f43f5e"
          : "rgba(var(--accent-rgb),0.5)";
      }}
      onBlur={(e) => {
        e.currentTarget.style.borderColor = error
          ? "#f43f5e60"
          : "var(--border)";
      }}
    />
  );
}

function Select({
  value,
  onChange,
  options,
  placeholder,
  error,
}: {
  value: string;
  onChange: (v: string) => void;
  options: { id: string | number; name: string }[];
  placeholder?: string;
  error?: boolean;
}) {
  return (
    <div className="relative">
      <select
        className="w-full h-9 px-3 pr-8 rounded-lg text-[12px] outline-none appearance-none cursor-pointer transition-all"
        style={{
          background: "var(--btn-ghost)",
          border: `1px solid ${error ? "#f43f5e60" : "var(--border)"}`,
          color: "var(--text-primary)",
        }}
        value={value}
        onChange={(e) => onChange(e.target.value)}
      >
        <option value="" style={{ background: "#16213e" }}>
          {placeholder || "Select…"}
        </option>
        {options.map((o) => (
          <option
            key={o.id}
            value={String(o.id)}
            style={{ background: "#16213e" }}
          >
            {o.name}
          </option>
        ))}
      </select>
      <ChevronDown
        size={13}
        color="#888"
        className="absolute right-2.5 top-1/2 -translate-y-1/2 pointer-events-none"
      />
    </div>
  );
}

/* ── File drop zone ─────────────────────────────────────────────────────────── */

function DropZone({
  file,
  onFile,
  accept,
  label,
  icon: Icon,
  color,
  error,
}: {
  file: File | null;
  onFile: (f: File | null) => void;
  accept: string;
  label: string;
  icon?: React.ElementType;
  color?: string;
  error?: boolean;
}) {
  const [dragging, setDragging] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);
  const preview =
    file && file.type.startsWith("image/") ? URL.createObjectURL(file) : null;

  const onDrop = useCallback(
    (e: DragEvent<HTMLDivElement>) => {
      e.preventDefault();
      setDragging(false);
      const f = e.dataTransfer.files[0];
      if (f) onFile(f);
    },
    [onFile],
  );

  const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
    const f = e.target.files?.[0] ?? null;
    onFile(f);
  };

  return (
    <div
      className="relative flex flex-col items-center justify-center rounded-xl cursor-pointer transition-all duration-200 overflow-hidden"
      style={{
        minHeight: 100,
        border: `1.5px dashed ${dragging ? color || "var(--accent)" : error ? "#f43f5e60" : "var(--border)"}`,
        background: dragging
          ? `${color || "var(--accent)"}10`
          : "var(--border-soft)",
        boxShadow: dragging ? `0 0 20px ${color || "var(--accent)"}20` : "none",
      }}
      onDragOver={(e) => {
        e.preventDefault();
        setDragging(true);
      }}
      onDragLeave={() => setDragging(false)}
      onDrop={onDrop}
      onClick={() => inputRef.current?.click()}
    >
      {preview ? (
        <>
          <Image
            src={preview}
            alt="preview"
            fill
            className="object-cover opacity-70"
          />
          <div
            className="absolute inset-0 flex items-center justify-center"
            style={{ background: "rgba(0,0,0,0.45)" }}
          >
            <p className="text-[11px] font-semibold text-[#ffffff]">{file?.name}</p>
          </div>
        </>
      ) : file ? (
        <div className="flex flex-col items-center gap-1.5 py-4 px-3 text-center">
          {Icon && (
            <Icon
              size={18}
              color={color || "var(--accent)"}
              strokeWidth={1.5}
            />
          )}
          <p className="text-[11px] font-semibold truncate max-w-[180px]" style={{ color: "var(--text-primary)" }}>
            {file.name}
          </p>
          <p className="text-[10px]" style={{ color: "#666" }}>
            {(file.size / 1024 / 1024).toFixed(1)} MB
          </p>
        </div>
      ) : (
        <div className="flex flex-col items-center gap-2 py-5 px-4 text-center">
          <div
            className="w-9 h-9 rounded-xl flex items-center justify-center"
            style={{ background: `${color || "var(--accent)"}15` }}
          >
            {Icon ? (
              <Icon
                size={16}
                color={color || "var(--accent)"}
                strokeWidth={1.5}
              />
            ) : (
              <Upload
                size={16}
                color={color || "var(--accent)"}
                strokeWidth={1.5}
              />
            )}
          </div>
          <div>
            <p className="text-[11px] font-semibold" style={{ color: "var(--text-primary)" }}>{label}</p>
            <p className="text-[10px] mt-0.5" style={{ color: "#555" }}>
              drag & drop or click
            </p>
          </div>
        </div>
      )}

      {file && (
        <button
          type="button"
          className="absolute top-1.5 right-1.5 w-5 h-5 rounded-full flex items-center justify-center z-10"
          style={{ background: "rgba(0,0,0,0.7)" }}
          onClick={(e) => {
            e.stopPropagation();
            onFile(null);
          }}
        >
          <X size={10} color="#fff" />
        </button>
      )}

      <input
        ref={inputRef}
        type="file"
        className="hidden"
        accept={accept}
        onChange={onInputChange}
      />
    </div>
  );
}

/* ── Image drop zone (small) ────────────────────────────────────────────────── */

function ImageDrop({
  file,
  onFile,
  label,
  color,
  error,
}: {
  file: File | null;
  onFile: (f: File | null) => void;
  label: string;
  color?: string;
  error?: boolean;
}) {
  return (
    <DropZone
      file={file}
      onFile={onFile}
      accept="image/*"
      label={label}
      icon={ImageIcon}
      color={color}
      error={error}
    />
  );
}

/* ── Toggle row ─────────────────────────────────────────────────────────────── */

function ToggleRow({
  label,
  value,
  onChange,
  color,
}: {
  label: string;
  value: boolean;
  onChange: (v: boolean) => void;
  color?: string;
}) {
  return (
    <div className="flex items-center justify-between gap-3">
      <span className="text-[12px]" style={{ color: "#bbb" }}>
        {label}
      </span>
      <Toggle value={value} onChange={onChange} color={color} />
    </div>
  );
}

/* ── Upload progress overlay ────────────────────────────────────────────────── */

function ProgressOverlay({
  pct,
  label,
  color,
}: {
  pct: number;
  label: string;
  color: string;
}) {
  return (
    <div
      className="fixed inset-0 z-[200] flex flex-col items-center justify-center"
      style={{ background: "rgba(0,0,0,0.85)", backdropFilter: "blur(12px)" }}
    >
      <div
        className="w-80 rounded-2xl p-8 flex flex-col items-center gap-5"
        style={{
          background: "var(--card)",
          border: "1px solid var(--border)",
        }}
      >
        {/* Animated ring */}
        <div className="relative w-20 h-20">
          <svg
            width="80"
            height="80"
            viewBox="0 0 80 80"
            className="-rotate-90"
          >
            <circle
              cx="40"
              cy="40"
              r="34"
              fill="none"
              stroke="var(--border-soft)"
              strokeWidth="6"
            />
            <circle
              cx="40"
              cy="40"
              r="34"
              fill="none"
              stroke={color}
              strokeWidth="6"
              strokeLinecap="round"
              strokeDasharray={`${2 * Math.PI * 34}`}
              strokeDashoffset={`${2 * Math.PI * 34 * (1 - pct / 100)}`}
              style={{ transition: "stroke-dashoffset 0.3s ease" }}
            />
          </svg>
          <div className="absolute inset-0 flex items-center justify-center">
            <span className="text-sm font-bold" style={{ color: "var(--text-primary)" }}>{pct}%</span>
          </div>
        </div>

        <div className="text-center">
          <p className="text-sm font-semibold" style={{ color: "var(--text-primary)" }}>{label}</p>
          <p className="text-[11px] mt-1" style={{ color: "#666" }}>
            Please don't close this window
          </p>
        </div>

        {/* Bar */}
        <div
          className="w-full h-1 rounded-full"
          style={{ background: "var(--border-soft)" }}
        >
          <div
            className="h-full rounded-full transition-all duration-300"
            style={{ width: `${pct}%`, background: color }}
          />
        </div>
      </div>
    </div>
  );
}

/* ── Success overlay ────────────────────────────────────────────────────────── */

function SuccessOverlay({
  color,
  onDone,
}: {
  color: string;
  onDone: () => void;
}) {
  return (
    <div
      className="fixed inset-0 z-[200] flex flex-col items-center justify-center"
      style={{ background: "rgba(0,0,0,0.85)", backdropFilter: "blur(12px)" }}
    >
      <div
        className="w-72 rounded-2xl p-8 flex flex-col items-center gap-4"
        style={{
          background: "var(--card)",
          border: "1px solid var(--border)",
          animation: "upload-success 0.5s cubic-bezier(0.34,1.5,0.64,1) both",
        }}
      >
        <div
          className="w-16 h-16 rounded-full flex items-center justify-center"
          style={{ background: `${color}15`, border: `2px solid ${color}` }}
        >
          <CheckCircle2 size={30} color={color} strokeWidth={1.8} />
        </div>
        <div className="text-center">
          <p className="text-sm font-bold" style={{ color: "var(--text-primary)" }}>Uploaded!</p>
          <p className="text-[11px] mt-1" style={{ color: "#888" }}>
            Your content is being processed
          </p>
        </div>
        <button
          className="w-full h-9 rounded-lg text-[12px] font-bold text-[#ffffff] transition-all active:scale-95"
          style={{ background: color }}
          onClick={onDone}
        >
          Upload Another
        </button>
      </div>
    </div>
  );
}

/* ── Form section card ──────────────────────────────────────────────────────── */

function Card({
  children,
  title,
}: {
  children: React.ReactNode;
  title?: string;
}) {
  return (
    <div
      className="rounded-xl p-5 flex flex-col gap-4"
      style={{
        background: "var(--card)",
        border: "1px solid var(--border-soft)",
      }}
    >
      {title && (
        <p
          className="text-[11px] font-bold uppercase tracking-widest"
          style={{ color: "#555" }}
        >
          {title}
        </p>
      )}
      {children}
    </div>
  );
}

/* ── Shared metadata fields ─────────────────────────────────────────────────── */

type Errors = Record<string, string>;

function MetaFields({
  fields,
  setField,
  categories,
  languages,
  errors,
  showCategory = true,
  showLanguage = true,
}: {
  fields: Record<string, string>;
  setField: (k: string, v: string) => void;
  categories: { id: number; name: string }[];
  languages: Language[];
  errors: Errors;
  color: string;
  showCategory?: boolean;
  showLanguage?: boolean;
}) {
  return (
    <>
      <Field label="Title" required error={errors.title}>
        <Input
          value={fields.title || ""}
          onChange={(v) => setField("title", v)}
          placeholder="Enter title…"
          error={!!errors.title}
        />
      </Field>
      {showCategory && (
        <Field label="Category" required error={errors.categoryId}>
          <Select
            value={fields.categoryId || ""}
            onChange={(v) => setField("categoryId", v)}
            options={categories.map((c) => ({ id: c.id, name: c.name }))}
            placeholder="Select category"
            error={!!errors.categoryId}
          />
        </Field>
      )}
      {showLanguage && (
        <Field label="Language" required error={errors.languageId}>
          <Select
            value={fields.languageId || ""}
            onChange={(v) => setField("languageId", v)}
            options={languages.map((l) => ({ id: l.id, name: l.name }))}
            placeholder="Select language"
            error={!!errors.languageId}
          />
        </Field>
      )}
      <Field label="Description">
        <Textarea
          value={fields.description || ""}
          onChange={(v) => setField("description", v)}
          placeholder="Add a description…"
        />
      </Field>
    </>
  );
}

/* ── Feed media item ────────────────────────────────────────────────────────── */

interface FeedMedia {
  file: File;
  type: "1" | "2";
  preview: string;
}

/* ════════════════════════════════════════════════════════════════════════════ */
/*  MAIN COMPONENT                                                              */
/* ════════════════════════════════════════════════════════════════════════════ */

export default function UploadPage() {
  const dispatch = useAppDispatch();
  const { categories } = useAppSelector((s) => s.category);

  const [activeType, setActiveType] = useState<ContentType>("video");
  const [languages, setLanguages] = useState<Language[]>([]);
  const [podcasts, setPodcasts] = useState<PodcastItem[]>([]);
  const [podcastsLoading, setPodcastsLoading] = useState(false);
  const [fields, setFields] = useState<Record<string, string>>({});
  const channelId = Cookies.get("channel_id") ?? "";
  const [toggles, setToggles] = useState({
    isComment: true,
    isLike: true,
    isDownload: false,
    isRent: false,
  });
  const [mainFile, setMainFile] = useState<File | null>(null);
  const [portraitFile, setPortraitFile] = useState<File | null>(null);
  const [landscapeFile, setLandscapeFile] = useState<File | null>(null);
  const [feedMedia, setFeedMedia] = useState<FeedMedia[]>([]);
  const [errors, setErrors] = useState<Errors>({});
  const [uploadState, setUploadState] = useState<
    "idle" | "uploading" | "success" | "error"
  >("idle");
  const [uploadPct, setUploadPct] = useState(0);
  const [uploadLabel, setUploadLabel] = useState("");
  const [uploadError, setUploadError] = useState("");

  const typeCfg = getTypeCfg(activeType);

  useEffect(() => {
    dispatch(fetchCategories());
    uploadService
      .getLanguages()
      .then(setLanguages)
      .catch(() => {});
  }, [dispatch]);

  /* Fetch podcasts when episode tab selected and channelId available */
  useEffect(() => {
    if (activeType !== "episode") return;
    const cid = channelId;
    if (!cid) return;
    setPodcastsLoading(true);
    uploadService
      .getPodcasts(cid)
      .then(setPodcasts)
      .catch(() => {})
      .finally(() => setPodcastsLoading(false));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeType]);

  const setField = useCallback((k: string, v: string) => {
    setFields((prev) => ({ ...prev, [k]: v }));
    setErrors((prev) => {
      const e = { ...prev };
      delete e[k];
      return e;
    });
  }, []);

  const setToggle = (k: keyof typeof toggles) => (v: boolean) =>
    setToggles((prev) => ({ ...prev, [k]: v }));

  /* Auto-detect duration when a video or audio file is selected */
  useEffect(() => {
    if (!mainFile || !["video", "music"].includes(activeType)) return;

    const url = URL.createObjectURL(mainFile);
    const media = mainFile.type.startsWith("video/")
      ? document.createElement("video")
      : document.createElement("audio");

    media.preload = "metadata";
    media.src = url;

    const onLoaded = () => {
      if (media.duration && isFinite(media.duration)) {
        setField("contentDuration", String(Math.round(media.duration)));
      }
      URL.revokeObjectURL(url);
    };

    media.addEventListener("loadedmetadata", onLoaded);
    media.addEventListener("error", () => URL.revokeObjectURL(url));

    return () => {
      media.removeEventListener("loadedmetadata", onLoaded);
      URL.revokeObjectURL(url);
    };
  }, [mainFile, activeType, setField]);

  const resetForm = useCallback(() => {
    setFields({});
    setToggles({
      isComment: true,
      isLike: true,
      isDownload: false,
      isRent: false,
    });
    setMainFile(null);
    setPortraitFile(null);
    setLandscapeFile(null);
    setFeedMedia([]);
    setErrors({});
    setUploadState("idle");
    setUploadPct(0);
    setUploadLabel("");
    setUploadError("");
  }, []);

  const onProgress: UploadProgressCallback = (pct, label) => {
    setUploadPct(pct);
    setUploadLabel(label);
  };

  /* ── Validation ── */
  const validate = (): boolean => {
    const e: Errors = {};
    const f = fields;
    const type = activeType;

    if (type !== "episode" && type !== "feed" && !f.title)
      e.title = "Title is required";
    if (["video", "music", "radio", "podcast"].includes(type) && !f.categoryId)
      e.categoryId = "Required";
    if (["video", "music", "podcast"].includes(type) && !f.languageId)
      e.languageId = "Required";
    if (type === "episode") {
      if (!f.podcastsId) e.podcastsId = "Select a podcast";
      if (!f.name) e.name = "Episode name is required";
    }
    if (type === "feed") {
      if (!f.description && feedMedia.length === 0)
        e.description = "Add description or media";
    }
    if (type !== "feed" && type !== "podcast" && !mainFile)
      e.mainFile = "File is required";
    if (toggles.isRent && type === "video") {
      if (!f.rentPrice) e.rentPrice = "Required";
      if (!f.rentDay) e.rentDay = "Required";
    }

    setErrors(e);
    return Object.keys(e).length === 0;
  };

  /* ── Submit ── */
  const handleSubmit = async () => {
    if (!validate()) return;
    setUploadState("uploading");
    setUploadError("");

    try {
      const boolVal = (v: boolean) => (v ? "1" : "0");
      const f = fields;

      const cid = channelId;

      switch (activeType) {
        case "video":
          await uploadService.uploadVideo(
            {
              file: mainFile!,
              portraitImg: portraitFile ?? undefined,
              landscapeImg: landscapeFile ?? undefined,
              title: f.title,
              channelId: cid,
              categoryId: f.categoryId,
              languageId: f.languageId,
              description: f.description || "",
              isComment: boolVal(toggles.isComment),
              isDownload: boolVal(toggles.isDownload),
              isLike: boolVal(toggles.isLike),
              isRent: boolVal(toggles.isRent),
              rentPrice: f.rentPrice || "0",
              rentDay: f.rentDay || "0",
              contentDuration: f.contentDuration || "0",
            },
            onProgress,
          );
          break;

        case "music":
          await uploadService.uploadMusic(
            {
              file: mainFile!,
              portraitImg: portraitFile ?? undefined,
              landscapeImg: landscapeFile ?? undefined,
              title: f.title,
              channelId: cid,
              categoryId: f.categoryId,
              languageId: f.languageId,
              description: f.description || "",
              isComment: boolVal(toggles.isComment),
              isDownload: boolVal(toggles.isDownload),
              isLike: boolVal(toggles.isLike),
              contentDuration: f.contentDuration || "0",
            },
            onProgress,
          );
          break;

        case "reels":
          await uploadService.uploadReels(
            {
              file: mainFile!,
              portraitImg: portraitFile ?? undefined,
              channelId: cid,
              title: f.title,
              isComment: boolVal(toggles.isComment),
              isDownload: boolVal(toggles.isDownload),
              isLike: boolVal(toggles.isLike),
            },
            onProgress,
          );
          break;

        case "radio":
          await uploadService.uploadRadio(
            {
              file: mainFile!,
              portraitImg: portraitFile ?? undefined,
              landscapeImg: landscapeFile ?? undefined,
              title: f.title,
              channelId: cid,
              description: f.description || "",
              isComment: boolVal(toggles.isComment),
              isLike: boolVal(toggles.isLike),
            },
            onProgress,
          );
          break;

        case "episode":
          await uploadService.uploadEpisode(
            {
              file: mainFile!,
              portraitImg: portraitFile ?? undefined,
              landscapeImg: landscapeFile ?? undefined,
              podcastsId: f.podcastsId,
              name: f.name,
              description: f.description || "",
              isComment: boolVal(toggles.isComment),
              isDownload: boolVal(toggles.isDownload),
              isLike: boolVal(toggles.isLike),
            },
            onProgress,
          );
          break;

        case "feed": {
          const postContent: {
            content_type: string;
            image: string;
            video: string;
          }[] = [];
          for (let i = 0; i < feedMedia.length; i++) {
            const m = feedMedia[i];
            setUploadLabel(`Uploading media ${i + 1}/${feedMedia.length}…`);
            const result = await uploadService.uploadFeedContent(
              m.file,
              m.type,
            );
            postContent.push({
              content_type: m.type,
              image: result.image || "",
              video: result.video || "",
            });
            setUploadPct(Math.round(((i + 1) / feedMedia.length) * 80));
          }
          setUploadLabel("Publishing post…");
          setUploadPct(90);
          await uploadService.uploadFeed({
            channelId: cid,
            description: f.description || "",
            isLike: boolVal(toggles.isLike),
            isComment: boolVal(toggles.isComment),
            postContent,
          });
          setUploadPct(100);
          break;
        }

        case "podcast":
          await uploadService.createPodcast(
            {
              channelId: cid,
              categoryId: f.categoryId,
              languageId: f.languageId,
              title: f.title,
              description: f.description || "",
              portraitImg: portraitFile ?? undefined,
              landscapeImg: landscapeFile ?? undefined,
            },
            onProgress,
          );
          break;
      }

      setUploadState("success");
    } catch (err) {
      setUploadState("error");
      setUploadError(
        err instanceof Error ? err.message : "Upload failed. Please try again.",
      );
    }
  };

  /* ── Feed media helpers ── */
  const addFeedMedia = (e: ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files ?? []);
    files.forEach((file) => {
      const isVideo = file.type.startsWith("video/");
      setFeedMedia((prev) => [
        ...prev,
        { file, type: isVideo ? "2" : "1", preview: URL.createObjectURL(file) },
      ]);
    });
    e.target.value = "";
  };

  const removeFeedMedia = (i: number) =>
    setFeedMedia((prev) => prev.filter((_, idx) => idx !== i));

  /* ── Render ── */
  return (
    <div
      className="min-h-screen pb-28"
      style={{
        background: "var(--bg)",
        animation: "upload-page-in 0.4s ease both",
      }}
    >
      {/* Overlays */}
      {uploadState === "uploading" && (
        <ProgressOverlay
          pct={uploadPct}
          label={uploadLabel}
          color={typeCfg.color}
        />
      )}
      {uploadState === "success" && (
        <SuccessOverlay color={typeCfg.color} onDone={resetForm} />
      )}

      {/* Page header */}
      <div
        className="sticky top-0 z-10 flex items-center gap-3 px-5 py-4"
        style={{
          background: "var(--bg)",
          borderBottom: "1px solid var(--border-soft)",
        }}
      >
        <div
          className="w-8 h-8 rounded-xl flex items-center justify-center flex-shrink-0"
          style={{
            background: `${typeCfg.color}18`,
            border: `1px solid ${typeCfg.color}30`,
          }}
        >
          <Upload size={14} color={typeCfg.color} strokeWidth={2} />
        </div>
        <div>
          <h1 className="text-sm font-bold leading-none" style={{ color: "var(--text-primary)" }}>
            Upload Content
          </h1>
          <p className="text-[10px] mt-0.5" style={{ color: "#555" }}>
            Share your content with the world
          </p>
        </div>
      </div>

      <div className=" mx-auto px-4 pt-5">
        {/* ── Type selector ── */}
        <div
          className="flex gap-2 overflow-x-auto scrollbar-hide pb-1 mb-6"
          style={{ animation: "upload-row-in 0.4s ease both" }}
        >
          {TYPES.map((t, i) => {
            const Icon = t.icon;
            const active = activeType === t.id;
            return (
              <button
                key={t.id}
                type="button"
                className="flex items-center gap-2 px-4 py-2 rounded-xl flex-shrink-0 text-[12px] font-semibold transition-all duration-200 active:scale-95"
                style={{
                  background: active
                    ? `${t.color}18`
                    : "var(--btn-ghost)",
                  border: `1px solid ${active ? t.color + "50" : "var(--border-soft)"}`,
                  color: active ? t.color : "#777",
                  animation: `upload-row-in 0.35s ease both`,
                  animationDelay: `${i * 40}ms`,
                }}
                onClick={() => {
                  if (activeType === t.id) return;
                  resetForm();
                  setActiveType(t.id);
                }}
              >
                <Icon size={13} strokeWidth={2} />
                {t.label}
              </button>
            );
          })}
        </div>

        {/* ── Error banner ── */}
        {uploadState === "error" && (
          <div
            className="flex items-center gap-2 px-4 py-3 rounded-xl mb-4"
            style={{
              background: "rgba(244,63,94,0.08)",
              border: "1px solid rgba(244,63,94,0.2)",
            }}
          >
            <AlertCircle size={14} color="#f43f5e" />
            <p className="text-[12px]" style={{ color: "#f43f5e" }}>
              {uploadError}
            </p>
          </div>
        )}

        {/* ── Main form grid ── */}
        <div className="grid grid-cols-1 lg:grid-cols-[1fr_340px] gap-4">
          {/* Left: metadata */}
          <div
            className="flex flex-col gap-4"
            style={{
              animation: "upload-row-in 0.45s ease both",
              animationDelay: "0.05s",
            }}
          >
            {/* ── Video / Music / Radio / Reels fields ── */}
            {(activeType === "video" ||
              activeType === "music" ||
              activeType === "radio" ||
              activeType === "reels") && (
              <Card title="Content Details">
                <MetaFields
                  fields={fields}
                  setField={setField}
                  categories={categories}
                  languages={languages}
                  errors={errors}
                  color={typeCfg.color}
                  showCategory={activeType !== "reels"}
                  showLanguage={
                    activeType === "video" || activeType === "music"
                  }
                />
              </Card>
            )}

            {/* ── Episode fields ── */}
            {activeType === "episode" && (
              <Card title="Episode Details">
                <Field
                  label="Podcast Series"
                  required
                  error={errors.podcastsId}
                >
                  {podcastsLoading ? (
                    <div
                      className="h-9 rounded-lg flex items-center px-3 gap-2 animate-pulse"
                      style={{
                        background: "var(--btn-ghost)",
                        border: "1px solid var(--border)",
                      }}
                    >
                      <div
                        className="w-3 h-3 rounded-full"
                        style={{ background: "var(--border)" }}
                      />
                      <div
                        className="h-2 rounded-full flex-1"
                        style={{ background: "var(--border)" }}
                      />
                    </div>
                  ) : podcasts.length > 0 ? (
                    <div className="relative">
                      <select
                        className="w-full h-9 px-3 pr-8 rounded-lg text-[12px] outline-none appearance-none cursor-pointer"
                        style={{
                          background: "var(--btn-ghost)",
                          border: `1px solid ${errors.podcastsId ? "#f43f5e60" : "var(--border)"}`,
                          color: "var(--text-primary)",
                        }}
                        value={fields.podcastsId || ""}
                        onChange={(e) => setField("podcastsId", e.target.value)}
                      >
                        <option value="" style={{ background: "#16213e" }}>
                          Select podcast series…
                        </option>
                        {podcasts.map((p) => (
                          <option
                            key={p.id}
                            value={String(p.id)}
                            style={{ background: "#16213e" }}
                          >
                            {p.title}
                          </option>
                        ))}
                      </select>
                      <ChevronDown
                        size={13}
                        color="#888"
                        className="absolute right-2.5 top-1/2 -translate-y-1/2 pointer-events-none"
                      />
                    </div>
                  ) : (
                    <div
                      className="h-9 rounded-lg flex items-center px-3 gap-2"
                      style={{
                        background: "var(--border-soft)",
                        border: "1px solid var(--border-soft)",
                      }}
                    >
                      <span className="text-[11px]" style={{ color: "#555" }}>
                        {channelId
                          ? "No podcasts found for your channel"
                          : "Channel ID not found in session"}
                      </span>
                    </div>
                  )}
                </Field>
                <Field label="Episode Name" required error={errors.name}>
                  <Input
                    value={fields.name || ""}
                    onChange={(v) => setField("name", v)}
                    placeholder="Episode title…"
                    error={!!errors.name}
                  />
                </Field>
                <Field label="Description">
                  <Textarea
                    value={fields.description || ""}
                    onChange={(v) => setField("description", v)}
                    placeholder="Episode description…"
                  />
                </Field>
              </Card>
            )}

            {/* ── Podcast fields ── */}
            {activeType === "podcast" && (
              <Card title="Podcast Series Details">
                <Field label="Title" required error={errors.title}>
                  <Input
                    value={fields.title || ""}
                    onChange={(v) => setField("title", v)}
                    placeholder="Podcast series name…"
                    error={!!errors.title}
                  />
                </Field>
                <Field label="Category" required error={errors.categoryId}>
                  <Select
                    value={fields.categoryId || ""}
                    onChange={(v) => setField("categoryId", v)}
                    options={categories.map((c) => ({
                      id: c.id,
                      name: c.name,
                    }))}
                    placeholder="Select category"
                    error={!!errors.categoryId}
                  />
                </Field>
                <Field label="Language" required error={errors.languageId}>
                  <Select
                    value={fields.languageId || ""}
                    onChange={(v) => setField("languageId", v)}
                    options={languages.map((l) => ({ id: l.id, name: l.name }))}
                    placeholder="Select language"
                    error={!!errors.languageId}
                  />
                </Field>
                <Field label="Description">
                  <Textarea
                    value={fields.description || ""}
                    onChange={(v) => setField("description", v)}
                    placeholder="What is this podcast about?"
                    rows={4}
                  />
                </Field>
              </Card>
            )}

            {/* ── Feed fields ── */}
            {activeType === "feed" && (
              <Card title="Post Details">
                <Field label="Description" error={errors.description}>
                  <Textarea
                    value={fields.description || ""}
                    onChange={(v) => setField("description", v)}
                    placeholder="What's on your mind?"
                    rows={4}
                    error={!!errors.description}
                  />
                </Field>

                {/* Feed media */}
                <div>
                  <FieldLabel>Media</FieldLabel>
                  <div className="grid grid-cols-3 gap-2">
                    {feedMedia.map((m, i) => (
                      <div
                        key={i}
                        className="relative rounded-lg overflow-hidden"
                        style={{
                          aspectRatio: "1/1",
                          background: "var(--deep)",
                        }}
                      >
                        <Image
                          src={m.preview}
                          alt=""
                          fill
                          className="object-cover"
                        />
                        {m.type === "2" && (
                          <div
                            className="absolute top-1 left-1 text-[8px] font-bold px-1.5 py-0.5 rounded"
                            style={{
                              background: "rgba(0,0,0,0.7)",
                              color: "#fff",
                            }}
                          >
                            VIDEO
                          </div>
                        )}
                        <button
                          type="button"
                          className="absolute top-1 right-1 w-5 h-5 rounded-full flex items-center justify-center"
                          style={{ background: "rgba(0,0,0,0.7)" }}
                          onClick={() => removeFeedMedia(i)}
                        >
                          <X size={9} color="#fff" />
                        </button>
                      </div>
                    ))}
                    <label
                      className="flex flex-col items-center justify-center rounded-lg cursor-pointer transition-all"
                      style={{
                        aspectRatio: "1/1",
                        background: "var(--border-soft)",
                        border: "1.5px dashed var(--border)",
                      }}
                      onMouseEnter={(e) =>
                        ((
                          e.currentTarget as HTMLLabelElement
                        ).style.borderColor = typeCfg.color + "60")
                      }
                      onMouseLeave={(e) =>
                        ((
                          e.currentTarget as HTMLLabelElement
                        ).style.borderColor = "var(--border)")
                      }
                    >
                      <Plus size={18} color="#555" />
                      <span
                        className="text-[9px] mt-1"
                        style={{ color: "#555" }}
                      >
                        Add
                      </span>
                      <input
                        type="file"
                        className="hidden"
                        accept="image/*,video/*"
                        multiple
                        onChange={addFeedMedia}
                      />
                    </label>
                  </div>
                </div>
              </Card>
            )}

            {/* ── Settings ── */}
            <Card title="Settings">
              <div className="flex flex-col gap-3">
                <ToggleRow
                  label="Allow Comments"
                  value={toggles.isComment}
                  onChange={setToggle("isComment")}
                  color={typeCfg.color}
                />
                <ToggleRow
                  label="Allow Likes"
                  value={toggles.isLike}
                  onChange={setToggle("isLike")}
                  color={typeCfg.color}
                />
                {(activeType === "video" ||
                  activeType === "music" ||
                  activeType === "episode") && (
                  <ToggleRow
                    label="Allow Downloads"
                    value={toggles.isDownload}
                    onChange={setToggle("isDownload")}
                    color={typeCfg.color}
                  />
                )}
                {activeType === "video" && (
                  <>
                    <div
                      style={{
                        height: 1,
                        background: "var(--btn-ghost)",
                      }}
                    />
                    <ToggleRow
                      label="Enable Rent"
                      value={toggles.isRent}
                      onChange={setToggle("isRent")}
                      color={typeCfg.color}
                    />
                    {toggles.isRent && (
                      <div className="grid grid-cols-2 gap-3">
                        <Field label="Rent Price" error={errors.rentPrice}>
                          <Input
                            value={fields.rentPrice || ""}
                            onChange={(v) => setField("rentPrice", v)}
                            placeholder="0.00"
                            type="number"
                            error={!!errors.rentPrice}
                          />
                        </Field>
                        <Field label="Rent Days" error={errors.rentDay}>
                          <Input
                            value={fields.rentDay || ""}
                            onChange={(v) => setField("rentDay", v)}
                            placeholder="7"
                            type="number"
                            error={!!errors.rentDay}
                          />
                        </Field>
                      </div>
                    )}
                  </>
                )}
              </div>
            </Card>
          </div>

          {/* Podcast: thumbnails only (no main file) */}
          {activeType === "podcast" && (
            <div
              className="flex flex-col gap-4"
              style={{
                animation: "upload-row-in 0.45s ease both",
                animationDelay: "0.1s",
              }}
            >
              <Card title="Cover Images">
                <Field label="Portrait Cover" required>
                  <ImageDrop
                    file={portraitFile}
                    onFile={setPortraitFile}
                    label="Portrait (9:16)"
                    color={typeCfg.color}
                  />
                </Field>
                <Field label="Landscape Cover">
                  <ImageDrop
                    file={landscapeFile}
                    onFile={setLandscapeFile}
                    label="Landscape (16:9)"
                    color={typeCfg.color}
                  />
                </Field>
              </Card>
              <div
                className="rounded-xl px-4 py-3"
                style={{
                  background: "rgba(139,92,246,0.06)",
                  border: "1px solid rgba(139,92,246,0.15)",
                }}
              >
                <p
                  className="text-[11px] font-semibold mb-1"
                  style={{ color: "#8b5cf6" }}
                >
                  Creating a Podcast Series
                </p>
                <p
                  className="text-[10px] leading-relaxed"
                  style={{ color: "#666" }}
                >
                  This creates the podcast container. After publishing, upload
                  individual episodes using the{" "}
                  <strong style={{ color: "#aaa" }}>Episode</strong> tab and
                  select this podcast.
                </p>
              </div>
            </div>
          )}

          {/* Right: file uploads */}
          {activeType !== "feed" && activeType !== "podcast" && (
            <div
              className="flex flex-col gap-4"
              style={{
                animation: "upload-row-in 0.45s ease both",
                animationDelay: "0.1s",
              }}
            >
              {/* Main file */}
              <Card title="Content File">
                <Field
                  label={
                    activeType === "episode"
                      ? "Episode File"
                      : `${typeCfg.label} File`
                  }
                  required
                  error={errors.mainFile}
                >
                  <DropZone
                    file={mainFile}
                    onFile={(f) => {
                      setMainFile(f);
                      setErrors((e) => {
                        const ne = { ...e };
                        delete ne.mainFile;
                        return ne;
                      });
                    }}
                    accept={typeCfg.accept}
                    label={`Drop ${typeCfg.label.toLowerCase()} here`}
                    icon={typeCfg.icon}
                    color={typeCfg.color}
                    error={!!errors.mainFile}
                  />
                </Field>

                {(activeType === "video" || activeType === "music") && (
                  <Field
                    label={
                      fields.contentDuration
                        ? `Duration — ${fields.contentDuration}s`
                        : "Duration (seconds)"
                    }
                  >
                    <div className="relative">
                      <input
                        type="number"
                        className="w-full h-9 px-3 pr-8 rounded-lg text-[12px] outline-none transition-all"
                        style={{
                          background: fields.contentDuration
                            ? "rgba(16,185,129,0.06)"
                            : "var(--btn-ghost)",
                          border: fields.contentDuration
                            ? "1px solid rgba(16,185,129,0.3)"
                            : "1px solid var(--border)",
                          color: "var(--text-primary)",
                        }}
                        value={fields.contentDuration || ""}
                        onChange={(e) =>
                          setField("contentDuration", e.target.value)
                        }
                        placeholder="Auto-detected from file…"
                        onFocus={(e) => {
                          e.currentTarget.style.borderColor =
                            "rgba(var(--accent-rgb),0.5)";
                        }}
                        onBlur={(e) => {
                          e.currentTarget.style.borderColor =
                            fields.contentDuration
                              ? "rgba(16,185,129,0.3)"
                              : "var(--border)";
                        }}
                      />
                      {fields.contentDuration && (
                        <span
                          className="absolute right-2.5 top-1/2 -translate-y-1/2 text-[9px] font-bold"
                          style={{ color: "#10b981" }}
                        >
                          ✓
                        </span>
                      )}
                    </div>
                    {fields.contentDuration && (
                      <p
                        className="text-[10px] mt-1"
                        style={{ color: "#10b981" }}
                      >
                        Auto-detected ·{" "}
                        {Math.floor(Number(fields.contentDuration) / 60)}m{" "}
                        {Number(fields.contentDuration) % 60}s
                      </p>
                    )}
                  </Field>
                )}
              </Card>

              {/* Images */}
              <Card title="Thumbnails">
                <Field label="Portrait Image">
                  <ImageDrop
                    file={portraitFile}
                    onFile={setPortraitFile}
                    label="Portrait (9:16)"
                    color={typeCfg.color}
                  />
                </Field>
                {activeType !== "reels" && (
                  <Field label="Landscape Image">
                    <ImageDrop
                      file={landscapeFile}
                      onFile={setLandscapeFile}
                      label="Landscape (16:9)"
                      color={typeCfg.color}
                    />
                  </Field>
                )}
              </Card>
            </div>
          )}
        </div>

        {/* ── Submit ── */}
        <div
          className="mt-6 flex items-center justify-end gap-3"
          style={{
            animation: "upload-row-in 0.5s ease both",
            animationDelay: "0.15s",
          }}
        >
          <button
            type="button"
            className="h-10 px-5 rounded-xl text-[12px] font-semibold transition-all"
            style={{
              background: "var(--btn-ghost)",
              color: "var(--text-muted)",
              border: "1px solid var(--btn-ghost-hover)",
            }}
            onClick={resetForm}
          >
            Reset
          </button>
          <button
            type="button"
            className="h-10 px-7 rounded-xl text-[12px] font-bold text-[#ffffff] transition-all active:scale-95 flex items-center gap-2"
            style={{
              background: typeCfg.color,
              boxShadow: `0 4px 20px ${typeCfg.color}35`,
            }}
            onClick={handleSubmit}
            onMouseEnter={(e) => {
              (e.currentTarget as HTMLButtonElement).style.filter =
                "brightness(1.1)";
            }}
            onMouseLeave={(e) => {
              (e.currentTarget as HTMLButtonElement).style.filter = "none";
            }}
          >
            <Upload size={13} strokeWidth={2.5} />
            Publish {typeCfg.label}
          </button>
        </div>
      </div>
    </div>
  );
}
