import { useEffect } from 'react'
import { z } from 'zod'
import { useForm, useWatch } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { ArrowLeft, Loader2 } from 'lucide-react'
import type { AdminPageRecord } from '@/lib/api/types'
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 { Switch } from '@/components/ui/switch'
import { Textarea } from '@/components/ui/textarea'
import { slugify } from '../helpers'

export const pageFormSchema = z.object({
  title: z.string().min(1, 'Başlık zorunludur'),
  slug: z.string().min(1, 'Slug zorunludur'),
  metaTitle: z.string().optional().default(''),
  metaDescription: z.string().optional().default(''),
  isActive: z.boolean().default(true),
})

export type PageFormInput = z.input<typeof pageFormSchema>
export type PageFormValues = z.output<typeof pageFormSchema>

export function PageForm({
  page: pageRecord,
  isEdit,
  isPending,
  onCancel,
  onSubmit,
}: {
  page: AdminPageRecord | null
  isEdit: boolean
  isPending: boolean
  onCancel: () => void
  onSubmit: (values: PageFormValues) => Promise<void>
}) {
  const form = useForm<PageFormInput, undefined, PageFormValues>({
    resolver: zodResolver(pageFormSchema),
    defaultValues: {
      title: pageRecord?.title ?? '',
      slug: pageRecord?.slug ?? '',
      metaTitle: pageRecord?.metaTitle ?? '',
      metaDescription: pageRecord?.metaDescription ?? '',
      isActive: pageRecord?.isActive ?? true,
    } satisfies PageFormInput,
  })

  useEffect(() => {
    form.reset({
      title: pageRecord?.title ?? '',
      slug: pageRecord?.slug ?? '',
      metaTitle: pageRecord?.metaTitle ?? '',
      metaDescription: pageRecord?.metaDescription ?? '',
      isActive: pageRecord?.isActive ?? true,
    })
  }, [form, pageRecord])

  const titleValue = useWatch({ control: form.control, name: 'title' })

  useEffect(() => {
    const nextSlug = slugify(titleValue ?? '')
    if (form.getValues('slug') !== nextSlug) {
      form.setValue('slug', nextSlug, {
        shouldDirty: true,
        shouldTouch: true,
      })
    }
  }, [form, titleValue])

  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>
              {isEdit ? 'Sayfayı düzenle' : 'Yeni sayfa oluştur'}
            </CardTitle>
            <CardDescription>
              {isEdit
                ? 'Sayfa bilgilerini güncelleyin. Blokları aşağıdan yönetebilirsiniz.'
                : 'Sayfa bilgilerini girin. Blokları sayfa oluşturduktan sonra ekleyebilirsiniz.'}
            </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) => {
              await onSubmit(values)
            })}
            className='space-y-4'
          >
            <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'>
                  Sayfa başlığı, slug ve aktiflik durumu
                </p>
              </div>
              <div className='space-y-3'>
                <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='Sayfa başlığı' />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name='slug'
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Slug</FormLabel>
                        <FormControl>
                          <Input
                            {...field}
                            placeholder='sayfa-url-yolu'
                            readOnly
                            className='cursor-not-allowed bg-muted/50 text-muted-foreground'
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <FormField
                  control={form.control}
                  name='isActive'
                  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>Aktif</FormLabel>
                        <p className='text-sm text-muted-foreground'>
                          Sayfa sitede görünür olur.
                        </p>
                      </div>
                      <FormControl>
                        <Switch
                          checked={field.value}
                          onCheckedChange={field.onChange}
                        />
                      </FormControl>
                    </FormItem>
                  )}
                />
              </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'>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 başlık (opsiyonel)</FormLabel>
                      <FormControl>
                        <Input
                          {...field}
                          maxLength={60}
                          placeholder='SEO başlığı (maks 60 karakter)'
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name='metaDescription'
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Meta açıklama (opsiyonel)</FormLabel>
                      <FormControl>
                        <Textarea
                          {...field}
                          rows={3}
                          maxLength={160}
                          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}>
                {isPending && <Loader2 className='animate-spin' />}
                {isEdit ? 'Kaydet' : 'Sayfa oluştur'}
              </Button>
            </div>
          </form>
        </Form>
      </CardContent>
    </Card>
  )
}
