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,
  FilterX,
  Loader2,
  PencilLine,
  RefreshCw,
  Search,
  Trash2,
} from 'lucide-react'
import { toast } from 'sonner'
import { deleteComment, fetchComments, updateComment } from '@/lib/api/comments'
import type { AdminCommentRecord } 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 {
  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 { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { ConfirmDialog } from '@/components/confirm-dialog'
import { Main } from '@/components/layout/main'
import { CommentsHeader } from './components/comments-header'

const perPage = 20

const commentFormSchema = z.object({
  isApproved: z.boolean().default(false),
  adminReply: z.string().optional(),
})

type CommentFormInput = z.input<typeof commentFormSchema>
type CommentFormValues = z.output<typeof commentFormSchema>

function CommentEditorPage({
  comment,
  isPending,
  onCancel,
  onSubmit,
}: {
  comment: AdminCommentRecord
  isPending: boolean
  onCancel: () => void
  onSubmit: (values: CommentFormValues) => Promise<void>
}) {
  const form = useForm<CommentFormInput, undefined, CommentFormValues>({
    resolver: zodResolver(commentFormSchema),
    defaultValues: {
      isApproved: comment.isApproved,
      adminReply: comment.adminReply ?? '',
    } satisfies CommentFormInput,
  })

  useEffect(() => {
    form.reset({
      isApproved: comment.isApproved,
      adminReply: comment.adminReply ?? '',
    })
  }, [form, comment])

  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>Yorumu incele</CardTitle>
            <CardDescription>
              Onaylama, cevaplama ve moderasyon.
            </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'>
        <div className='mb-4 rounded-3xl border border-border/70 bg-muted/20 p-4 shadow-sm'>
          <div className='mb-3 border-b border-border/70 pb-3'>
            <p className='text-sm font-semibold'>Yorum bilgisi</p>
          </div>
          <div className='space-y-2 text-sm'>
            <div>
              <span className='font-semibold'>{comment.authorName}</span>
            </div>
            <div className='text-muted-foreground'>
              {comment.commentableType} #{comment.commentableId}
            </div>
            <p className='whitespace-pre-wrap'>{comment.content}</p>
            <p className='text-xs text-muted-foreground'>
              {comment.createdAt &&
                new Date(comment.createdAt).toLocaleString('tr-TR')}
            </p>
          </div>
        </div>

        <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'>Moderasyon</p>
                <p className='text-sm text-muted-foreground'>
                  Onay durumu ve admin cevabı
                </p>
              </div>
              <div className='space-y-3'>
                <FormField
                  control={form.control}
                  name='isApproved'
                  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>Onaylandı</FormLabel>
                        <p className='text-sm text-muted-foreground'>
                          Yorum sitede görünür olur.
                        </p>
                      </div>
                      <FormControl>
                        <Switch
                          checked={field.value}
                          onCheckedChange={field.onChange}
                        />
                      </FormControl>
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name='adminReply'
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Admin cevabı</FormLabel>
                      <FormControl>
                        <Textarea
                          {...field}
                          rows={4}
                          placeholder='Yoruma cevap yazın...'
                        />
                      </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' />}
                Kaydet
              </Button>
            </div>
          </form>
        </Form>
      </CardContent>
    </Card>
  )
}

export function CommentsPage() {
  const queryClient = useQueryClient()
  const [page, setPage] = useState(1)
  const [searchTerm, setSearchTerm] = useState('')
  const deferredSearch = useDeferredValue(searchTerm)
  const [approvedFilter, setApprovedFilter] = useState('all')
  const [editorOpen, setEditorOpen] = useState(false)
  const [activeComment, setActiveComment] = useState<AdminCommentRecord | null>(
    null
  )
  const [commentToDelete, setCommentToDelete] =
    useState<AdminCommentRecord | null>(null)

  const commentsQuery = useQuery({
    queryKey: ['comments', page, approvedFilter, deferredSearch],
    queryFn: () =>
      fetchComments({
        page,
        perPage,
        search: deferredSearch || undefined,
        is_approved:
          approvedFilter === 'all' ? undefined : approvedFilter === 'approved',
      }),
  })

  const updateMutation = useMutation({
    mutationFn: async (values: CommentFormValues) => {
      if (!activeComment) return
      return updateComment(activeComment.id, {
        is_approved: values.isApproved,
        admin_reply: values.adminReply || null,
      })
    },
    onSuccess: async () => {
      toast.success('Yorum güncellendi')
      await queryClient.invalidateQueries({ queryKey: ['comments'] })
      setEditorOpen(false)
      setActiveComment(null)
    },
    onError: handleServerError,
  })

  const deleteMutation = useMutation({
    mutationFn: async (id: number | string) => deleteComment(id),
    onSuccess: async () => {
      toast.success('Yorum silindi')
      await queryClient.invalidateQueries({ queryKey: ['comments'] })
      setCommentToDelete(null)
    },
    onError: handleServerError,
  })

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

  return (
    <>
      <CommentsHeader />

      <Main className='space-y-6'>
        {editorOpen && activeComment ? (
          <CommentEditorPage
            comment={activeComment}
            isPending={updateMutation.isPending}
            onCancel={() => {
              setEditorOpen(false)
              setActiveComment(null)
            }}
            onSubmit={async (values) => {
              await updateMutation.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>Yorumlar</CardTitle>
                  <CardDescription>
                    Kullanıcı yorumlarını onaylama ve cevaplama.
                  </CardDescription>
                </div>
                <Button
                  variant='outline'
                  className='rounded-xl'
                  onClick={() => commentsQuery.refetch()}
                >
                  <RefreshCw
                    className={commentsQuery.isFetching ? 'animate-spin' : ''}
                  />
                  Yenile
                </Button>
              </div>

              <div className='rounded-2xl border border-dashed border-border/70 bg-muted/20 p-4'>
                <div className='grid gap-3 md:grid-cols-[1fr_220px_auto]'>
                  <div className='relative'>
                    <Search className='absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground' />
                    <Input
                      placeholder='Yazar adı veya içerik ara...'
                      value={searchTerm}
                      onChange={(e) => {
                        setSearchTerm(e.target.value)
                        setPage(1)
                      }}
                      className='pl-9'
                    />
                  </div>
                  <Select
                    value={approvedFilter}
                    onValueChange={(value) =>
                      startTransition(() => {
                        setApprovedFilter(value)
                        setPage(1)
                      })
                    }
                  >
                    <SelectTrigger className='w-full'>
                      <SelectValue placeholder='Tüm yorumlar' />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value='all'>Tüm yorumlar</SelectItem>
                      <SelectItem value='approved'>Onaylanan</SelectItem>
                      <SelectItem value='pending'>Bekleyen</SelectItem>
                    </SelectContent>
                  </Select>
                  <div className='flex items-end justify-end'>
                    <Button
                      variant='outline'
                      className='rounded-xl'
                      onClick={() => {
                        setSearchTerm('')
                        setApprovedFilter('all')
                        setPage(1)
                      }}
                      disabled={approvedFilter === 'all' && !searchTerm}
                    >
                      <FilterX />
                      Temizle
                    </Button>
                  </div>
                </div>
              </div>
            </CardHeader>
            <CardContent className='space-y-4'>
              <div className='rounded-2xl border border-border/70'>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className='px-4'>Yazar</TableHead>
                      <TableHead>Yorum</TableHead>
                      <TableHead>İlişkili</TableHead>
                      <TableHead>Durum</TableHead>
                      <TableHead>Tarih</TableHead>
                      <TableHead className='w-[180px] text-right'>
                        İşlemler
                      </TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {commentsQuery.isLoading ? (
                      <TableRow>
                        <TableCell
                          colSpan={6}
                          className='h-28 text-center text-muted-foreground'
                        >
                          <Loader2 className='mx-auto mb-2 size-5 animate-spin' />
                          Yükleniyor...
                        </TableCell>
                      </TableRow>
                    ) : commentsQuery.data?.items.length ? (
                      commentsQuery.data.items.map((item) => (
                        <TableRow
                          key={item.id}
                          className={
                            !item.isApproved
                              ? 'bg-yellow-50/60 dark:bg-yellow-950/10'
                              : ''
                          }
                        >
                          <TableCell className='px-4 py-4'>
                            <div className='font-medium'>{item.authorName}</div>
                          </TableCell>
                          <TableCell className='max-w-[300px] truncate text-sm text-muted-foreground'>
                            {item.content}
                          </TableCell>
                          <TableCell className='text-sm'>
                            <Badge
                              variant='outline'
                              className='rounded-full text-xs'
                            >
                              {item.commentableType} #{item.commentableId}
                            </Badge>
                          </TableCell>
                          <TableCell>
                            <Badge
                              variant={
                                item.isApproved ? 'default' : 'secondary'
                              }
                              className='rounded-full'
                            >
                              {item.isApproved ? 'Onaylı' : 'Bekliyor'}
                            </Badge>
                          </TableCell>
                          <TableCell className='text-sm text-muted-foreground'>
                            {item.createdAt &&
                              new Date(item.createdAt).toLocaleDateString(
                                'tr-TR'
                              )}
                          </TableCell>
                          <TableCell>
                            <div className='flex justify-end gap-2'>
                              <Button
                                variant='outline'
                                size='sm'
                                className='rounded-xl'
                                onClick={() => {
                                  setActiveComment(item)
                                  setEditorOpen(true)
                                }}
                              >
                                <PencilLine />
                                İncele
                              </Button>
                              <Button
                                variant='destructive'
                                size='sm'
                                className='rounded-xl'
                                onClick={() => setCommentToDelete(item)}
                              >
                                <Trash2 />
                                Sil
                              </Button>
                            </div>
                          </TableCell>
                        </TableRow>
                      ))
                    ) : (
                      <TableRow>
                        <TableCell
                          colSpan={6}
                          className='h-28 text-center text-muted-foreground'
                        >
                          Yorum 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 {commentsQuery.data?.meta.total ?? 0} kayıt. Sayfa{' '}
                  {page} / {commentsQuery.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(
                            commentsQuery.data?.meta.lastPage ?? 1,
                            c + 1
                          )
                        )
                      )
                    }
                    disabled={page === (commentsQuery.data?.meta.lastPage ?? 1)}
                  >
                    <ChevronRight />
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        )}
      </Main>

      <ConfirmDialog
        open={!!commentToDelete}
        onOpenChange={(open) => {
          if (!open) setCommentToDelete(null)
        }}
        title='Yorumu silmek istediğinize emin misiniz?'
        desc='Bu yorum kalıcı olarak silinecek.'
        confirmText='Evet, sil'
        cancelBtnText='İptal'
        destructive
        isLoading={deleteMutation.isPending}
        handleConfirm={() => {
          if (commentToDelete) {
            deleteMutation.mutate(commentToDelete.id)
          }
        }}
      />
    </>
  )
}
