"use client";

import { useState } from "react";
import { toast } from "sonner";
import { ImageSquare } from "@/lib/icons";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Drawer,
  DrawerContent,
  DrawerHeader,
  DrawerTitle,
} from "@/components/ui/drawer";
import { Button } from "@/components/ui/button";
import { PropertyImageUploader } from "./property-image-uploader";
import {
  updatePropertyImagesAction,
} from "@/lib/appwrite/property-actions";
import {
  deletePropertyImageAndSyncAction,
} from "@/lib/appwrite/storage-actions";
import { useIsMobile } from "@/hooks/use-mobile";

interface PropertyImageSheetProps {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  propertyId: string;
  initialImageIds: string[];
  onSuccess?: () => void;
}

export function PropertyImageSheet({
  open,
  onOpenChange,
  propertyId,
  initialImageIds,
  onSuccess,
}: PropertyImageSheetProps) {
  const isMobile = useIsMobile();
  const [imageIds, setImageIds] = useState<string[]>(initialImageIds);
  const [saving, setSaving] = useState(false);

  // Silme: storage + DB'yi tek seferde güncelle, "Kaydet" gerektirmez
  async function handleDeleteImage(fileId: string): Promise<boolean> {
    const remaining = imageIds.filter((id) => id !== fileId);
    const result = await deletePropertyImageAndSyncAction(propertyId, fileId, remaining);
    if (result.ok) {
      setImageIds(remaining);
      onSuccess?.();
      return true;
    }
    toast.error(result.error ?? "Fotoğraf silinemedi.");
    return false;
  }

  // Yeni yüklenen fotoğrafları kaydet
  async function handleSave() {
    setSaving(true);
    const result = await updatePropertyImagesAction(propertyId, imageIds);
    setSaving(false);
    if (result.ok) {
      toast.success("Fotoğraflar kaydedildi.");
      onSuccess?.();
      onOpenChange(false);
    } else {
      toast.error(result.error ?? "Kaydedilemedi.");
    }
  }

  const content = (
    <div className="space-y-4">
      <PropertyImageUploader
        name="imageIds"
        initialImageIds={imageIds}
        onChangeIds={setImageIds}
        onDeleteImage={handleDeleteImage}
      />
      <div className="flex justify-end gap-2 pt-2 border-t">
        <Button variant="outline" type="button" onClick={() => onOpenChange(false)}>
          Kapat
        </Button>
        <Button type="button" onClick={handleSave} disabled={saving}>
          {saving ? "Kaydediliyor…" : "Kaydet"}
        </Button>
      </div>
    </div>
  );

  if (isMobile) {
    return (
      <Drawer open={open} onOpenChange={onOpenChange} direction="bottom">
        <DrawerContent className="max-h-[92dvh]">
          <DrawerHeader className="border-b pb-3">
            <DrawerTitle className="flex items-center gap-2">
              <ImageSquare className="size-4" />
              Fotoğraf Yönetimi
            </DrawerTitle>
          </DrawerHeader>
          <div className="flex-1 overflow-y-auto px-4 py-4">{content}</div>
        </DrawerContent>
      </Drawer>
    );
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <ImageSquare className="size-4" />
            Fotoğraf Yönetimi
          </DialogTitle>
        </DialogHeader>
        {content}
      </DialogContent>
    </Dialog>
  );
}
