import { startTransition, useEffect, useState } from 'react'
import { z } from 'zod'
import { useForm, useWatch } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { useMutation } from '@tanstack/react-query'
import { ArrowLeft, Loader2 } from 'lucide-react'
import { toast } from 'sonner'
import { apiOrigin } from '@/lib/api/client'
import type { AdminAnnouncementRecord } from '@/lib/api/types'
import { uploadImage } from '@/lib/api/upload'
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,
  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 { Switch } from '@/components/ui/switch'
import { Textarea } from '@/components/ui/textarea'
import { ImageUploadField } from '@/components/image-upload-field'
import { RichTextEditor } from '@/components/rich-text-editor'

export const announcementFormSchema = z.object({
  title: z.string().min(2, 'Başlık en az 2 karakter olmalıdır'),
  slug: z.string().optional(),
  category: z.string().min(1, 'Kategori seçiniz'),
  excerpt: z.string().min(1, 'Özet zorunludur'),
  content: z.string().min(1, 'İçerik zorunludur'),
  image: z.string().optional(),
  isFeatured: z.boolean().default(false),
  metaTitle: z.string().max(60).optional(),
  metaDescription: z.string().max(160).optional(),
  publishedAt: z.string().optional(),
})

export type AnnouncementFormInput = z.input<typeof announcementFormSchema>
export type AnnouncementFormValues = z.output<typeof announcementFormSchema>

export function AnnouncementForm({
  announcement,
  isPending,
  onCancel,
  onSubmit,
}: {
  announcement: AdminAnnouncementRecord | null
  isPending: boolean
  onCancel: () => void
  onSubmit: (values: AnnouncementFormValues) => Promise<void>
}) {
  const form = useForm<
    AnnouncementFormInput,
    undefined,
    AnnouncementFormValues
  >({
    resolver: zodResolver(announcementFormSchema),
    defaultValues: {
      title: announcement?.title ?? '',
      slug: announcement?.slug ?? '',
      category: announcement?.category ?? 'announcement',
      excerpt: announcement?.excerpt ?? '',
      content: announcement?.content ?? '',
      image: announcement?.image ?? '',
      isFeatured: announcement?.isFeatured ?? false,
      metaTitle: announcement?.metaTitle ?? '',
      metaDescription: announcement?.metaDescription ?? '',
      publishedAt: announcement?.publishedAt
        ? announcement.publishedAt.slice(0, 16)
        : '',
    } satisfies AnnouncementFormInput,
  })

  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(() => {
    form.reset({
      title: announcement?.title ?? '',
      slug: announcement?.slug ?? '',
      category: announcement?.category ?? 'announcement',
      excerpt: announcement?.excerpt ?? '',
      content: announcement?.content ?? '',
      image: announcement?.image ?? '',
      isFeatured: announcement?.isFeatured ?? false,
      metaTitle: announcement?.metaTitle ?? '',
      metaDescription: announcement?.metaDescription ?? '',
      publishedAt: announcement?.publishedAt
        ? announcement.publishedAt.slice(0, 16)
        : '',
    })
    startTransition(() => setSelectedImage({ file: null, previewUrl: null }))
  }, [form, announcement])

  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>
              {announcement ? 'Duyuruyu düzenle' : 'Yeni duyuru oluştur'}
            </CardTitle>
            <CardDescription>
              Duyuru, haber ve etkinlik içerikleri yönetimi.
            </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 duyuru başarıyla kaydedildi.')
                setSelectedImage({ file: null, previewUrl: null })
              }
            })}
            className='space-y-4'
          >
            <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 flex items-center justify-between gap-3 border-b border-border/70 pb-3'>
                  <div>
                    <p className='text-sm font-semibold'>Temel bilgiler</p>
                    <p className='text-sm text-muted-foreground'>
                      Duyuru kimliği ve görünürlük ayarları
                    </p>
                  </div>
                </div>

                <div className='space-y-3'>
                  <FormField
                    control={form.control}
                    name='title'
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Başlık</FormLabel>
                        <FormControl>
                          <Input {...field} placeholder='Duyuru başlığı' />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name='slug'
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Slug</FormLabel>
                        <FormControl>
                          <Input
                            {...field}
                            placeholder='Otomatik oluşturulur'
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <div className='grid gap-3 md:grid-cols-2'>
                    <FormField
                      control={form.control}
                      name='category'
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Kategori</FormLabel>
                          <Select
                            value={field.value}
                            onValueChange={field.onChange}
                          >
                            <FormControl>
                              <SelectTrigger className='w-full'>
                                <SelectValue placeholder='Kategori seçiniz' />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              <SelectItem value='announcement'>
                                Duyuru
                              </SelectItem>
                              <SelectItem value='news'>Haber</SelectItem>
                              <SelectItem value='event'>Etkinlik</SelectItem>
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name='publishedAt'
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Yayın tarihi</FormLabel>
                          <FormControl>
                            <Input {...field} type='datetime-local' />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>
                  <FormField
                    control={form.control}
                    name='isFeatured'
                    render={({ field }) => (
                      <FormItem className='flex min-h-full items-center justify-between rounded-2xl border border-border/70 px-4 py-2.5'>
                        <div>
                          <FormLabel>Ana sayfada manşet yap</FormLabel>
                          <p className='text-sm text-muted-foreground'>
                            Bu duyuru ana sayfada öne çıkarılır.
                          </p>
                        </div>
                        <FormControl>
                          <Switch
                            checked={field.value}
                            onCheckedChange={field.onChange}
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />
                </div>
              </div>
            </div>

            <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'>Özet</p>
                <p className='text-sm text-muted-foreground'>
                  Liste ve kart görünümlerinde kullanılacak kısa açıklama
                </p>
              </div>
              <FormField
                control={form.control}
                name='excerpt'
                render={({ field }) => (
                  <FormItem>
                    <FormControl>
                      <Textarea
                        {...field}
                        rows={3}
                        placeholder='Kısa açıklama...'
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <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'>İçerik editörü</p>
                <p className='text-sm text-muted-foreground'>
                  Duyuru detay sayfasındaki ana içerik alanı
                </p>
              </div>
              <FormField
                control={form.control}
                name='content'
                render={({ field }) => (
                  <FormItem>
                    <FormControl>
                      <RichTextEditor
                        value={field.value ?? ''}
                        onChange={field.onChange}
                        placeholder='Duyuru içeriğini yazın...'
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <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={60}
                          placeholder='SEO başlığı (maks 60 karakter)'
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name='metaDescription'
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Meta description</FormLabel>
                      <FormControl>
                        <Textarea
                          {...field}
                          value={field.value ?? ''}
                          maxLength={160}
                          rows={3}
                          placeholder='SEO açıklaması (maks 160 karakter)'
                        />
                      </FormControl>
                      <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 || imageUploadMutation.isPending}
              >
                {(isPending || imageUploadMutation.isPending) && (
                  <Loader2 className='animate-spin' />
                )}
                {announcement ? 'Kaydet' : 'Duyuru oluştur'}
              </Button>
            </div>
          </form>
        </Form>
      </CardContent>
    </Card>
  )
}
