import { startTransition, useDeferredValue, useEffect, useState } from 'react'
import { z } from 'zod'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import {
  ArrowLeft,
  ChevronLeft,
  ChevronRight,
  Loader2,
  PencilLine,
  Plus,
  RefreshCw,
  Search,
  Trash2,
} from 'lucide-react'
import { toast } from 'sonner'
import {
  createGuideCard,
  deleteGuideCard,
  fetchGuideCards,
  updateGuideCard,
} from '@/lib/api/guide-cards'
import type { AdminGuideCardRecord } from '@/lib/api/types'
import { handleServerError } from '@/lib/handle-server-error'
import { getPageNumbers } from '@/lib/utils'
import { Badge } from '@/components/ui/badge'
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 {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { Textarea } from '@/components/ui/textarea'
import { ConfirmDialog } from '@/components/confirm-dialog'
import { Main } from '@/components/layout/main'
import { GuideCardsHeader } from './components/guide-cards-header'

const perPage = 20

const iconOptions = [
  { value: 'anchor', label: 'Anchor' },
  { value: 'compass', label: 'Compass' },
  { value: 'shield', label: 'Shield' },
  { value: 'briefcase', label: 'Briefcase' },
  { value: 'book-open', label: 'Book Open' },
  { value: 'graduation-cap', label: 'Graduation Cap' },
  { value: 'award', label: 'Award' },
  { value: 'check-circle', label: 'Check Circle' },
  { value: 'star', label: 'Star' },
  { value: 'heart', label: 'Heart' },
  { value: 'users', label: 'Users' },
  { value: 'map-pin', label: 'Map Pin' },
]

const guideCardFormSchema = z.object({
  title: z.string().min(1, 'Başlık zorunludur'),
  description: z.string().min(1, 'Açıklama zorunludur'),
  icon: z.string().min(1, 'İkon seçiniz'),
  order: z.coerce.number().min(0).default(0),
  isActive: z.boolean().default(true),
})

type GuideCardFormInput = z.input<typeof guideCardFormSchema>
type GuideCardFormValues = z.output<typeof guideCardFormSchema>

function GuideCardEditorPage({
  guideCard,
  isPending,
  onCancel,
  onSubmit,
}: {
  guideCard: AdminGuideCardRecord | null
  isPending: boolean
  onCancel: () => void
  onSubmit: (values: GuideCardFormValues) => Promise<void>
}) {
  const form = useForm<GuideCardFormInput, undefined, GuideCardFormValues>({
    resolver: zodResolver(guideCardFormSchema),
    defaultValues: {
      title: guideCard?.title ?? '',
      description: guideCard?.description ?? '',
      icon: guideCard?.icon ?? '',
      order: guideCard?.orderIndex ?? 0,
      isActive: guideCard?.isActive ?? true,
    } satisfies GuideCardFormInput,
  })

  useEffect(() => {
    form.reset({
      title: guideCard?.title ?? '',
      description: guideCard?.description ?? '',
      icon: guideCard?.icon ?? '',
      order: guideCard?.orderIndex ?? 0,
      isActive: guideCard?.isActive ?? true,
    })
  }, [form, guideCard])

  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>
              {guideCard ? 'Rehber kartı düzenle' : 'Yeni rehber kartı'}
            </CardTitle>
            <CardDescription>
              Eğitim rehberi sayfasındaki bilgi kartları.
            </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'>Kart başlığı, ikon ve görünürlük ayarları</p>
              </div>
              <div className='space-y-3'>
                <FormField control={form.control} name='title' render={({ field }) => (
                  <FormItem><FormLabel>Başlık</FormLabel><FormControl><Input {...field} placeholder='Kart başlığı' /></FormControl><FormMessage /></FormItem>
                )} />
                <FormField control={form.control} name='description' render={({ field }) => (
                  <FormItem><FormLabel>Açıklama</FormLabel><FormControl><Textarea {...field} rows={3} placeholder='Kart açıklaması...' /></FormControl><FormMessage /></FormItem>
                )} />
                <div className='grid gap-3 md:grid-cols-2'>
                  <FormField control={form.control} name='icon' render={({ field }) => (
                    <FormItem>
                      <FormLabel>İkon</FormLabel>
                      <Select value={field.value} onValueChange={field.onChange}>
                        <FormControl><SelectTrigger className='w-full'><SelectValue placeholder='İkon seçiniz' /></SelectTrigger></FormControl>
                        <SelectContent>{iconOptions.map((opt) => (<SelectItem key={opt.value} value={opt.value}>{opt.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>
                  )} />
                </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'>Buton & Görünürlük</p>
                <p className='text-sm text-muted-foreground'>Kart buton ayarları ve aktiflik durumu</p>
              </div>
              <div className='space-y-3'>
                <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'>Kart sitede görünür olur.</p></div>
                    <FormControl><Switch checked={field.value} onCheckedChange={field.onChange} /></FormControl>
                  </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' />}
                {guideCard ? 'Kaydet' : 'Kart oluştur'}
              </Button>
            </div>
          </form>
        </Form>
      </CardContent>
    </Card>
  )
}

export function GuideCardsPage() {
  const queryClient = useQueryClient()
  const [page, setPage] = useState(1)
  const [search, setSearch] = useState('')
  const deferredSearch = useDeferredValue(search)
  const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'inactive'>('all')
  const [editorOpen, setEditorOpen] = useState(false)
  const [activeCard, setActiveCard] = useState<AdminGuideCardRecord | null>(null)
  const [cardToDelete, setCardToDelete] = useState<AdminGuideCardRecord | null>(null)

  const cardsQuery = useQuery({
    queryKey: ['guide-cards', page, deferredSearch, statusFilter],
    queryFn: () => fetchGuideCards({ page, perPage, search: deferredSearch || undefined, is_active: statusFilter === 'active' ? true : statusFilter === 'inactive' ? false : undefined }),
  })

  const upsertMutation = useMutation({
    mutationFn: async (values: GuideCardFormValues) => {
      const payload = { title: values.title, description: values.description, icon: values.icon, order_index: values.order, is_active: values.isActive }
      if (activeCard) return updateGuideCard(activeCard.id, payload)
      return createGuideCard(payload)
    },
    onSuccess: async () => { toast.success('Rehber kartı kaydedildi'); await queryClient.invalidateQueries({ queryKey: ['guide-cards'] }); setEditorOpen(false); setActiveCard(null) },
    onError: handleServerError,
  })

  const deleteMutation = useMutation({
    mutationFn: async (id: number | string) => deleteGuideCard(id),
    onSuccess: async () => { toast.success('Rehber kartı silindi'); await queryClient.invalidateQueries({ queryKey: ['guide-cards'] }); setCardToDelete(null) },
    onError: handleServerError,
  })

  const pageNumbers = getPageNumbers(page, cardsQuery.data?.meta.lastPage ?? 1)

  return (
    <>
      <GuideCardsHeader />
      <Main className='space-y-6'>
        {editorOpen ? (
          <GuideCardEditorPage guideCard={activeCard} isPending={upsertMutation.isPending} onCancel={() => { setEditorOpen(false); setActiveCard(null) }} onSubmit={async (values) => { await upsertMutation.mutateAsync(values) }} />
        ) : (
          <Card>
            <CardHeader className='gap-4'>
              <div className='flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between'>
                <div><CardTitle>Rehber Kartları</CardTitle><CardDescription>Eğitim rehberi sayfasındaki bilgi kartları.</CardDescription></div>
                <div className='flex flex-wrap gap-2'>
                  <Button variant='outline' className='rounded-xl' onClick={() => cardsQuery.refetch()}><RefreshCw className={cardsQuery.isFetching ? 'animate-spin' : ''} />Yenile</Button>
                  <Button className='rounded-xl' onClick={() => { setActiveCard(null); setEditorOpen(true) }}><Plus />Ekle</Button>
                </div>
              </div>
              <div className='flex flex-col gap-3 rounded-2xl border border-dashed border-border/70 bg-muted/20 p-4 sm:flex-row sm:items-end'>
                <div className='relative max-w-sm flex-1'>
                  <Search className='absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground' />
                  <Input placeholder='Başlık veya açıklamaya göre ara...' className='pl-9' value={search} onChange={(event) => { setSearch(event.target.value); setPage(1) }} />
                </div>
                <div className='w-full sm:w-[180px]'>
                  <Select value={statusFilter} onValueChange={(value: 'all' | 'active' | 'inactive') => { setStatusFilter(value); setPage(1) }}>
                    <SelectTrigger className='w-full'><SelectValue placeholder='Durum' /></SelectTrigger>
                    <SelectContent><SelectItem value='all'>Tümü</SelectItem><SelectItem value='active'>Aktif</SelectItem><SelectItem value='inactive'>Pasif</SelectItem></SelectContent>
                  </Select>
                </div>
              </div>
            </CardHeader>
            <CardContent className='space-y-4'>
              <div className='rounded-2xl border border-border/70'>
                <Table>
                  <TableHeader><TableRow><TableHead className='px-4'>Başlık</TableHead><TableHead>İkon</TableHead><TableHead>Sıra</TableHead><TableHead>Durum</TableHead><TableHead className='w-[180px] text-right'>İşlemler</TableHead></TableRow></TableHeader>
                  <TableBody>
                    {cardsQuery.isLoading ? (
                      <TableRow><TableCell colSpan={5} className='h-28 text-center text-muted-foreground'><Loader2 className='mx-auto mb-2 size-5 animate-spin' />Yükleniyor...</TableCell></TableRow>
                    ) : cardsQuery.data?.items.length ? (
                      cardsQuery.data.items.map((item) => (
                        <TableRow key={item.id}>
                          <TableCell className='px-4 py-4'><p className='font-medium'>{item.title}</p><p className='mt-0.5 max-w-[300px] truncate text-xs text-muted-foreground'>{item.description}</p></TableCell>
                          <TableCell><Badge variant='outline' className='rounded-full'>{item.icon}</Badge></TableCell>
                          <TableCell>{item.orderIndex}</TableCell>
                          <TableCell><Badge variant={item.isActive ? 'default' : 'secondary'} className='rounded-full'>{item.isActive ? 'Aktif' : 'Pasif'}</Badge></TableCell>
                          <TableCell>
                            <div className='flex justify-end gap-2'>
                              <Button variant='outline' size='sm' className='rounded-xl' onClick={() => { setActiveCard(item); setEditorOpen(true) }}><PencilLine />Düzenle</Button>
                              <Button variant='destructive' size='sm' className='rounded-xl' onClick={() => setCardToDelete(item)}><Trash2 />Sil</Button>
                            </div>
                          </TableCell>
                        </TableRow>
                      ))
                    ) : (
                      <TableRow><TableCell colSpan={5} className='h-28 text-center text-muted-foreground'>Rehber kartı bulunamadı.</TableCell></TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
              <div className='flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between'>
                <p className='text-sm text-muted-foreground'>Toplam {cardsQuery.data?.meta.total ?? 0} kayıt. Sayfa {page} / {cardsQuery.data?.meta.lastPage ?? 1}</p>
                <div className='flex flex-wrap items-center gap-2'>
                  <Button variant='outline' size='sm' onClick={() => startTransition(() => setPage((c) => Math.max(1, c - 1)))} disabled={page === 1}><ChevronLeft /></Button>
                  {pageNumbers.map((item, index) => item === '...' ? (<span key={`${item}-${index}`} className='px-2 text-sm text-muted-foreground'>...</span>) : (<Button key={item} size='sm' variant={item === page ? 'default' : 'outline'} onClick={() => startTransition(() => setPage(Number(item)))}>{item}</Button>))}
                  <Button variant='outline' size='sm' onClick={() => startTransition(() => setPage((c) => Math.min(cardsQuery.data?.meta.lastPage ?? 1, c + 1)))} disabled={page === (cardsQuery.data?.meta.lastPage ?? 1)}><ChevronRight /></Button>
                </div>
              </div>
            </CardContent>
          </Card>
        )}
      </Main>
      <ConfirmDialog open={!!cardToDelete} onOpenChange={(open) => { if (!open) setCardToDelete(null) }} title='Kartı silmek istediğinize emin misiniz?' desc={`"${cardToDelete?.title ?? ''}" kalıcı olarak silinecek.`} confirmText='Evet, sil' cancelBtnText='İptal' destructive isLoading={deleteMutation.isPending} handleConfirm={() => { if (cardToDelete) deleteMutation.mutate(cardToDelete.id) }} />
    </>
  )
}
