import { startTransition, useEffect, useState } from 'react'
import { useForm, useWatch } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { useMutation } from '@tanstack/react-query'
import { ArrowLeft, Loader2, Plus, X } from 'lucide-react'
import { toast } from 'sonner'
import { apiOrigin } from '@/lib/api/client'
import { uploadImage } from '@/lib/api/upload'
import { RichTextEditor } from '@/components/rich-text-editor'
import { ImageUploadField } from '@/components/image-upload-field'
import type { AdminCategoryRecord, AdminCourseRecord } from '@/lib/api/types'
import { handleServerError } from '@/lib/handle-server-error'
import { Button } from '@/components/ui/button'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Textarea } from '@/components/ui/textarea'
import {
  courseFormSchema,
  metaTitleMinLength,
  metaTitleMaxLength,
  metaDescriptionMinLength,
  metaDescriptionMaxLength,
  getSeoCounter,
} from '../helpers'
import type { CourseFormInput, CourseFormValues } from '../helpers'

// ── SeoCharacterHint ───────────────────────────────────────────────────
function SeoCharacterHint({
  length,
  min,
  max,
}: {
  length: number
  min: number
  max: number
}) {
  const counter = getSeoCounter(length, min, max)
  return (
    <div className='mt-2 flex items-center justify-between gap-3 text-xs'>
      <span
        className={
          counter.tone === 'good'
            ? 'font-medium text-emerald-700'
            : counter.tone === 'danger'
              ? 'font-medium text-rose-700'
              : 'font-medium text-amber-700'
        }
      >
        {counter.text}
      </span>
      <span
        className={
          counter.tone === 'good'
            ? 'rounded-full bg-emerald-100 px-2 py-1 font-semibold text-emerald-800'
            : counter.tone === 'danger'
              ? 'rounded-full bg-rose-100 px-2 py-1 font-semibold text-rose-800'
              : 'rounded-full bg-amber-100 px-2 py-1 font-semibold text-amber-800'
        }
      >
        {length} karakter
      </span>
    </div>
  )
}

// ── BulletListField ────────────────────────────────────────────────────
function BulletListField({
  label,
  description,
  value,
  onChange,
  placeholder,
}: {
  label: string
  description: string
  value: string[]
  onChange: (value: string[]) => void
  placeholder: string
}) {
  const [draft, setDraft] = useState('')

  const addItem = () => {
    const nextValue = draft.trim()
    if (!nextValue) return
    onChange([...value, nextValue])
    setDraft('')
  }

  return (
    <div className='space-y-3 rounded-3xl border border-border/70 bg-card p-4 shadow-sm'>
      <div className='space-y-1'>
        <p className='text-sm font-medium'>{label}</p>
        <p className='text-sm text-muted-foreground'>{description}</p>
      </div>
      <div className='flex gap-2'>
        <Input
          value={draft}
          onChange={(event) => setDraft(event.target.value)}
          onKeyDown={(event) => {
            if (event.key === 'Enter') {
              event.preventDefault()
              addItem()
            }
          }}
          placeholder={placeholder}
        />
        <Button type='button' onClick={addItem} className='rounded-xl'>
          <Plus />
          Ekle
        </Button>
      </div>
      <div className='rounded-2xl border border-dashed border-border/70 bg-muted/10 p-4'>
        {value.length ? (
          <ul className='space-y-2'>
            {value.map((item, index) => (
              <li
                key={`${label}-${index}-${item}`}
                className='flex items-start justify-between gap-3 rounded-2xl border border-border/60 bg-muted/20 px-3 py-2 text-sm'
              >
                <div className='flex items-start gap-2'>
                  <span className='mt-1 size-2 shrink-0 rounded-full bg-primary' />
                  <span>{item}</span>
                </div>
                <Button
                  type='button'
                  variant='ghost'
                  size='icon'
                  className='size-8 rounded-lg text-muted-foreground'
                  onClick={() =>
                    onChange(value.filter((_, i) => i !== index))
                  }
                >
                  <X className='size-4' />
                </Button>
              </li>
            ))}
          </ul>
        ) : (
          <p className='text-sm text-muted-foreground'>
            Eklenen maddeler burada madde işaretli liste olarak görünecek.
          </p>
        )}
      </div>
    </div>
  )
}

