import { useMemo, useRef } from "react"
import type { DealDraft } from "../../models/DealDraft"

type Props = {
  data: DealDraft
  onChange: (data: DealDraft) => void
  onBack: () => void
  onSubmit: () => void
}

const MAX_IMAGES = 5

export default function DealDetailsStep({ data, onChange, onBack, onSubmit }: Props) {
const hasDetectedCompany = data?.seller?.id !== -1
  const fileInputRef = useRef<HTMLInputElement | null>(null)

  const images = data.images ?? []
  const remaining = MAX_IMAGES - images.length

  const previews = useMemo(() => {
    return images.map((f) => ({ file: f, url: URL.createObjectURL(f) }))
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [images])

  function openFileDialog() {
    fileInputRef.current?.click()
  }

  function onPickFiles(fileList: FileList | null) {
    if (!fileList) return
    const picked = Array.from(fileList).filter((f) => f.type.startsWith("image/"))
    if (picked.length === 0) return

    const next = [...images, ...picked].slice(0, MAX_IMAGES)
    onChange({ ...data, images: next })

    if (fileInputRef.current) fileInputRef.current.value = ""
  }

  function removeImage(index: number) {
    const next = images.filter((_, i) => i !== index)
    onChange({ ...data, images: next })
  }

  function moveImage(from: number, to: number) {
    if (to < 0 || to >= images.length) return
    const next = [...images]
    const [item] = next.splice(from, 1)
    next.splice(to, 0, item)
    onChange({ ...data, images: next })
  }

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault()
        onSubmit()
      }}
      className="max-w-5xl mx-auto px-4"
    >
      {/* Outer card */}
      <div className="rounded-3xl border border-border bg-surface shadow-lg p-4 sm:p-6">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
          {/* LEFT: Photos */}
          <section className="lg:col-span-5">
            <div className="rounded-2xl border border-border bg-surface p-4">
              <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3">
                <div>
                  <h2 className="text-base font-semibold text-text">Fotoğraflar</h2>
                  <p className="text-sm text-text-muted">
                    En fazla {MAX_IMAGES} fotoğraf ekleyebilirsiniz.
                  </p>
                </div>

                <button
                  type="button"
                  onClick={openFileDialog}
                  disabled={remaining <= 0}
                  className="inline-flex items-center justify-center gap-2 rounded-xl border border-border bg-surface-2 px-3 py-2 text-sm font-semibold text-text hover:border-border/70 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  Fotoğraf ekle
                  <span className="text-xs text-text-muted">({remaining})</span>
                </button>

                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/*"
                  multiple
                  onChange={(e) => onPickFiles(e.target.files)}
                  className="hidden"
                />
              </div>

              {/* Dropzone */}
              <button
                type="button"
                onClick={openFileDialog}
                disabled={remaining <= 0}
                className="mt-4 w-full rounded-2xl border border-dashed border-border bg-background p-5 text-left hover:bg-surface-2 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <div className="text-sm font-semibold text-text">
                  Sürükle-bırak veya tıkla
                </div>
                <div className="text-xs text-text-muted mt-1">
                  PNG, JPG, WEBP desteklenir.
                </div>
              </button>

              {/* Preview */}
              {previews.length > 0 ? (
                <div className="mt-4 grid grid-cols-2 sm:grid-cols-3 gap-3">
                  {previews.map((p, idx) => (
                    <div
                      key={p.url}
                      className="relative overflow-hidden rounded-2xl border border-border bg-surface-2"
                    >
                      <img
                        src={p.url}
                        alt={`Seçilen görsel ${idx + 1}`}
                        className="h-28 w-full object-cover"
                        onLoad={() => URL.revokeObjectURL(p.url)}
                      />

                      {/* Top bar */}
                      <div className="absolute inset-x-0 top-0 p-2 flex items-center justify-between">
                        <span className="text-[11px] font-semibold text-text bg-background/80 border border-border rounded-full px-2 py-1 backdrop-blur">
                          {idx + 1}
                        </span>

                        <button
                          type="button"
                          onClick={() => removeImage(idx)}
                          className="text-[11px] font-semibold text-text bg-background/80 border border-border rounded-full px-2 py-1 hover:bg-background backdrop-blur"
                        >
                          Kaldır
                        </button>
                      </div>

                      {/* Bottom bar: order */}
                      <div className="absolute inset-x-0 bottom-0 p-2 flex gap-2">
                        <button
                          type="button"
                          onClick={() => moveImage(idx, idx - 1)}
                          disabled={idx === 0}
                          className="flex-1 rounded-full border border-border bg-background/80 text-text text-xs py-1 hover:bg-background disabled:opacity-50 disabled:cursor-not-allowed backdrop-blur"
                        >
                          ↑
                        </button>
                        <button
                          type="button"
                          onClick={() => moveImage(idx, idx + 1)}
                          disabled={idx === previews.length - 1}
                          className="flex-1 rounded-full border border-border bg-background/80 text-text text-xs py-1 hover:bg-background disabled:opacity-50 disabled:cursor-not-allowed backdrop-blur"
                        >
                          ↓
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="mt-4 text-sm text-text-muted">Henüz fotoğraf eklemediniz.</p>
              )}
            </div>
          </section>

          {/* RIGHT: Form */}
          <section className="lg:col-span-7">
            <div className="rounded-2xl border border-border bg-surface p-5">
              <div className="mb-5">
                <h2 className="text-lg font-semibold text-text">Fırsat Detayları</h2>
                <p className="text-sm text-text-muted mt-1">
                  Fırsata ait temel bilgileri aşağıdaki alanlara giriniz.
                </p>
              </div>

              <div className="flex flex-col gap-4">
                {/* Title */}
                <div className="flex flex-col gap-1">
                  <label className="text-sm font-semibold text-text">Fırsat başlığı</label>
                  <input
                    type="text"
                    placeholder="Örn: %40 indirimli spor ayakkabı"
                    value={data.title}
                    onChange={(e) => onChange({ ...data, title: e.target.value })}
                    className="rounded-xl border border-border bg-surface-2 px-3 py-2 text-text placeholder:text-text-muted outline-none focus:ring-2 focus:ring-[var(--color-primary-ring)]"
                    required
                  />
                  <p className="text-xs text-text-muted">
                    Kullanıcının ilk göreceği kısa ve net başlık.
                  </p>
                </div>

                {/* Description */}
                <div className="flex flex-col gap-1">
                  <label className="text-sm font-semibold text-text">Açıklama</label>
                  <textarea
                    placeholder="İndirim koşulları, geçerlilik süresi veya ek bilgiler..."
                    value={data.description ?? ""}
                    onChange={(e) => onChange({ ...data, description: e.target.value })}
                    className="h-28 resize-none rounded-xl border border-border bg-surface-2 px-3 py-2 text-text placeholder:text-text-muted outline-none focus:ring-2 focus:ring-[var(--color-primary-ring)]"
                  />
                  <p className="text-xs text-text-muted">
                    İsteğe bağlıdır. Fırsat hakkında ek bilgi verebilirsiniz.
                  </p>
                </div>

                {/* Seller */}
                <div className="flex flex-col gap-1">
                  <label className="text-sm font-semibold text-text">Satıcı bilgisi</label>

                  {hasDetectedCompany ? (
                    <>
                      <input
                        type="text"
                        value={data.seller.name ?? ""}
                        disabled
                        className="rounded-xl border border-border bg-background px-3 py-2 text-text-muted cursor-not-allowed"
                      />
                      <p className="text-xs text-text-muted">
                        Satıcı bilgisi ürün bağlantısından otomatik olarak algılanmıştır.
                      </p>
                    </>
                  ) : (
                    <>
                      <input
                        type="text"
                        placeholder="Satıcı adını giriniz"
                        value={data.customCompany ?? ""}
                        onChange={(e) => onChange({ ...data, customCompany: e.target.value })}
                        className="rounded-xl border border-border bg-surface-2 px-3 py-2 text-text placeholder:text-text-muted outline-none focus:ring-2 focus:ring-[var(--color-primary-ring)]"
                      />
                      <p className="text-xs text-text-muted">
                        Satıcı bilgisi otomatik algılanamazsa manuel girilebilir.
                      </p>
                    </>
                  )}
                </div>

                {/* Price */}
                <div className="flex flex-col gap-1">
                  <label className="text-sm font-semibold text-text">Fiyat</label>
                  <input
                    inputMode="numeric"
                    placeholder="Örn: 999"
                    value={data.price ?? ""}
                    onChange={(e) =>
                      onChange({
                        ...data,
                        price: e.target.value ? Number(e.target.value) : undefined,
                      })
                    }
                    className="rounded-xl border border-border bg-surface-2 px-3 py-2 text-text placeholder:text-text-muted outline-none focus:ring-2 focus:ring-[var(--color-primary-ring)]"
                  />
                  <p className="text-xs text-text-muted">KDV dahil satış fiyatını giriniz.</p>
                </div>

                {/* Buttons */}
                <div className="flex gap-3 pt-2">
                  <button
                    type="button"
                    onClick={onBack}
                    className="rounded-xl border border-border bg-background px-4 py-2 text-text font-semibold hover:bg-surface-2"
                  >
                    Geri
                  </button>

                  <button
                    type="submit"
                    className="rounded-xl bg-primary px-6 py-2 font-semibold text-[color:var(--color-on-primary)] hover:bg-primary-hover"
                  >
                    Gönder
                  </button>
                </div>
              </div>
            </div>
          </section>
        </div>
      </div>
    </form>
  )
}
