import { useEffect, useRef, useState } from 'react'
import { ImagePlus, X } from 'lucide-react'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Switch } from '@/components/ui/switch'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
import { RichTextEditor } from '@/components/rich-text-editor'
import { apiOrigin } from '@/lib/api/client'
import { uploadImage } from '@/lib/api/upload'

type FieldDef = {
  key: string
  label: string
  type: 'text' | 'textarea' | 'richtext' | 'url' | 'number' | 'boolean' | 'image'
  placeholder?: string
  half?: boolean
}

const blockFieldMap: Record<string, FieldDef[]> = {
  hero: [
    { key: 'title', label: 'Başlık', type: 'text', placeholder: 'Hero başlığı' },
    { key: 'subtitle', label: 'Alt başlık', type: 'text', placeholder: 'Kısa açıklama' },
    { key: 'description', label: 'Açıklama', type: 'richtext', placeholder: 'Detaylı açıklama' },
    { key: 'button_text', label: 'Buton metni', type: 'text', placeholder: 'Detaylı Bilgi', half: true },
    { key: 'button_url', label: 'Buton linki', type: 'url', placeholder: '/iletisim', half: true },
    { key: 'image', label: 'Arka plan görseli', type: 'image' },
  ],
  text: [
    { key: 'title', label: 'Başlık', type: 'text', placeholder: 'Bölüm başlığı' },
    { key: 'body', label: 'İçerik', type: 'richtext', placeholder: 'Metin içeriği...' },
  ],
  text_image: [
    { key: 'title', label: 'Başlık', type: 'text', placeholder: 'Bölüm başlığı' },
    { key: 'body', label: 'Metin', type: 'richtext', placeholder: 'Açıklama metni' },
    { key: 'image', label: 'Görsel', type: 'image' },
    { key: 'image_alt', label: 'Görsel alt metni', type: 'text', placeholder: 'Görselin açıklaması' },
  ],
  stats_grid: [
    { key: 'title', label: 'Başlık', type: 'text', placeholder: 'İstatistikler' },
    { key: 'stat_1_value', label: 'Değer 1', type: 'text', placeholder: '500+', half: true },
    { key: 'stat_1_label', label: 'Etiket 1', type: 'text', placeholder: 'Öğrenci', half: true },
    { key: 'stat_2_value', label: 'Değer 2', type: 'text', placeholder: '50+', half: true },
    { key: 'stat_2_label', label: 'Etiket 2', type: 'text', placeholder: 'Eğitim', half: true },
    { key: 'stat_3_value', label: 'Değer 3', type: 'text', placeholder: '20+', half: true },
    { key: 'stat_3_label', label: 'Etiket 3', type: 'text', placeholder: 'Eğitmen', half: true },
    { key: 'stat_4_value', label: 'Değer 4', type: 'text', placeholder: '10+', half: true },
    { key: 'stat_4_label', label: 'Etiket 4', type: 'text', placeholder: 'Yıl', half: true },
  ],
  cta: [
    { key: 'title', label: 'Başlık', type: 'text', placeholder: 'Hemen Başlayın' },
    { key: 'description', label: 'Açıklama', type: 'textarea', placeholder: 'CTA açıklaması' },
    { key: 'button_text', label: 'Buton metni', type: 'text', placeholder: 'Kayıt Ol', half: true },
    { key: 'button_url', label: 'Buton linki', type: 'url', placeholder: '/kayit', half: true },
  ],
  faq: [
    { key: 'title', label: 'Başlık', type: 'text', placeholder: 'Sıkça Sorulan Sorular' },
    { key: 'q1', label: 'Soru 1', type: 'text', placeholder: 'Soru...' },
    { key: 'a1', label: 'Cevap 1', type: 'textarea', placeholder: 'Cevap...' },
    { key: 'q2', label: 'Soru 2', type: 'text', placeholder: 'Soru...' },
    { key: 'a2', label: 'Cevap 2', type: 'textarea', placeholder: 'Cevap...' },
    { key: 'q3', label: 'Soru 3', type: 'text', placeholder: 'Soru...' },
    { key: 'a3', label: 'Cevap 3', type: 'textarea', placeholder: 'Cevap...' },
  ],
  gallery: [
    { key: 'title', label: 'Başlık', type: 'text', placeholder: 'Galeri başlığı' },
    { key: 'image_1', label: 'Görsel 1', type: 'image' },
    { key: 'image_2', label: 'Görsel 2', type: 'image' },
    { key: 'image_3', label: 'Görsel 3', type: 'image' },
    { key: 'image_4', label: 'Görsel 4', type: 'image' },
  ],
  video: [
    { key: 'title', label: 'Başlık', type: 'text', placeholder: 'Video başlığı' },
    { key: 'video_url', label: 'Video URL', type: 'url', placeholder: 'https://youtube.com/watch?v=...' },
    { key: 'description', label: 'Açıklama', type: 'textarea', placeholder: 'Video açıklaması' },
    { key: 'thumbnail', label: 'Kapak görseli', type: 'image' },
  ],
  cards: [
    { key: 'title', label: 'Bölüm başlığı', type: 'text', placeholder: 'Kartlar bölümü' },
    { key: 'card_1_title', label: 'Kart 1 - Başlık', type: 'text', placeholder: 'Başlık', half: true },
    { key: 'card_1_icon', label: 'Kart 1 - İkon', type: 'text', placeholder: 'anchor', half: true },
    { key: 'card_1_text', label: 'Kart 1 - Metin', type: 'textarea', placeholder: 'Açıklama' },
    { key: 'card_2_title', label: 'Kart 2 - Başlık', type: 'text', placeholder: 'Başlık', half: true },
    { key: 'card_2_icon', label: 'Kart 2 - İkon', type: 'text', placeholder: 'compass', half: true },
    { key: 'card_2_text', label: 'Kart 2 - Metin', type: 'textarea', placeholder: 'Açıklama' },
    { key: 'card_3_title', label: 'Kart 3 - Başlık', type: 'text', placeholder: 'Başlık', half: true },
    { key: 'card_3_icon', label: 'Kart 3 - İkon', type: 'text', placeholder: 'shield', half: true },
    { key: 'card_3_text', label: 'Kart 3 - Metin', type: 'textarea', placeholder: 'Açıklama' },
  ],
  testimonials: [
    { key: 'title', label: 'Bölüm başlığı', type: 'text', placeholder: 'Referanslar' },
    { key: 'ref_1_name', label: 'Referans 1 - İsim', type: 'text', placeholder: 'Ad Soyad', half: true },
    { key: 'ref_1_role', label: 'Referans 1 - Ünvan', type: 'text', placeholder: 'Kaptan', half: true },
    { key: 'ref_1_text', label: 'Referans 1 - Yorum', type: 'textarea', placeholder: 'Yorum' },
    { key: 'ref_2_name', label: 'Referans 2 - İsim', type: 'text', placeholder: 'Ad Soyad', half: true },
    { key: 'ref_2_role', label: 'Referans 2 - Ünvan', type: 'text', placeholder: 'Mühendis', half: true },
    { key: 'ref_2_text', label: 'Referans 2 - Yorum', type: 'textarea', placeholder: 'Yorum' },
  ],
  html: [
    { key: 'html', label: 'HTML İçerik', type: 'textarea', placeholder: '<div>...</div>' },
  ],
}

