import { useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { FiArrowLeft, FiImage } from "react-icons/fi";
import { useForm } from "react-hook-form";
import { useApiSocialHubsCreate } from "@/api/generated/private/hubs/hubs";
import Button from "@/components/ui/Button";
import FormErrorBanner from "@/components/ui/FormErrorBanner";

interface FormValues {
  name: string;
  description: string;
  is_public: boolean;
}

export default function HubCreatePage() {
  const { t } = useTranslation("social");
  const navigate = useNavigate();
  const [icon, setIcon] = useState<File | null>(null);
  const [banner, setBanner] = useState<File | null>(null);
  const [iconPreview, setIconPreview] = useState<string | null>(null);
  const [bannerPreview, setBannerPreview] = useState<string | null>(null);
  const [serverError, setServerError] = useState<string | null>(null);
  const iconRef = useRef<HTMLInputElement>(null);
  const bannerRef = useRef<HTMLInputElement>(null);

  const { register, handleSubmit, formState: { errors } } = useForm<FormValues>({
    defaultValues: { name: "", description: "", is_public: true },
  });

  const mutation = useApiSocialHubsCreate({
    mutation: {
      onSuccess: (hub) => navigate(`/social/h/${hub.name}`),
      onError: () => setServerError(t("hubCreate.error")),
    },
  });

  function pickFile(setter: (f: File) => void, previewSetter: (s: string) => void) {
    return (e: React.ChangeEvent<HTMLInputElement>) => {
      const f = e.target.files?.[0];
      if (!f) return;
      setter(f);
      previewSetter(URL.createObjectURL(f));
    };
  }

  async function onSubmit(values: FormValues) {
    setServerError(null);
    const form = new FormData();
    form.append("name", values.name);
    form.append("description", values.description);
    form.append("is_public", String(values.is_public));
    if (icon) form.append("icon", icon);
    if (banner) form.append("banner", banner);
    mutation.mutate({ data: form as unknown as Parameters<typeof mutation.mutate>[0]["data"] });
  }

  return (
    <div className="mx-auto max-w-xl">
      <header className="sticky top-0 z-10 flex items-center gap-3 border-b border-brand-lines/10 bg-brand-bg/80 px-4 py-3 backdrop-blur">
        <button
          type="button"
          onClick={() => navigate(-1)}
          className="rounded-full p-1 text-brand-text hover:bg-brand-lines/10"
        >
          <FiArrowLeft size={20} />
        </button>
        <h1 className="text-lg font-bold text-brand-text">{t("hubCreate.title")}</h1>
      </header>

      <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-5 px-4 py-6">
        {serverError && <FormErrorBanner message={serverError} />}

        {/* Banner picker */}
        <div>
          <label className="mb-1 block text-xs font-medium text-brand-text/60">{t("hubCreate.bannerLabel")}</label>
          <button
            type="button"
            onClick={() => bannerRef.current?.click()}
            className="relative flex h-28 w-full items-center justify-center overflow-hidden rounded-xl border-2 border-dashed border-brand-lines/30 bg-brand-bgLight/30 text-brand-text/40 transition-colors hover:border-brand-accent/40 hover:text-brand-accent/60"
          >
            {bannerPreview ? (
              <img src={bannerPreview} alt="" className="h-full w-full object-cover" />
            ) : (
              <span className="flex flex-col items-center gap-1 text-xs">
                <FiImage size={22} />
                {t("hubCreate.addBanner")}
              </span>
            )}
          </button>
          <input ref={bannerRef} type="file" accept="image/*" className="hidden" onChange={pickFile(setBanner, setBannerPreview)} />
        </div>

        {/* Icon picker */}
        <div>
          <label className="mb-1 block text-xs font-medium text-brand-text/60">{t("hubCreate.iconLabel")}</label>
          <button
            type="button"
            onClick={() => iconRef.current?.click()}
            className="relative flex h-20 w-20 items-center justify-center overflow-hidden rounded-full border-2 border-dashed border-brand-lines/30 bg-brand-bgLight/30 text-brand-text/40 transition-colors hover:border-brand-accent/40 hover:text-brand-accent/60"
          >
            {iconPreview ? (
              <img src={iconPreview} alt="" className="h-full w-full object-cover rounded-full" />
            ) : (
              <FiImage size={20} />
            )}
          </button>
          <input ref={iconRef} type="file" accept="image/*" className="hidden" onChange={pickFile(setIcon, setIconPreview)} />
        </div>

        {/* Name */}
        <div>
          <label className="mb-1 block text-xs font-medium text-brand-text/60">
            {t("hubCreate.nameLabel")} <span className="text-red-400">*</span>
          </label>
          <input
            {...register("name", { required: t("hubCreate.nameRequired") })}
            placeholder={t("hubCreate.namePlaceholder")}
            className="w-full rounded-xl border border-brand-lines/25 bg-brand-bgLight/40 px-3 py-2 text-sm text-brand-text placeholder:text-brand-text/40 focus:border-brand-accent focus:outline-none"
          />
          {errors.name && <p className="mt-1 text-xs text-red-400">{errors.name.message}</p>}
        </div>

        {/* Description */}
        <div>
          <label className="mb-1 block text-xs font-medium text-brand-text/60">{t("hubCreate.descriptionLabel")}</label>
          <textarea
            {...register("description")}
            rows={3}
            placeholder={t("hubCreate.descriptionPlaceholder")}
            className="w-full resize-none rounded-xl border border-brand-lines/25 bg-brand-bgLight/40 px-3 py-2 text-sm text-brand-text placeholder:text-brand-text/40 focus:border-brand-accent focus:outline-none"
          />
        </div>

        {/* Visibility */}
        <label className="flex cursor-pointer items-center justify-between gap-3 rounded-xl border border-brand-lines/15 bg-brand-bgLight/30 px-4 py-3">
          <div>
            <p className="text-sm font-medium text-brand-text">{t("hubCreate.visibilityLabel")}</p>
            <p className="text-xs text-brand-text/50">{t("hubCreate.visibilityDesc")}</p>
          </div>
          <input type="checkbox" {...register("is_public")} className="h-4 w-4 accent-brand-accent" />
        </label>

        <Button type="submit" variant="primary" fullWidth loading={mutation.isPending}>
          {t("hubCreate.submit")}
        </Button>
      </form>
    </div>
  );
}
