"use client";

import { useActionState, useEffect, useState } from "react";
import { toast } from "sonner";

import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Drawer,
  DrawerContent,
  DrawerHeader,
  DrawerTitle,
} from "@/components/ui/drawer";
import { FormWizard } from "@/components/ui/responsive-sheet";
import { createPropertyAction, updatePropertyAction } from "@/lib/appwrite/property-actions";
import { PropertyImageUploader } from "./property-image-uploader";
import { PropertyMapPicker } from "@/components/map/property-map-picker";
import { parseImageIds } from "@/lib/appwrite/storage-utils";
import { useIsMobile } from "@/hooks/use-mobile";
import type { Property } from "@/lib/appwrite/schema";

type ActionState = { ok: boolean; error?: string; fieldErrors?: Record<string, string[]> };
const INITIAL: ActionState = { ok: false };

interface PropertyFormSheetProps {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  property?: Property | null;
  onSuccess?: () => void;
  maxImages?: number;
  isOwner?: boolean;
}

export function PropertyFormSheet({ open, onOpenChange, property, onSuccess, maxImages, isOwner }: PropertyFormSheetProps) {
  const isMobile = useIsMobile();
  const action = property ? updatePropertyAction.bind(null, property.$id) : createPropertyAction;

  const [state, formAction, isPending] = useActionState(action, INITIAL);
  const [mapLat, setMapLat] = useState<number | null>(property?.mapLat ?? null);
  const [mapLng, setMapLng] = useState<number | null>(property?.mapLng ?? null);

  useEffect(() => {
    if (state.ok) {
      toast.success(property ? "İlan güncellendi." : "İlan oluşturuldu.");
      onSuccess?.();
      onOpenChange(false);
    } else if (state.error) {
      toast.error(state.error);
    }
  }, [state]);

  useEffect(() => {
    if (open) {
      setMapLat(property?.mapLat ?? null);
      setMapLng(property?.mapLng ?? null);
    }
  }, [open, property]);

  const fe = state.fieldErrors ?? {};

  const initialSearchQuery = [property?.neighborhood, property?.district, property?.city]
    .filter(Boolean).join(", ");

  const steps = [
    {
      label: "İlan",
      content: (
        <>
          <input type="hidden" name="mapLat" value={mapLat ?? ""} />
          <input type="hidden" name="mapLng" value={mapLng ?? ""} />
          <div className="grid gap-1.5">
            <Label htmlFor="title">Başlık *</Label>
            <Input id="title" name="title" defaultValue={property?.title} placeholder="3+1 Daire, Kadıköy" />
            {fe.title && <p className="text-destructive text-xs">{fe.title[0]}</p>}
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div className="grid gap-1.5">
              <Label>Emlak tipi *</Label>
              <select name="propertyType" defaultValue={property?.propertyType ?? "daire"}
                className="border-input bg-background h-9 rounded-md border px-3 text-sm">
                <option value="daire">Daire</option>
                <option value="villa">Villa</option>
                <option value="arsa">Arsa</option>
                <option value="dukkan">Dükkan</option>
                <option value="ofis">Ofis</option>
                <option value="depo">Depo</option>
              </select>
            </div>
            <div className="grid gap-1.5">
              <Label>İlan türü *</Label>
              <select name="listingType" defaultValue={property?.listingType ?? "satilik"}
                className="border-input bg-background h-9 rounded-md border px-3 text-sm">
                <option value="satilik">Satılık</option>
                <option value="kiralik">Kiralık</option>
              </select>
            </div>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div className="grid gap-1.5">
              <Label htmlFor="price">Fiyat *</Label>
              <Input id="price" name="price" type="number" min="0" defaultValue={property?.price} placeholder="0" />
              {fe.price && <p className="text-destructive text-xs">{fe.price[0]}</p>}
            </div>
            <div className="grid gap-1.5">
              <Label>Durum</Label>
              <select name="status" defaultValue={property?.status ?? "aktif"}
                className="border-input bg-background h-9 rounded-md border px-3 text-sm">
                <option value="aktif">Aktif</option>
                <option value="rezerve">Rezerve</option>
                <option value="pasif">Pasif</option>
                <option value="satildi">Satıldı</option>
                <option value="kiralandit">Kiralandı</option>
              </select>
            </div>
          </div>
        </>
      ),
    },
    {
      label: "Konum",
      content: (
        <>
          <div className="grid grid-cols-3 gap-3">
            <div className="grid gap-1.5">
              <Label htmlFor="city">Şehir *</Label>
              <Input id="city" name="city" defaultValue={property?.city} placeholder="İstanbul" />
              {fe.city && <p className="text-destructive text-xs">{fe.city[0]}</p>}
            </div>
            <div className="grid gap-1.5">
              <Label htmlFor="district">İlçe</Label>
              <Input id="district" name="district" defaultValue={property?.district ?? ""} placeholder="Kadıköy" />
            </div>
            <div className="grid gap-1.5">
              <Label htmlFor="neighborhood">Mahalle</Label>
              <Input id="neighborhood" name="neighborhood" defaultValue={property?.neighborhood ?? ""} placeholder="Moda" />
            </div>
          </div>
          <div className="grid gap-1.5">
            <Label htmlFor="address">Adres</Label>
            <Input id="address" name="address" defaultValue={property?.address ?? ""} placeholder="Sokak, kapı no..." />
          </div>
          {open && (
            <PropertyMapPicker
              initialLat={mapLat}
              initialLng={mapLng}
              initialSearchQuery={initialSearchQuery}
              onLocationChange={(lat, lng) => { setMapLat(lat); setMapLng(lng); }}
              onClear={() => { setMapLat(null); setMapLng(null); }}
            />
          )}
        </>
      ),
    },
    {
      label: "Özellikler",
      content: (
        <div className="grid grid-cols-2 gap-3">
          <div className="grid gap-1.5">
            <Label htmlFor="roomCount">Oda sayısı</Label>
            <select name="roomCount" defaultValue={property?.roomCount ?? ""}
              className="border-input bg-background h-9 rounded-md border px-3 text-sm">
              <option value="">—</option>
              <option value="Stüdyo">Stüdyo</option>
              <option value="1+0">1+0</option>
              <option value="1+1">1+1</option>
              <option value="2+1">2+1</option>
              <option value="3+1">3+1</option>
              <option value="4+1">4+1</option>
              <option value="4+2">4+2</option>
              <option value="5+1">5+1</option>
              <option value="5+2">5+2</option>
              <option value="6+">6+</option>
            </select>
          </div>
          <div className="grid gap-1.5">
            <Label htmlFor="netM2">Net m²</Label>
            <Input id="netM2" name="netM2" type="number" min="0" defaultValue={property?.netM2 ?? ""} placeholder="90" />
          </div>
          <div className="grid gap-1.5">
            <Label htmlFor="floor">Kat</Label>
            <Input id="floor" name="floor" type="number" defaultValue={property?.floor ?? ""} />
          </div>
          <div className="grid gap-1.5">
            <Label htmlFor="totalFloors">Toplam kat</Label>
            <Input id="totalFloors" name="totalFloors" type="number" defaultValue={property?.totalFloors ?? ""} />
          </div>
          <div className="grid gap-1.5 col-span-2">
            <Label htmlFor="buildingAge">Bina yaşı</Label>
            <Input id="buildingAge" name="buildingAge" type="number" min="0" defaultValue={property?.buildingAge ?? ""} />
          </div>
        </div>
      ),
    },
    {
      label: "Medya",
      content: (
        <>
          <div className="grid gap-1.5">
            <Label htmlFor="description">Açıklama</Label>
            <Textarea id="description" name="description" rows={3}
              defaultValue={property?.description ?? ""} placeholder="İlan detayları..." />
          </div>
          <div className="grid gap-1.5">
            <Label>Fotoğraflar</Label>
            <PropertyImageUploader name="imageIds" initialImageIds={parseImageIds(property?.imageIds)} maxImages={maxImages} isOwner={isOwner} />
          </div>
        </>
      ),
    },
  ];

  const title = property ? "İlanı Düzenle" : "Yeni İlan";

  const formContent = (
    <form
      action={formAction}
      onKeyDown={(e) => {
        if (e.key === "Enter" && (e.target as HTMLElement).tagName !== "TEXTAREA") {
          e.preventDefault();
        }
      }}
    >
      <FormWizard steps={steps} isPending={isPending} submitLabel={property ? "Güncelle" : "Oluştur"} />
    </form>
  );

  if (isMobile) {
    return (
      <Drawer open={open} onOpenChange={onOpenChange} direction="bottom">
        <DrawerContent className="max-h-[92dvh]">
          <DrawerHeader className="border-b pb-3">
            <DrawerTitle>{title}</DrawerTitle>
          </DrawerHeader>
          <div className="flex-1 overflow-y-auto px-4 py-4">{formContent}</div>
        </DrawerContent>
      </Drawer>
    );
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
        </DialogHeader>
        <div>{formContent}</div>
      </DialogContent>
    </Dialog>
  );
}