export function getFieldsForType(type: string): FieldDef[] {
  return blockFieldMap[type] ?? [
    { key: 'title', label: 'Başlık', type: 'text', placeholder: 'Başlık' },
    { key: 'body', label: 'İçerik', type: 'richtext', placeholder: 'İçerik' },
  ]
}

export function contentToFieldValues(
  type: string,
  content: Record<string, unknown> | null
): Record<string, string> {
  const fields = getFieldsForType(type)
  const values: Record<string, string> = {}
  for (const field of fields) {
    const raw = content?.[field.key]
    values[field.key] = raw != null ? String(raw) : ''
  }
  return values
}

export function fieldValuesToContent(
  values: Record<string, string>
): Record<string, unknown> {
  const content: Record<string, unknown> = {}
  for (const [key, value] of Object.entries(values)) {
    if (value.trim() !== '') {
      content[key] = value
    }
  }
  return content
}

export function getBlockPreviewText(
  type: string,
  content: Record<string, unknown> | null
): string {
  if (!content) return 'Boş blok'
  const title = content.title ?? content.html ?? content.body ?? ''
  const str = String(title).replace(/<[^>]*>/g, '').trim()
  return str.length > 80 ? str.slice(0, 80) + '...' : str || 'Boş blok'
}

function InlineImageUpload({
  value,
  onChange,
  label,
}: {
  value: string
  onChange: (path: string) => void
  label: string
}) {
  const inputRef = useRef<HTMLInputElement | null>(null)
  const [uploading, setUploading] = useState(false)
  const [localPreview, setLocalPreview] = useState<string | null>(null)

  const serverPreview = value
    ? value.startsWith('http')
      ? value
      : `${apiOrigin}/${value.replace(/^\/+/, '').replace(/^storage\//, '')}`
    : null

  const displayPreview = localPreview ?? serverPreview

  useEffect(() => {
    return () => {
      if (localPreview) URL.revokeObjectURL(localPreview)
    }
  }, [localPreview])

  async function handleFile(file: File) {
    const blobUrl = URL.createObjectURL(file)
    setLocalPreview(blobUrl)
    setUploading(true)
    try {
      const result = await uploadImage(file)
      onChange(result.path)
    } catch {
      setLocalPreview(null)
    } finally {
      setUploading(false)
    }
  }

  return (
    <div className='space-y-2'>
      <Label className='text-sm'>{label}</Label>
      <input
        ref={inputRef}
        type='file'
        accept='image/*'
        className='hidden'
        onChange={(e) => {
          const file = e.target.files?.[0]
          if (file) handleFile(file)
          e.currentTarget.value = ''
        }}
      />
      <div className='flex items-center gap-3'>
        <button
          type='button'
          onClick={() => inputRef.current?.click()}
          disabled={uploading}
          className='group relative flex h-20 w-28 shrink-0 items-center justify-center overflow-hidden rounded-xl border border-dashed border-border/70 bg-muted/20 transition hover:border-primary/40'
        >
          {displayPreview ? (
            <img
              src={displayPreview}
              alt={label}
              className='h-full w-full object-cover'
            />
          ) : (
            <ImagePlus className='size-5 text-muted-foreground transition group-hover:text-foreground' />
          )}
          {uploading && (
            <div className='absolute inset-0 flex items-center justify-center bg-background/70'>
              <div className='size-4 animate-spin rounded-full border-2 border-primary border-t-transparent' />
            </div>
          )}
        </button>
        <div className='min-w-0 flex-1'>
          {uploading ? (
            <p className='text-xs text-amber-600'>Yükleniyor...</p>
          ) : value ? (
            <div className='flex items-center gap-2'>
              <p className='truncate text-xs text-muted-foreground'>{value}</p>
              <Button
                type='button'
                variant='ghost'
                size='icon'
                className='size-6 shrink-0'
                onClick={() => {
                  onChange('')
                  setLocalPreview(null)
                }}
              >
                <X className='size-3' />
              </Button>
            </div>
          ) : (
            <p className='text-xs text-muted-foreground'>
              Görsel yüklemek için tıklayın
            </p>
          )}
        </div>
      </div>
    </div>
  )
}

