'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { ImageUploader, type UploadedImage } from './ImageUploader'
import type { CategoryNodeDTO } from '@/lib/api/cms'

const TYPE_OPTIONS = [
  { value: 'CONDO', label: 'Condo' },
  { value: 'HOUSE', label: 'House' },
  { value: 'PENTHOUSE', label: 'Penthouse' },
  { value: 'LAND', label: 'Land' },
  { value: 'COMMERCIAL', label: 'Commercial' },
]

const AREA_OPTIONS = [
  { value: 'conchas-chinas', label: 'Conchas Chinas' },
  { value: 'zona-romantica', label: 'Zona Romantica' },
  { value: 'emiliano-zapata', label: 'Emiliano Zapata' },
  { value: 'alta-vista', label: 'Alta Vista' },
  { value: 'riviera-nayarit', label: 'Riviera Nayarit' },
]

interface InitialData {
  title: string
  titleEs?: string
  titleFr?: string
  description: string
  descriptionEs?: string
  descriptionFr?: string
  priceUsd?: number
  type: string
  beds?: number
  baths?: number
  sqft?: number
  address?: string
  areaKey?: string
  categorySlug?: string
  mls?: string
  youtubeId?: string
}

interface FormState extends InitialData {}

interface Props {
  listingId: string
  initial?: InitialData
  initialImages: UploadedImage[]
  /** Estado actual del listing (en edit mode). Determina qué botones mostrar. */
  status?: 'DRAFT' | 'PENDING' | 'APPROVED' | 'REJECTED' | 'ARCHIVED'
  /** Nota del admin cuando el listing fue rechazado. */
  rejectionNote?: string
  /** Árbol de categorías. Si viene vacío, el selector no se renderiza. */
  categories?: CategoryNodeDTO[]
}

