import { useEffect } from 'react'
import { z } from 'zod'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { ArrowLeft, Loader2 } from 'lucide-react'
import type { AdminFaqRecord } 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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
import { RichTextEditor } from '@/components/rich-text-editor'

const categoryLabels: Record<string, string> = {
  egitimler: 'Eğitimler',
  kayit: 'Kayıt',
  iletisim: 'İletişim',
}

export const faqFormSchema = z.object({
  question: z.string().min(1, 'Soru zorunludur'),
  answer: z.string().min(1, 'Cevap zorunludur'),
  category: z.string().min(1, 'Kategori seçiniz'),
  order: z.coerce.number().min(0).default(0),
  isActive: z.boolean().default(true),
})

export type FaqFormInput = z.input<typeof faqFormSchema>
export type FaqFormValues = z.output<typeof faqFormSchema>

export function FaqForm({
  faq,
  isPending,
  onCancel,
  onSubmit,
}: {
  faq: AdminFaqRecord | null
  isPending: boolean
  onCancel: () => void
  onSubmit: (values: FaqFormValues) => Promise<void>
}) {
  const form = useForm<FaqFormInput, undefined, FaqFormValues>({
    resolver: zodResolver(faqFormSchema),
    defaultValues: {
      question: faq?.question ?? '',
      answer: faq?.answer ?? '',
      category: faq?.category ?? 'egitimler',
      order: faq?.orderIndex ?? 0,
      isActive: faq?.isActive ?? true,
    } satisfies FaqFormInput,
  })

  useEffect(() => {
    form.reset({
      question: faq?.question ?? '',
      answer: faq?.answer ?? '',
      category: faq?.category ?? 'egitimler',
      order: faq?.orderIndex ?? 0,
      isActive: faq?.isActive ?? true,
    })
  }, [form, faq])

  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>{faq ? 'SSS düzenle' : 'Yeni SSS oluştur'}</CardTitle>
            <CardDescription>Sık sorulan sorular ve cevapları.</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'>
                  Soru metni, kategori ve görünürlük ayarları
                </p>
              </div>
              <div className='space-y-3'>
                <FormField
                  control={form.control}
                  name='question'
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Soru</FormLabel>
                      <FormControl>
                        <Input {...field} placeholder='Soru metni...' />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <div className='grid gap-3 md:grid-cols-3'>
                  <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 />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            {Object.entries(categoryLabels).map(
                              ([value, label]) => (
                                <SelectItem key={value} value={value}>
                                  {label}
                                </SelectItem>
                              )
                            )}
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name='order'
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Sıralama</FormLabel>
                        <FormControl>
                          <Input
                            name={field.name}
                            ref={field.ref}
                            onBlur={field.onBlur}
                            disabled={field.disabled}
                            type='number'
                            min={0}
                            value={String(field.value ?? 0)}
                            onChange={(event) =>
                              field.onChange(event.target.value)
                            }
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <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'>
                            Sitede görünü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'>Cevap</p>
                <p className='text-sm text-muted-foreground'>
                  Sorunun detaylı cevabı (zengin metin editörü)
                </p>
              </div>
              <FormField
                control={form.control}
                name='answer'
                render={({ field }) => (
                  <FormItem>
                    <FormControl>
                      <RichTextEditor
                        value={field.value ?? ''}
                        onChange={field.onChange}
                        placeholder='Cevap metnini yazın...'
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </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' />}
                {faq ? 'Kaydet' : 'SSS oluştur'}
              </Button>
            </div>
          </form>
        </Form>
      </CardContent>
    </Card>
  )
}