// ── CourseForm (main export) ───────────────────────────────────────────
export function CourseForm({
  course,
  categories,
  isPending,
  onCancel,
  onSubmit,
}: {
  course: AdminCourseRecord | null
  categories: AdminCategoryRecord[]
  isPending: boolean
  onCancel: () => void
  onSubmit: (values: CourseFormValues) => Promise<void>
}) {
  const form = useForm<CourseFormInput, undefined, CourseFormValues>({
    resolver: zodResolver(courseFormSchema),
    defaultValues: {
      categoryId: Number(course?.categoryId ?? 0),
      title: course?.title ?? '',
      slug: course?.slug ?? '',
      sub: course?.sub ?? '',
      duration: course?.duration ?? '',
      price: course?.price ?? '',
      badge: course?.badge ?? '',
      standard: course?.standard ?? '',
      image: course?.image ?? '',
      description: course?.description ?? '',
      longDescription: course?.longDescription ?? undefined,
      includes: course?.includes ?? [],
      requirements: course?.requirements ?? [],
      scope: course?.scope ?? [],
      metaTitle: course?.metaTitle ?? '',
      metaDescription: course?.metaDescription ?? '',
    } satisfies CourseFormInput,
  })

  useEffect(() => {
    form.reset({
      categoryId: Number(course?.categoryId ?? 0),
      title: course?.title ?? '',
      slug: course?.slug ?? '',
      sub: course?.sub ?? '',
      duration: course?.duration ?? '',
      price: course?.price ?? '',
      badge: course?.badge ?? '',
      standard: course?.standard ?? '',
      image: course?.image ?? '',
      description: course?.description ?? '',
      longDescription: course?.longDescription ?? undefined,
      includes: course?.includes ?? [],
      requirements: course?.requirements ?? [],
      scope: course?.scope ?? [],
      metaTitle: course?.metaTitle ?? '',
      metaDescription: course?.metaDescription ?? '',
    })
    startTransition(() => setSelectedImage({ file: null, previewUrl: null }))
  }, [course, form])

  const [selectedImage, setSelectedImage] = useState<{
    file: File | null
    previewUrl: string | null
  }>({ file: null, previewUrl: null })

  const imageValue = useWatch({ control: form.control, name: 'image' })

  const imageUploadMutation = useMutation({
    mutationFn: uploadImage,
    onError: handleServerError,
  })

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

  const previewUrl = selectedImage.previewUrl
    ? selectedImage.previewUrl
    : imageValue
      ? imageValue.startsWith('http')
        ? imageValue
        : `${apiOrigin}/${imageValue.replace(/^\/+/, '')}`
      : null

  return (
    <Card className='border-border/70 shadow-sm'>
      <CardHeader className='border-b border-border/70 bg-muted/20 px-5 py-4'>
        <div className='flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between'>
          <div className='space-y-1'>
            <CardTitle>
              {course ? 'Eğitimi düzenle' : 'Yeni eğitim oluştur'}
            </CardTitle>
            <CardDescription>
              Kurs kartı, detay sayfası ve fiyat/içerik blokları bu formdan
              yönetilir.
            </CardDescription>
          </div>
          <Button
            type='button'
            variant='ghost'
            size='sm'
            className='h-8 rounded-lg px-2 text-muted-foreground sm:shrink-0'
            onClick={onCancel}
          >
            <ArrowLeft />
            Listeye dön
          </Button>
        </div>
      </CardHeader>
      <CardContent className='p-4 md:p-5'>
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(async (values) => {
              let nextImage = values.image ?? ''

              if (selectedImage.file) {
                const uploadResult = await imageUploadMutation.mutateAsync(
                  selectedImage.file
                )
                nextImage = uploadResult.path
                form.setValue('image', nextImage, {
                  shouldDirty: true,
                  shouldTouch: true,
                })
              }

              await onSubmit({ ...values, image: nextImage })

              if (selectedImage.file) {
                toast.success('Görsel ve eğitim başarıyla kaydedildi.')
                setSelectedImage({ file: null, previewUrl: null })
              }
            })}
            className='space-y-4'
          >
            {/* Kapak görseli + Temel bilgiler */}
            <div className='grid gap-4 xl:grid-cols-[340px_minmax(0,1fr)]'>
              <FormField
                control={form.control}
                name='image'
                render={({ field }) => (
                  <FormItem>
                    <FormControl>
                      <ImageUploadField
                        value={field.value ?? ''}
                        onChange={field.onChange}
                        previewUrl={previewUrl}
                        pendingFileName={selectedImage.file?.name ?? null}
                        isSaving={isPending || imageUploadMutation.isPending}
                        onFileSelect={(file) => {
                          setSelectedImage((current) => {
                            if (current.previewUrl)
                              URL.revokeObjectURL(current.previewUrl)
                            return {
                              file,
                              previewUrl: URL.createObjectURL(file),
                            }
                          })
                        }}
                        onClearSelection={() => {
                          setSelectedImage((current) => {
                            if (current.previewUrl)
                              URL.revokeObjectURL(current.previewUrl)
                            return { file: null, previewUrl: null }
                          })
                        }}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <div className='rounded-3xl border border-border/70 bg-card p-4 shadow-sm'>
                <div className='mb-3 border-b border-border/70 pb-3'>
                  <p className='text-sm font-semibold'>Temel bilgiler</p>
                  <p className='text-sm text-muted-foreground'>
                    Eğitim kimliği ve kategori bağlantısı
                  </p>
                </div>
              <div className='space-y-3'>
                <div className='grid gap-3 md:grid-cols-2'>
                  <FormField
                    control={form.control}
                    name='categoryId'
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Kategori</FormLabel>
                        <Select
                          value={String(field.value || '')}
                          onValueChange={(value) =>
                            field.onChange(Number(value))
                          }
                        >
                          <FormControl>
                            <SelectTrigger className='w-full'>
                              <SelectValue placeholder='Kategori seçiniz' />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            {categories.map((category) => (
                              <SelectItem
                                key={category.id}
                                value={String(category.id)}
                              >
                                {category.name}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name='sub'
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Alt başlık</FormLabel>
                        <FormControl>
                          <Input {...field} placeholder='STCW II/1' />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <div className='grid gap-3 md:grid-cols-2'>
                  <FormField
                    control={form.control}
                    name='title'
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Başlık</FormLabel>
                        <FormControl>
                          <Input
                            {...field}
                            placeholder='Örnek: Yağcı (Temel)'
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name='slug'
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Slug</FormLabel>
                        <FormControl>
                          <Input {...field} placeholder='yagci-temel' />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              </div>
            </div>
            </div>

            {/* Kurs özellikleri */}
            <div className='rounded-3xl border border-border/70 bg-card p-4 shadow-sm'>
              <div className='mb-3 border-b border-border/70 pb-3'>
                <p className='text-sm font-semibold'>Kurs özellikleri</p>
                <p className='text-sm text-muted-foreground'>
                  Süre, fiyat ve rozet bilgileri
                </p>
              </div>
              <div className='space-y-3'>
                <div className='grid gap-3 md:grid-cols-3'>
                  <FormField
                    control={form.control}
                    name='duration'
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Süre</FormLabel>
                        <FormControl>
                          <Input {...field} placeholder='5 Gün' />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name='price'
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Fiyat</FormLabel>
                        <FormControl>
                          <Input {...field} placeholder='15.000 TL' />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name='badge'
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Rozet</FormLabel>
                        <Select
                          value={field.value || ''}
                          onValueChange={(value) =>
                            field.onChange(value === '_none' ? '' : value)
                          }
                        >
                          <FormControl>
                            <SelectTrigger className='w-full'>
                              <SelectValue placeholder='Rozet seçiniz' />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            <SelectItem value='_none'>Yok</SelectItem>
                            <SelectItem value='popular'>Popüler</SelectItem>
                            <SelectItem value='most_preferred'>
                              En Çok Tercih Edilen
                            </SelectItem>
                            <SelectItem value='new'>Yeni</SelectItem>
                            <SelectItem value='recommended'>
                              Önerilen
                            </SelectItem>
                            <SelectItem value='limited'>
                              Sınırlı Kontenjan
                            </SelectItem>
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <FormField
                  control={form.control}
                  name='standard'
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Standart</FormLabel>
                      <FormControl>
                        <Input {...field} placeholder='STCW / IMO Uyumlu' />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </div>

            {/* Kısa açıklama */}
            <div className='rounded-3xl border border-border/70 bg-card p-4 shadow-sm'>
              <div className='mb-3 border-b border-border/70 pb-3'>
                <p className='text-sm font-semibold'>Kısa açıklama</p>
                <p className='text-sm text-muted-foreground'>
                  Kart ve liste görünümlerinde kullanılacak özet metin
                </p>
              </div>
              <FormField
                control={form.control}
                name='description'
                render={({ field }) => (
                  <FormItem>
                    <FormControl>
                      <RichTextEditor
                        value={field.value ?? ''}
                        onChange={field.onChange}
                        placeholder='Kart ve liste açıklaması...'
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            {/* Detay içerik editörü */}
            <div className='rounded-3xl border border-border/70 bg-card p-4 shadow-sm'>
              <div className='mb-3 border-b border-border/70 pb-3'>
                <p className='text-sm font-semibold'>Detay içerik editörü</p>
                <p className='text-sm text-muted-foreground'>
                  Eğitim detay sayfasındaki ana içerik alanı
                </p>
              </div>
              <FormField
                control={form.control}
                name='longDescription'
                render={({ field }) => (
                  <FormItem>
                    <FormControl>
                      <RichTextEditor
                        value={field.value ?? ''}
                        onChange={field.onChange}
                        placeholder='Eğitim için SEO uyumlu giriş metni, başlıklar ve açıklamalar ekleyin.'
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            {/* Liste alanları */}
            <div className='rounded-3xl border border-border/70 bg-card p-4 shadow-sm'>
              <div className='mb-3 border-b border-border/70 pb-3'>
                <p className='text-sm font-semibold'>Liste alanları</p>
                <p className='text-sm text-muted-foreground'>
                  Kısa maddeler halinde ek içerikler
                </p>
              </div>
              <div className='grid gap-3 xl:grid-cols-3'>
                <FormField
                  control={form.control}
                  name='includes'
                  render={({ field }) => (
                    <FormItem>
                      <FormControl>
                        <BulletListField
                          label='Fiyata dahil olanlar'
                          description='Eklediğiniz her madde alt tarafta otomatik olarak işaretli liste şeklinde görünür.'
                          value={field.value ?? []}
                          onChange={field.onChange}
                          placeholder='Örnek: Basılı eğitim dokümanı'
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name='requirements'
                  render={({ field }) => (
                    <FormItem>
                      <FormControl>
                        <BulletListField
                          label='Gereksinimler'
                          description='Katılımcı şartlarını veya ön hazırlıkları madde madde ekleyin.'
                          value={field.value ?? []}
                          onChange={field.onChange}
                          placeholder='Örnek: Temel denizcilik belgesi'
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name='scope'
                  render={({ field }) => (
                    <FormItem>
                      <FormControl>
                        <BulletListField
                          label='Kapsam'
                          description='Eğitim kapsamındaki ana konu başlıklarını kısa maddeler halinde girin.'
                          value={field.value ?? []}
                          onChange={field.onChange}
                          placeholder='Örnek: Gemide güvenlik prosedürleri'
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </div>

            {/* SEO */}
            <div className='rounded-3xl border border-border/70 bg-card p-4 shadow-sm'>
              <div className='mb-3 border-b border-border/70 pb-3'>
                <p className='text-sm font-semibold'>SEO alanları</p>
                <p className='text-sm text-muted-foreground'>
                  Arama sonuçlarında görünecek başlık ve açıklama
                </p>
              </div>
              <div className='space-y-3'>
                <FormField
                  control={form.control}
                  name='metaTitle'
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Meta title</FormLabel>
                      <FormControl>
                        <Input
                          {...field}
                          value={field.value ?? ''}
                          maxLength={metaTitleMaxLength}
                          placeholder='SEO başlığı'
                        />
                      </FormControl>
                      <FormDescription>
                        Arama sonuçlarında ideal görünüm için{' '}
                        {metaTitleMinLength}-{metaTitleMaxLength} karakter
                        hedefleyin.
                      </FormDescription>
                      <SeoCharacterHint
                        length={(field.value ?? '').trim().length}
                        min={metaTitleMinLength}
                        max={metaTitleMaxLength}
                      />
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name='metaDescription'
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Meta description</FormLabel>
                      <FormControl>
                        <Textarea
                          {...field}
                          value={field.value ?? ''}
                          maxLength={metaDescriptionMaxLength}
                          rows={4}
                          placeholder='SEO açıklaması'
                        />
                      </FormControl>
                      <FormDescription>
                        {metaDescriptionMinLength}-{metaDescriptionMaxLength}{' '}
                        karakter aralığı tıklanma oranı için genelde daha
                        uygundur.
                      </FormDescription>
                      <SeoCharacterHint
                        length={(field.value ?? '').trim().length}
                        min={metaDescriptionMinLength}
                        max={metaDescriptionMaxLength}
                      />
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </div>

            <div className='flex flex-wrap justify-end gap-3 border-t border-border/70 pt-4'>
              <Button type='button' variant='outline' onClick={onCancel}>
                Vazgeç
              </Button>
              <Button type='submit' className='rounded-xl' disabled={isPending}>
                {isPending && <Loader2 className='animate-spin' />}
                {course ? 'Kaydet' : 'Eğitim oluştur'}
              </Button>
            </div>
          </form>
        </Form>
      </CardContent>
    </Card>
  )
}
