"use client"

import { Loader2Icon } from "lucide-react"
import { toast } from "sonner"

import { useGetRestaurantInfoQuery, useUpdateProfileMutation } from "@/src/state/auth"
import { useUploadFileMutation, useDeleteFileMutation } from "@/src/state/upload"
import { ImageCard } from "./image-card"
import { ProfileForm } from "./profile-form"
import { useState } from "react"

type ImageField = "thumbnailUrl" | "logoUrl" | "coverImageUrl"

export default function ProfileComponent() {
  const { data, isLoading } = useGetRestaurantInfoQuery()
  const profile = data?.data

  const [updateProfile] = useUpdateProfileMutation()
  const [uploadFile] = useUploadFileMutation()
  const [deleteFile] = useDeleteFileMutation()

  const [uploadingField, setUploadingField] = useState<ImageField | null>(null)

  const handleImageUpload = async (field: ImageField, file: File) => {
    setUploadingField(field)
    try {
      const formData = new FormData()
      formData.append("file", file)
      formData.append("fileType", "image")
      const res = await uploadFile(formData).unwrap()
      await updateProfile({ [field]: res.data.url }).unwrap()
      toast.success("Image mise à jour")
    } catch {
      toast.error("Erreur lors de l'envoi de l'image")
    } finally {
      setUploadingField(null)
    }
  }

  const handleImageDelete = async (field: ImageField, url: string) => {
    setUploadingField(field)
    try {
      await deleteFile({ fileUrl: url }).unwrap()
      await updateProfile({ [field]: "" }).unwrap()
      toast.success("Image supprimée")
    } catch {
      toast.error("Erreur lors de la suppression de l'image")
    } finally {
      setUploadingField(null)
    }
  }

  if (isLoading)
    return (
      <div className="min-h-[80.8svh] w-full flex items-center justify-center">
        <Loader2Icon className="animate-spin text-muted-foreground" />
      </div>
    )

  if (!profile) return null

  return (
    <div className="px-4 py-8 space-y-8">
      <div>
        <h1 className="text-xl font-semibold">Profil du restaurant</h1>
        <p className="text-sm text-muted-foreground mt-0.5">
          Gérez les informations et les médias de votre restaurant
        </p>
      </div>

      <section className="space-y-4 rounded-xl border bg-white p-5">
        <h2 className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">
          Images
        </h2>

        <ImageCard
          label="Image de couverture"
          hint="Affiché en haut de votre page restaurant"
          currentUrl={profile.coverImageUrl}
          aspectRatio="cover"
          isUploading={uploadingField === "coverImageUrl"}
          onUpload={(file) => handleImageUpload("coverImageUrl", file)}
          onDelete={() =>
            profile.coverImageUrl
              ? handleImageDelete("coverImageUrl", profile.coverImageUrl)
              : Promise.resolve()
          }
        />

        <div className="flex gap-4">
          <ImageCard
            label="Logo"
            hint="Format carré (1:1) recommandé"
            currentUrl={profile.logoUrl}
            aspectRatio="square"
            isUploading={uploadingField === "logoUrl"}
            onUpload={(file) => handleImageUpload("logoUrl", file)}
            onDelete={() =>
              profile.logoUrl
                ? handleImageDelete("logoUrl", profile.logoUrl)
                : Promise.resolve()
            }
          />
          <ImageCard
            label="Miniature"
            hint="Aperçu dans les listes"
            currentUrl={profile.thumbnailUrl}
            aspectRatio="square"
            isUploading={uploadingField === "thumbnailUrl"}
            onUpload={(file) => handleImageUpload("thumbnailUrl", file)}
            onDelete={() =>
              profile.thumbnailUrl
                ? handleImageDelete("thumbnailUrl", profile.thumbnailUrl)
                : Promise.resolve()
            }
          />
        </div>
      </section>

      <ProfileForm profile={profile} />
    </div>
  )
}
