"use client";

import { useActionState, useRef } from "react";
import { uploadGalleryPhoto, setStatusPhoto } from "@/lib/photo/actions";
import type { ActionState } from "@/lib/auth/actions";
import { Button } from "@/components/ui/Button";

function PhotoUploadForm({
  action,
  label,
  pendingLabel,
  showYoutubeInput,
  showTagInput,
}: {
  action: (prevState: ActionState, formData: FormData) => Promise<ActionState>;
  label: string;
  pendingLabel: string;
  showYoutubeInput?: boolean;
  showTagInput?: boolean;
}) {
  const [state, formAction, pending] = useActionState<ActionState, FormData>(action, undefined);
  const formRef = useRef<HTMLFormElement>(null);

  return (
    <form
      ref={formRef}
      action={async (formData) => {
        await formAction(formData);
        formRef.current?.reset();
      }}
      className="flex flex-wrap items-center gap-3"
    >
      <input
        type="file"
        name="file"
        accept="image/jpeg,image/png,image/webp"
        required
        className="text-[13px] text-text-muted file:mr-3 file:rounded-full file:border-0 file:bg-accent/10 file:px-4 file:py-2 file:text-[13px] file:font-semibold file:text-accent"
      />
      {showYoutubeInput && (
        <input
          type="url"
          name="youtubeUrl"
          placeholder="YouTube bağlantısı ekle (opsiyonel)"
          className="min-w-[220px] flex-1 rounded-lg border border-border px-3 py-2 text-[13px] outline-none focus:border-accent"
        />
      )}
      {showTagInput && (
        <input
          type="text"
          name="taggedUsername"
          placeholder="Bir üyeyi etiketle @kullaniciadi (opsiyonel)"
          className="min-w-[220px] flex-1 rounded-lg border border-border px-3 py-2 text-[13px] outline-none focus:border-accent"
        />
      )}
      <Button type="submit" variant="outline" disabled={pending} className="px-5 py-2 text-[13px]">
        {pending ? pendingLabel : label}
      </Button>
      {state?.message && <p className="w-full text-[12.5px] text-text-muted">{state.message}</p>}
    </form>
  );
}

export function GalleryUploadForm() {
  return <PhotoUploadForm action={uploadGalleryPhoto} label="Galeriye Ekle" pendingLabel="Yükleniyor..." />;
}

export function StatusUploadForm() {
  return (
    <PhotoUploadForm
      action={setStatusPhoto}
      label="Durum Paylaş"
      pendingLabel="Paylaşılıyor..."
      showYoutubeInput
      showTagInput
    />
  );
}