export function ListingForm({
  listingId,
  initial,
  initialImages,
  status,
  rejectionNote,
  categories = [],
}: Props) {
  const router = useRouter()
  const isEdit = Boolean(initial)
  const canSubmit = !isEdit || status === 'DRAFT' || status === 'REJECTED'

  const [form, setForm] = useState<FormState>(
    initial ?? ({
      title: '',
      description: '',
      type: 'CONDO',
    } as FormState)
  )
  const [images, setImages] = useState<UploadedImage[]>(initialImages)
  const [saving, setSaving] = useState(false)
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState('')

  function update<K extends keyof FormState>(field: K, value: FormState[K]) {
    setForm((f) => ({ ...f, [field]: value }))
  }

  async function save(submit: boolean) {
    setSaving(true)
    setError('')
    try {
      const url = isEdit ? `/api/agent/listings/${listingId}` : '/api/agent/listings'
      const method = isEdit ? 'PATCH' : 'POST'
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      })
      if (!res.ok) {
        const err = await res.json().catch(() => ({}))
        throw new Error(err.error || `Save failed (${res.status})`)
      }
      const { data } = await res.json()
      if (isEdit) {
        router.refresh()
      } else if (submit) {
        router.push('/agent')
      } else {
        router.push(`/agent/listings/${data.id}/edit`)
      }
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Save failed')
    } finally {
      setSaving(false)
    }
  }

  /**
   * Submit for review (solo edit mode, DRAFT/REJECTED).
   * Guarda cambios primero (PATCH) y luego llama /submit.
   */
  async function submitForReview() {
    setSubmitting(true)
    setError('')
    try {
      // Primero guardar cambios (PATCH) — si falla, no submitimos
      const patchRes = await fetch(`/api/agent/listings/${listingId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      })
      if (!patchRes.ok) {
        const err = await patchRes.json().catch(() => ({}))
        throw new Error(err.error || `Save failed (${patchRes.status})`)
      }

      // Luego llamar /submit
      const submitRes = await fetch(`/api/agent/listings/${listingId}/submit`, {
        method: 'POST',
      })
      if (!submitRes.ok) {
        const err = await submitRes.json().catch(() => ({}))
        throw new Error(err.error || `Submit failed (${submitRes.status})`)
      }

      router.refresh()
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Submit failed')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="space-y-6 max-w-4xl">
      {error && (
        <div className="bg-red-50 text-red-700 p-3 rounded" role="alert">
          {error}
        </div>
      )}

      <section className="bg-white rounded-lg shadow-sm border p-6">
        <h2 className="text-lg font-semibold mb-3 text-[#1D2019]">Photos</h2>
        <ImageUploader listingId={listingId} images={images} onChange={setImages} />
      </section>

      <section className="bg-white rounded-lg shadow-sm border p-6 space-y-4">
        <h2 className="text-lg font-semibold text-[#1D2019]">Title and Type</h2>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="block text-sm font-medium mb-1">Title (EN) *</label>
            <input
              value={form.title}
              onChange={(e) => update('title', e.target.value)}
              required
              minLength={5}
              className="w-full px-3 py-2 border rounded focus:border-[#374527]"
            />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">Title (ES)</label>
            <input
              value={form.titleEs || ''}
              onChange={(e) => update('titleEs', e.target.value)}
              className="w-full px-3 py-2 border rounded focus:border-[#374527]"
            />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">Title (FR)</label>
            <input
              value={form.titleFr || ''}
              onChange={(e) => update('titleFr', e.target.value)}
              className="w-full px-3 py-2 border rounded focus:border-[#374527]"
            />
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium mb-1">Type *</label>
            <select
              value={form.type}
              onChange={(e) => update('type', e.target.value)}
              className="w-full px-3 py-2 border rounded focus:border-[#374527]"
            >
              {TYPE_OPTIONS.map((t) => (
                <option key={t.value} value={t.value}>
                  {t.label}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">Area</label>
            <select
              value={form.areaKey || ''}
              onChange={(e) => update('areaKey', e.target.value || undefined)}
              className="w-full px-3 py-2 border rounded focus:border-[#374527]"
            >
              <option value="">Select...</option>
              {AREA_OPTIONS.map((a) => (
                <option key={a.value} value={a.value}>
                  {a.label}
                </option>
              ))}
            </select>
          </div>
        </div>
      </section>

      {/* El catálogo agrupa por categoría, así que sin esto la propiedad
          queda invisible en la navegación. Opcional: si el CMS no devuelve
          categorías, el formulario sigue guardando. */}
      {categories.length > 0 && (
        <section className="mb-6">
          <h2 className="text-lg font-semibold mb-4">Category</h2>
          <div>
            <label className="block text-sm font-medium mb-1">Category</label>
            <select
              value={form.categorySlug || ''}
              onChange={(e) => update('categorySlug', e.target.value || undefined)}
              className="w-full px-3 py-2 border rounded focus:border-[#374527]"
            >
              <option value="">Select...</option>
              {categories.map((root) => (
                <optgroup key={root.id} label={`${root.name} (${root.kind})`}>
                  <option value={root.slug}>{root.name}</option>
                  {root.children.map((child) => (
                    <option key={child.id} value={child.slug}>
                      {root.name} › {child.name}
                    </option>
                  ))}
                </optgroup>
              ))}
            </select>
          </div>
        </section>
      )}

      <section className="bg-white rounded-lg shadow-sm border p-6 space-y-4">
        <div>
          <label className="block text-sm font-medium mb-1">Description (EN) *</label>
          <textarea
            value={form.description}
            onChange={(e) => update('description', e.target.value)}
            required
            minLength={20}
            rows={5}
            className="w-full px-3 py-2 border rounded focus:border-[#374527]"
          />
          <p className="text-xs text-gray-500 mt-1">
            English is required. Spanish and French are optional but recommended.
          </p>
        </div>

        <details className="border rounded-lg">
          <summary className="px-4 py-2 cursor-pointer text-sm font-medium text-gray-700 hover:bg-gray-50">
            Translations (ES / FR) - optional but recommended
          </summary>
          <div className="p-4 space-y-3 border-t">
            <div>
              <label className="block text-sm font-medium mb-1">Description (ES)</label>
              <textarea
                value={form.descriptionEs || ''}
                onChange={(e) => update('descriptionEs', e.target.value)}
                rows={4}
                className="w-full px-3 py-2 border rounded focus:border-[#374527]"
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">Description (FR)</label>
              <textarea
                value={form.descriptionFr || ''}
                onChange={(e) => update('descriptionFr', e.target.value)}
                rows={4}
                className="w-full px-3 py-2 border rounded focus:border-[#374527]"
              />
            </div>
          </div>
        </details>
      </section>

      <section className="bg-white rounded-lg shadow-sm border p-6">
        <h2 className="text-lg font-semibold mb-3 text-[#1D2019]">Details</h2>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div>
            <label className="block text-sm font-medium mb-1">Price (USD)</label>
            <input
              type="number"
              value={form.priceUsd ?? ''}
              onChange={(e) =>
                update('priceUsd', e.target.value ? Number(e.target.value) : undefined)
              }
              className="w-full px-3 py-2 border rounded focus:border-[#374527]"
            />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">Beds</label>
            <input
              type="number"
              min={0}
              max={20}
              value={form.beds ?? ''}
              onChange={(e) =>
                update('beds', e.target.value ? Number(e.target.value) : undefined)
              }
              className="w-full px-3 py-2 border rounded focus:border-[#374527]"
            />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">Baths</label>
            <input
              type="number"
              step="0.5"
              min={0}
              max={20}
              value={form.baths ?? ''}
              onChange={(e) =>
                update('baths', e.target.value ? Number(e.target.value) : undefined)
              }
              className="w-full px-3 py-2 border rounded focus:border-[#374527]"
            />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">Sqft</label>
            <input
              type="number"
              min={0}
              value={form.sqft ?? ''}
              onChange={(e) =>
                update('sqft', e.target.value ? Number(e.target.value) : undefined)
              }
              className="w-full px-3 py-2 border rounded focus:border-[#374527]"
            />
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
          <div>
            <label className="block text-sm font-medium mb-1">Address</label>
            <input
              value={form.address || ''}
              onChange={(e) => update('address', e.target.value)}
              className="w-full px-3 py-2 border rounded focus:border-[#374527]"
            />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">YouTube ID (optional)</label>
            <input
              value={form.youtubeId || ''}
              onChange={(e) => update('youtubeId', e.target.value)}
              placeholder="e.g. dQw4w9WgXcQ"
              className="w-full px-3 py-2 border rounded focus:border-[#374527]"
            />
          </div>
        </div>
      </section>

      {isEdit && status === 'REJECTED' && (
        <div className="bg-red-50 border border-red-200 rounded-lg p-4 text-sm text-red-800">
          <p className="font-semibold mb-1">This listing was rejected.</p>
          {rejectionNote && (
            <p className="text-red-700">
              <span className="font-medium">Reason: </span>
              {rejectionNote}
            </p>
          )}
          <p className="text-xs text-red-600 mt-2">
            Make the requested changes and click &quot;Resubmit for review&quot;.
          </p>
        </div>
      )}

      <div className="flex gap-3 pt-4 sticky bottom-0 bg-gray-50 py-3 -mx-8 px-8 border-t">
        {!isEdit && (
          <button
            onClick={() => save(false)}
            disabled={saving}
            className="px-4 py-2 border border-[#374527] text-[#374527] rounded hover:bg-white disabled:opacity-50"
          >
            Save as draft
          </button>
        )}
        {isEdit && (
          <button
            onClick={() => save(true)}
            disabled={saving}
            className="px-4 py-2 border border-[#374527] text-[#374527] rounded hover:bg-white disabled:opacity-50"
          >
            {saving ? 'Saving...' : 'Save changes'}
          </button>
        )}
        {canSubmit ? (
          <button
            onClick={submitForReview}
            disabled={submitting || saving}
            className="px-4 py-2 bg-[#374527] text-white rounded hover:bg-[#1D2019] disabled:opacity-50"
          >
            {submitting
              ? 'Submitting...'
              : status === 'REJECTED'
                ? 'Resubmit for review'
                : 'Submit for review'}
          </button>
        ) : (
          <button
            disabled
            title="Listing is already pending or published. Contact admin to make changes."
            className="px-4 py-2 bg-gray-300 text-gray-500 rounded cursor-not-allowed"
          >
            {status === 'PENDING'
              ? 'Awaiting review'
              : status === 'APPROVED'
                ? 'Published'
                : status === 'ARCHIVED'
                  ? 'Archived'
                  : 'Submit'}
          </button>
        )}
      </div>
    </div>
  )
}