'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
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
}

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

  const [title, setTitle] = useState('')
  const [description, setDescription] = useState('')
  const [address, setAddress] = useState('')
  const [accessInfo, setAccessInfo] = useState('')
  const [selectedTags, setSelectedTags] = useState<string[]>([])
  const [selectedFeatures, setSelectedFeatures] = useState<string[]>([])
  const [lat, setLat] = useState('55.7558')
  const [lng, setLng] = useState('37.6173')
  const [hourlyRate, setHourlyRate] = useState('')
  const [minHours, setMinHours] = useState('1')
  const [coverFile, setCoverFile] = useState<File | null>(null)
  const [coverPreview, setCoverPreview] = useState('')
  const [showMapPicker, setShowMapPicker] = useState(false)

  useEffect(() => {
    api.get<Tag[]>('/tags').then(setTags).catch(() => {})
    api.get<Feature[]>('/features').then(setFeatures).catch(() => {})
  }, [])

  /** Освобождает 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 handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    setError('')

    try {
      let coverImage: string | undefined

      if (coverFile) {
        const presigned = await api.post<{ upload_url: string; file_url: string; fields: Record<string, string> }>(
          '/upload/presigned-url',
          { content_type: coverFile.type, max_size_mb: 10 }
        )

        const formData = new FormData()
        Object.entries(presigned.fields).forEach(([k, v]) => formData.append(k, v))
        formData.append('file', coverFile)
        await fetch(presigned.upload_url, { method: 'POST', body: formData })

        coverImage = presigned.file_url
      }

      const body: Record<string, unknown> = {
        type,
        title,
        description: description || undefined,
        address: address || undefined,
        lat: parseFloat(lat),
        lng: parseFloat(lng),
        access_info: accessInfo || undefined,
        tags: selectedTags,
        features: selectedFeatures,
        cover_image: coverImage,
      }

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

      await api.post('/places', body)
      if (onSuccess) { onSuccess() } else { router.push('/') }
    } catch (err: any) {
      setError(err.message || 'Ошибка при создании')
    } finally {
      setLoading(false)
    }
  }

  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]
    )
  }

  return (
    <form onSubmit={handleSubmit} className="mx-auto max-w-2xl space-y-6 p-6">
      <h1 className="text-2xl font-bold text-white">
        {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-3 gap-4">
        <div className="flex items-end">
          <button
            type="button"
            onClick={() => setShowMapPicker(true)}
            className="w-full rounded-lg border border-white/10 bg-white/5 px-2 py-3 text-sm text-white/80 hover:bg-white/10 transition text-center leading-tight"
          >
            Указать<br />на карте
          </button>
        </div>
        <div>
          <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>
          <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>

      <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)
              // Освобождаем предыдущий blob-URL, чтобы не было утечки
              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>

      <button
        type="submit"
        disabled={loading}
        className="w-full rounded-lg bg-green-600 px-4 py-3 font-medium text-white hover:bg-green-500 transition disabled:opacity-50"
      >
        {loading ? 'Сохранение...' : `Создать ${type === 'studio' ? 'студию' : 'место'}`}
      </button>

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