'use client'

import { useState, useEffect } from 'react'
import dynamic from 'next/dynamic'
import { api } from '@/lib/api'
import type { Tag, Feature } from '@/types'

const MapPicker = dynamic(() => import('./MapPicker'), { ssr: false })

/** Пропсы компонента формы создания/редактирования места/студии */
interface PlaceFormProps {
  /** Тип объекта: место или студия */
  type: 'place' | 'studio'
  /** Колбэк после успешного сохранения */
  onSuccess?: () => void
  /** Данные места для редактирования */
  place?: import('@/types').Place
}

/**
 * Форма создания нового места или студии.
 * Собирает название, описание, адрес, координаты, теги, характеристики и обложку.
 * Для студий дополнительно запрашивает цену за час и минимальное количество часов.
 * Перед сохранением загружает обложку через presigned URL.
 * @param type - Тип объекта: 'place' — место, 'studio' — студия
 */
export default function PlaceForm({ type, onSuccess, place }: PlaceFormProps) {
  const isEdit = !!place
  const [tags, setTags] = useState<Tag[]>([])
  const [features, setFeatures] = useState<Feature[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  const [title, setTitle] = useState(place?.title || '')
  const [description, setDescription] = useState(place?.description || '')
  const [address, setAddress] = useState(place?.address || '')
  const [accessInfo, setAccessInfo] = useState(place?.access_info || '')
  const [selectedTags, setSelectedTags] = useState<string[]>(place?.tags?.map((t) => t.id) || [])
  const [selectedFeatures, setSelectedFeatures] = useState<string[]>(place?.features?.map((f) => f.id) || [])
  const [lat, setLat] = useState(place?.lat?.toString() || '55.7558')
  const [lng, setLng] = useState(place?.lng?.toString() || '37.6173')
  const [hourlyRate, setHourlyRate] = useState(place?.hourly_rate?.toString() || '')
  const [minHours, setMinHours] = useState(place?.min_hours?.toString() || '1')
  const [coverFile, setCoverFile] = useState<File | null>(null)
  const [coverPreview, setCoverPreview] = useState(place?.cover_image || '')
  const [showMapPicker, setShowMapPicker] = useState(false)
  const [saved, setSaved] = useState<'draft' | 'submitted' | null>(null)

  useEffect(() => {
    api.get<Tag[]>('/tags').then(setTags).catch(() => setError('Ошибка загрузки тегов'))
    api.get<Feature[]>('/features').then(setFeatures).catch(() => setError('Ошибка загрузки характеристик'))
  }, [])

  /** Освобождает blob-URL обложки при размонтировании или смене preview */
  useEffect(() => {
    return () => {
      if (coverPreview) {
        URL.revokeObjectURL(coverPreview)
      }
    }
  }, [coverPreview])

  const handleMapPick = (pickLat: number, pickLng: number, pickAddress?: string) => {
    setLat(pickLat.toFixed(6))
    setLng(pickLng.toFixed(6))
    if (pickAddress) setAddress(pickAddress)
    setShowMapPicker(false)
  }

  const submitPlace = async (status?: string) => {
    setLoading(true)
    setError('')

    try {
      let coverImage: string | undefined

      if (coverFile) {
        const formData = new FormData()
        formData.append('file', coverFile)
        const res = await api.upload<{ file_url: string }>('/upload', formData)
        coverImage = res.file_url
      }

      const parsedLat = parseFloat(lat)
      const parsedLng = parseFloat(lng)
      if (isNaN(parsedLat) || isNaN(parsedLng)) {
        setError('Укажите корректные координаты')
        return
      }

      const body: Record<string, unknown> = {
        title,
        description: description || undefined,
        address: address || undefined,
        lat: parsedLat,
        lng: parsedLng,
        access_info: accessInfo || undefined,
        tags: selectedTags,
        features: selectedFeatures,
      }

      if (!isEdit) body.type = type

      if (coverImage) body.cover_image = coverImage

      if (type === 'studio') {
        body.hourly_rate = hourlyRate !== '' ? parseInt(hourlyRate) : undefined
        const parsedMinHours = parseInt(minHours)
        body.min_hours = isNaN(parsedMinHours) ? 1 : parsedMinHours
        body.currency = 'RUB'
      }

      if (status) body.status = status

      if (isEdit) {
        await api.patch(`/places/${place.id}`, body)
        if (onSuccess) onSuccess()
      } else {
        await api.post('/places', body)
        setSaved(status === 'draft' ? 'draft' : 'submitted')
      }
    } catch (err: any) {
      setError(err.message || 'Ошибка при создании')
    } finally {
      setLoading(false)
    }
  }

  const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); submitPlace() }
  const handleSaveDraft = () => submitPlace('draft')

  const toggleTag = (id: string) => {
    setSelectedTags((prev) =>
      prev.includes(id) ? prev.filter((t) => t !== id) : [...prev, id]
    )
  }

  const toggleFeature = (id: string) => {
    setSelectedFeatures((prev) =>
      prev.includes(id) ? prev.filter((f) => f !== id) : [...prev, id]
    )
  }

  if (saved) {
    return (
      <div className="mx-auto max-w-2xl space-y-4 p-6 text-center">
        <p className="text-lg font-medium text-green-400">
          {saved === 'draft' ? 'Черновик сохранён' : 'Место отправлено на модерацию'}
        </p>
        <a href={type === 'studio' ? '/studios/add' : '/places/add'}
          className="inline-block rounded-lg bg-green-600 px-6 py-2 text-white hover:bg-green-500 transition"
        >Добавить ещё</a>
      </div>
    )
  }

  return (
    <form onSubmit={handleSubmit} className="mx-auto max-w-2xl space-y-6 p-6">
      <h1 className="text-2xl font-bold text-white">
        {isEdit ? 'Редактировать' : type === 'studio' ? 'Добавить студию' : 'Добавить место'}
      </h1>

      {error && <p className="rounded-lg bg-red-500/10 p-3 text-sm text-red-400">{error}</p>}

      <div>
        <label className="mb-1 block text-sm text-white/60">Название *</label>
        <input
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-3 text-white outline-none focus:border-green-500"
          required
        />
      </div>

      <div>
        <label className="mb-1 block text-sm text-white/60">Описание</label>
        <textarea
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          rows={4}
          className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-3 text-white outline-none focus:border-green-500"
        />
      </div>

      <div>
        <label className="mb-1 block text-sm text-white/60">Адрес</label>
        <input
          value={address}
          onChange={(e) => setAddress(e.target.value)}
          className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-3 text-white outline-none focus:border-green-500"
        />
      </div>

      <div className="grid grid-cols-5 gap-4">
        <div className="col-span-2">
          <label className="mb-1 block text-sm text-white/60">Широта</label>
          <input
            type="number"
            step="any"
            value={lat}
            onChange={(e) => setLat(e.target.value)}
            className="w-full rounded-lg border border-white/10 bg-white/5 px-3 py-3 text-white outline-none focus:border-green-500"
          />
        </div>
        <div className="col-span-2">
          <label className="mb-1 block text-sm text-white/60">Долгота</label>
          <input
            type="number"
            step="any"
            value={lng}
            onChange={(e) => setLng(e.target.value)}
            className="w-full rounded-lg border border-white/10 bg-white/5 px-3 py-3 text-white outline-none focus:border-green-500"
          />
        </div>
        <div className="col-span-1 flex items-end">
          <button
            type="button"
            onClick={() => setShowMapPicker(true)}
            className="h-[50px] w-auto rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-sm text-white/80 hover:bg-white/10 transition text-center leading-tight"
          >
            Указать<br />на карте
          </button>
        </div>
      </div>

      <div>
        <label className="mb-1 block text-sm text-white/60">Информация о доступе</label>
        <textarea
          value={accessInfo}
          onChange={(e) => setAccessInfo(e.target.value)}
          rows={2}
          className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-3 text-white outline-none focus:border-green-500"
          placeholder="Как добраться, парковка..."
        />
      </div>

      <div>
        <label className="mb-1 block text-sm text-white/60">Обложка</label>
        <input
          type="file"
          accept="image/*"
          onChange={(e) => {
            const file = e.target.files?.[0]
            if (file) {
              setCoverFile(file)
              if (coverPreview) URL.revokeObjectURL(coverPreview)
              setCoverPreview(URL.createObjectURL(file))
            }
          }}
          className="w-full text-sm text-white/60 file:mr-4 file:rounded-lg file:border-0 file:bg-green-600 file:px-4 file:py-2 file:text-white file:hover:bg-green-500"
        />
        {coverPreview && (
          <img src={coverPreview} alt="preview" className="mt-2 h-32 rounded-lg object-cover" />
        )}
      </div>

      {type === 'studio' && (
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="mb-1 block text-sm text-white/60">Цена за час (₽)</label>
            <input
              type="number"
              value={hourlyRate}
              onChange={(e) => setHourlyRate(e.target.value)}
              className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-3 text-white outline-none focus:border-green-500"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm text-white/60">Мин. часов</label>
            <input
              type="number"
              min="1"
              value={minHours}
              onChange={(e) => setMinHours(e.target.value)}
              className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-3 text-white outline-none focus:border-green-500"
            />
          </div>
        </div>
      )}

      <div>
        <label className="mb-2 block text-sm text-white/60">Теги (стили съёмки)</label>
        <div className="flex flex-wrap gap-2">
          {tags.map((tag) => (
            <button
              key={tag.id}
              type="button"
              onClick={() => toggleTag(tag.id)}
              className={`rounded-full px-3 py-1.5 text-sm transition ${
                selectedTags.includes(tag.id)
                  ? 'bg-green-600 text-white'
                  : 'bg-white/10 text-white/60 hover:bg-white/20'
              }`}
            >
              {tag.name}
            </button>
          ))}
        </div>
      </div>

      <div>
        <label className="mb-2 block text-sm text-white/60">Характеристики</label>
        <div className="flex flex-wrap gap-2">
          {features.map((feat) => (
            <button
              key={feat.id}
              type="button"
              onClick={() => toggleFeature(feat.id)}
              className={`rounded-full px-3 py-1.5 text-sm transition ${
                selectedFeatures.includes(feat.id)
                  ? 'bg-green-600 text-white'
                  : 'bg-white/10 text-white/60 hover:bg-white/20'
              }`}
            >
              {feat.name}
            </button>
          ))}
        </div>
      </div>

      <div className="flex gap-3">
        {!isEdit && (
          <button type="button" onClick={handleSaveDraft} disabled={loading}
            className="flex-1 rounded-lg border border-white/20 px-4 py-3 font-medium text-white/80 hover:bg-white/5 transition disabled:opacity-50"
          >{loading ? 'Сохранение...' : 'Сохранить черновик'}</button>
        )}
        <button type="submit" disabled={loading}
          className={`rounded-lg bg-green-600 px-4 py-3 font-medium text-white hover:bg-green-500 transition disabled:opacity-50 ${isEdit ? 'w-full' : 'flex-1'}`}
        >
          {loading ? 'Сохранение...' : isEdit ? 'Сохранить' : `Опубликовать ${type === 'studio' ? 'студию' : 'место'}`}
        </button>
      </div>

      {showMapPicker && <MapPicker onSelect={handleMapPick} onClose={() => setShowMapPicker(false)} />}
    </form>
  )
}
