"use client";

import { useEffect, useMemo, useState } from "react";
import { Button } from "@/components/ui/Button";
import { Field } from "@/components/ui/Field";
import { SubjectAvatar } from "@/components/ui/SubjectAvatar";
import { ApiError, apiDelete, apiPostFormData } from "@/lib/api";

const MAX_BYTES = 2 * 1024 * 1024;

export function SubjectImageField({
  subjectId,
  subjectName,
  imageUrl,
  onUpdated,
  pendingFile,
  onPendingFileChange,
}: {
  subjectId?: number | null;
  subjectName: string;
  imageUrl?: string | null;
  onUpdated?: (imageUrl: string | null) => void;
  pendingFile?: File | null;
  onPendingFileChange?: (file: File | null) => void;
}) {
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const pendingPreview = useMemo(
    () => (pendingFile ? URL.createObjectURL(pendingFile) : null),
    [pendingFile],
  );

  useEffect(() => {
    return () => {
      if (pendingPreview) URL.revokeObjectURL(pendingPreview);
    };
  }, [pendingPreview]);

  const previewUrl = pendingPreview ?? imageUrl ?? null;
  const canRemove = Boolean(pendingFile || (subjectId && imageUrl));

  const applyFile = async (file: File) => {
    if (file.size > MAX_BYTES) {
      setError("حجم تصویر نباید بیشتر از ۲ مگابایت باشد.");
      return;
    }

    setError(null);

    if (!subjectId) {
      onPendingFileChange?.(file);
      return;
    }

    setUploading(true);
    try {
      const form = new FormData();
      form.append("image", file);
      const updated = await apiPostFormData<{ image_url?: string | null }>(
        `/subjects/${subjectId}/image`,
        form,
      );
      onUpdated?.(updated.image_url ?? null);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در آپلود تصویر");
    } finally {
      setUploading(false);
    }
  };

  const remove = async () => {
    setError(null);

    if (!subjectId) {
      onPendingFileChange?.(null);
      return;
    }

    setUploading(true);
    try {
      await apiDelete(`/subjects/${subjectId}/image`);
      onUpdated?.(null);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در حذف تصویر");
    } finally {
      setUploading(false);
    }
  };

  return (
    <Field label="تصویر درس">
      <div className="flex flex-wrap items-center gap-3">
        <SubjectAvatar name={subjectName} imageUrl={previewUrl} size="lg" />
        <div className="space-y-2">
          <input
            type="file"
            accept="image/*"
            disabled={uploading}
            onChange={(e) => {
              const file = e.target.files?.[0];
              if (file) void applyFile(file);
              e.target.value = "";
            }}
            className="block max-w-xs text-sm text-slate-600 file:mr-2 file:rounded-lg file:border-0 file:bg-teal-50 file:px-3 file:py-1.5 file:text-sm file:font-medium file:text-teal-800"
          />
          {canRemove ? (
            <Button
              variant="secondary"
              className="h-8 px-3 text-xs"
              onClick={() => void remove()}
              loading={uploading}
            >
              حذف تصویر
            </Button>
          ) : null}
          <p className="text-xs text-slate-500">PNG یا JPG · حداکثر ۲ مگابایت</p>
          {error ? <p className="text-xs text-red-600">{error}</p> : null}
        </div>
      </div>
    </Field>
  );
}
