"use client";

import { useState, type Dispatch, type SetStateAction } from "react";
import {
  getTenantLogoUrl,
  uploadTenantLogo,
  deleteTenantLogo,
  uploadMyTenantLogo,
  deleteMyTenantLogo,
  type Tenant,
} from "@/lib/api";

interface OwnLogoController {
  setOwnLogoPreviewUrl: Dispatch<SetStateAction<string | null>>;
  setOwnLogoUploading: Dispatch<SetStateAction<boolean>>;
  setOwnLogoError: Dispatch<SetStateAction<string>>;
}

export function useTenantLogos(
  setTenants: Dispatch<SetStateAction<Tenant[]>>,
  own: OwnLogoController,
) {
  // Logo dialog (superadmin: any tenant)
  const [logoDialogTenant, setLogoDialogTenant] = useState<Tenant | null>(null);
  const [logoPreviewUrl, setLogoPreviewUrl] = useState<string | null>(null);
  const [logoUploading, setLogoUploading] = useState(false);
  const [logoError, setLogoError] = useState("");

  async function openLogoDialog(t: Tenant) {
    setLogoDialogTenant(t);
    setLogoError("");
    setLogoPreviewUrl(null);
    if (t.has_logo) {
      try {
        const res = await fetch(getTenantLogoUrl(t.id), { credentials: "include" });
        if (res.ok) {
          const blob = await res.blob();
          setLogoPreviewUrl(URL.createObjectURL(blob));
        }
      } catch {
        // preview not critical
      }
    }
  }

  async function handleLogoUpload(file: File) {
    if (!logoDialogTenant) return;
    setLogoUploading(true);
    setLogoError("");
    try {
      await uploadTenantLogo(logoDialogTenant.id, file);
      const res = await fetch(getTenantLogoUrl(logoDialogTenant.id), { credentials: "include" });
      if (res.ok) {
        const blob = await res.blob();
        setLogoPreviewUrl(URL.createObjectURL(blob));
      }
      setTenants((prev) => prev.map((t) => t.id === logoDialogTenant.id ? { ...t, has_logo: true } : t));
    } catch (err: unknown) {
      setLogoError(err instanceof Error ? err.message : "Upload fehlgeschlagen.");
    } finally {
      setLogoUploading(false);
    }
  }

  async function handleLogoDelete() {
    if (!logoDialogTenant) return;
    setLogoUploading(true);
    setLogoError("");
    try {
      await deleteTenantLogo(logoDialogTenant.id);
      setLogoPreviewUrl(null);
      setTenants((prev) => prev.map((t) => t.id === logoDialogTenant.id ? { ...t, has_logo: false } : t));
    } catch (err: unknown) {
      setLogoError(err instanceof Error ? err.message : "Löschen fehlgeschlagen.");
    } finally {
      setLogoUploading(false);
    }
  }

  // Logo handlers (domain_admin: own tenant)
  async function handleOwnLogoUpload(file: File) {
    own.setOwnLogoUploading(true);
    own.setOwnLogoError("");
    try {
      await uploadMyTenantLogo(file);
      const res = await fetch(`/api/tenant/logo`, { credentials: "include" });
      if (res.ok) {
        const blob = await res.blob();
        own.setOwnLogoPreviewUrl(URL.createObjectURL(blob));
      }
    } catch (err: unknown) {
      own.setOwnLogoError(err instanceof Error ? err.message : "Upload fehlgeschlagen.");
    } finally {
      own.setOwnLogoUploading(false);
    }
  }

  async function handleOwnLogoDelete() {
    own.setOwnLogoUploading(true);
    own.setOwnLogoError("");
    try {
      await deleteMyTenantLogo();
      own.setOwnLogoPreviewUrl(null);
    } catch (err: unknown) {
      own.setOwnLogoError(err instanceof Error ? err.message : "Löschen fehlgeschlagen.");
    } finally {
      own.setOwnLogoUploading(false);
    }
  }

  return {
    logoDialogTenant,
    setLogoDialogTenant,
    logoPreviewUrl,
    setLogoPreviewUrl,
    logoUploading,
    logoError,
    openLogoDialog,
    handleLogoUpload,
    handleLogoDelete,
    handleOwnLogoUpload,
    handleOwnLogoDelete,
  };
}