export function BlockContentFields({
  type,
  values,
  onChange,
}: {
  type: string
  values: Record<string, string>
  onChange: (values: Record<string, string>) => void
}) {
  const fields = getFieldsForType(type)

  function updateField(key: string, value: string) {
    onChange({ ...values, [key]: value })
  }

  const grouped: (FieldDef | FieldDef[])[] = []
  let i = 0
  while (i < fields.length) {
    const field = fields[i]
    if (field.half && i + 1 < fields.length && fields[i + 1].half) {
      grouped.push([field, fields[i + 1]])
      i += 2
    } else {
      grouped.push(field)
      i++
    }
  }

  return (
    <div className='space-y-4'>
      {grouped.map((item) => {
        if (Array.isArray(item)) {
          return (
            <div key={item[0].key} className='grid gap-3 sm:grid-cols-2'>
              {item.map((f) => (
                <FieldRenderer
                  key={f.key}
                  field={f}
                  value={values[f.key] ?? ''}
                  onChange={(v) => updateField(f.key, v)}
                />
              ))}
            </div>
          )
        }
        return (
          <FieldRenderer
            key={item.key}
            field={item}
            value={values[item.key] ?? ''}
            onChange={(v) => updateField(item.key, v)}
          />
        )
      })}
    </div>
  )
}

function FieldRenderer({
  field,
  value,
  onChange,
}: {
  field: FieldDef
  value: string
  onChange: (value: string) => void
}) {
  switch (field.type) {
    case 'richtext':
      return (
        <div className='space-y-1.5'>
          <Label className='text-sm'>{field.label}</Label>
          <RichTextEditor
            value={value}
            onChange={onChange}
            placeholder={field.placeholder}
          />
        </div>
      )
    case 'image':
      return (
        <InlineImageUpload
          value={value}
          onChange={onChange}
          label={field.label}
        />
      )
    case 'textarea':
      return (
        <div className='space-y-1.5'>
          <Label className='text-sm'>{field.label}</Label>
          <Textarea
            value={value}
            onChange={(e) => onChange(e.target.value)}
            placeholder={field.placeholder}
            rows={3}
          />
        </div>
      )
    case 'boolean':
      return (
        <div className='flex items-center justify-between rounded-xl border border-border/70 px-3 py-2'>
          <Label className='text-sm'>{field.label}</Label>
          <Switch
            checked={value === 'true'}
            onCheckedChange={(checked) => onChange(String(checked))}
          />
        </div>
      )
    default:
      return (
        <div className='space-y-1.5'>
          <Label className='text-sm'>{field.label}</Label>
          <Input
            type={field.type === 'number' ? 'number' : 'text'}
            value={value}
            onChange={(e) => onChange(e.target.value)}
            placeholder={field.placeholder}
          />
        </div>
      )
  }
}
