import { startTransition, useDeferredValue, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import {
  ChevronLeft,
  ChevronRight,
  FilterX,
  Loader2,
  PencilLine,
  Plus,
  RefreshCw,
  Search,
  Trash2,
} from 'lucide-react'
import { toast } from 'sonner'
import { fetchCourseOptions } from '@/lib/api/courses'
import { deleteSchedule, fetchSchedules } from '@/lib/api/schedules'
import type { AdminScheduleRecord } 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 { Input } from '@/components/ui/input'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { ConfirmDialog } from '@/components/confirm-dialog'
import { Main } from '@/components/layout/main'
import { SchedulesHeader } from './components/schedules-header'

const perPage = 10

export function SchedulesPage() {
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const [page, setPage] = useState(1)
  const [searchInput, setSearchInput] = useState('')
  const deferredSearch = useDeferredValue(searchInput)
  const [statusFilter, setStatusFilter] = useState('all')
  const [courseFilter, setCourseFilter] = useState('all')
  const [dateFrom, setDateFrom] = useState('')
  const [dateTo, setDateTo] = useState('')
  const [scheduleToDelete, setScheduleToDelete] = useState<AdminScheduleRecord | null>(null)

  const hasActiveFilters = searchInput !== '' || statusFilter !== 'all' || courseFilter !== 'all' || dateFrom !== '' || dateTo !== ''

  const coursesQuery = useQuery({
    queryKey: ['courses', 'options'],
    queryFn: fetchCourseOptions,
  })

  const schedulesQuery = useQuery({
    queryKey: ['schedules', page, courseFilter, statusFilter, deferredSearch, dateFrom, dateTo],
    queryFn: () =>
      fetchSchedules({
        page,
        perPage,
        courseId: courseFilter === 'all' ? undefined : courseFilter,
        status: statusFilter === 'all' ? undefined : statusFilter,
        search: deferredSearch || undefined,
        dateFrom: dateFrom || undefined,
        dateTo: dateTo || undefined,
      }),
  })

  const deleteMutation = useMutation({
    mutationFn: async (scheduleId: number | string) => deleteSchedule(scheduleId),
    onSuccess: async () => {
      toast.success('Takvim kaydı silindi')
      await queryClient.invalidateQueries({ queryKey: ['schedules'] })
      setScheduleToDelete(null)
    },
    onError: handleServerError,
  })

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

  return (
    <>
      <SchedulesHeader />
      <Main className='space-y-6'>
        <Card>
          <CardHeader className='gap-4'>
            <div className='flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between'>
              <div>
                <CardTitle>Takvim listesi</CardTitle>
                <CardDescription>`/api/admin/schedules` kaynağı kurs bazlı filtrelenebilir.</CardDescription>
              </div>
              <div className='flex flex-wrap gap-2'>
                <Button variant='outline' className='rounded-xl' onClick={() => schedulesQuery.refetch()}>
                  <RefreshCw className={schedulesQuery.isFetching ? 'animate-spin' : ''} />
                  Yenile
                </Button>
                <Button className='rounded-xl' onClick={() => navigate({ to: '/schedules/create' })}>
                  <Plus />
                  Ekle
                </Button>
              </div>
            </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_180px_220px]'>
                <div className='relative'>
                  <Search className='pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground' />
                  <Input
                    placeholder='Lokasyon veya eğitmen ara...'
                    value={searchInput}
                    onChange={(e) => { setSearchInput(e.target.value); setPage(1) }}
                    className='pl-9'
                  />
                </div>
                <Select
                  value={statusFilter}
                  onValueChange={(value) => startTransition(() => { setStatusFilter(value); setPage(1) })}
                >
                  <SelectTrigger className='w-full'>
                    <SelectValue placeholder='Tüm durumlar' />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value='all'>Tümü</SelectItem>
                    <SelectItem value='planned'>Planlandı</SelectItem>
                    <SelectItem value='active'>Aktif</SelectItem>
                    <SelectItem value='completed'>Tamamlandı</SelectItem>
                    <SelectItem value='cancelled'>İptal</SelectItem>
                  </SelectContent>
                </Select>
                <Select
                  value={courseFilter}
                  onValueChange={(value) => startTransition(() => { setCourseFilter(value); setPage(1) })}
                >
                  <SelectTrigger className='w-full'>
                    <SelectValue placeholder='Tüm eğitimler' />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value='all'>Tüm eğitimler</SelectItem>
                    {(coursesQuery.data ?? []).map((course) => (
                      <SelectItem key={course.id} value={String(course.id)}>{course.title}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className='mt-3 grid gap-3 md:grid-cols-[1fr_1fr_auto]'>
                <div className='space-y-1'>
                  <label className='text-xs font-medium text-muted-foreground'>Başlangıç tarihi</label>
                  <Input
                    type='date'
                    value={dateFrom}
                    onChange={(e) => { setDateFrom(e.target.value); startTransition(() => setPage(1)) }}
                  />
                </div>
                <div className='space-y-1'>
                  <label className='text-xs font-medium text-muted-foreground'>Bitiş tarihi</label>
                  <Input
                    type='date'
                    value={dateTo}
                    onChange={(e) => { setDateTo(e.target.value); startTransition(() => setPage(1)) }}
                  />
                </div>
                <div className='flex items-end'>
                  {hasActiveFilters && (
                    <Button
                      variant='outline'
                      className='rounded-xl'
                      onClick={() => { setSearchInput(''); setStatusFilter('all'); setCourseFilter('all'); setDateFrom(''); setDateTo(''); setPage(1) }}
                    >
                      <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'>Program</TableHead>
                    <TableHead>Tarihler</TableHead>
                    <TableHead>Lokasyon</TableHead>
                    <TableHead>Koltuk</TableHead>
                    <TableHead className='w-[180px] text-right'>İşlemler</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {schedulesQuery.isLoading ? (
                    <TableRow>
                      <TableCell colSpan={5} className='h-28 text-center text-muted-foreground'>
                        <Loader2 className='mx-auto mb-2 size-5 animate-spin' />
                        Takvim kayıtları yükleniyor...
                      </TableCell>
                    </TableRow>
                  ) : schedulesQuery.data?.items.length ? (
                    schedulesQuery.data.items.map((schedule) => (
                      <TableRow key={schedule.id}>
                        <TableCell className='px-4 py-4'>
                          <div>
                            <p className='font-medium text-foreground'>{schedule.courseTitle}</p>
                            <p className='text-sm text-muted-foreground'>{schedule.status}</p>
                          </div>
                        </TableCell>
                        <TableCell className='text-sm text-muted-foreground'>
                          <div>{schedule.startDate || '-'}</div>
                          <div>{schedule.endDate || '-'}</div>
                        </TableCell>
                        <TableCell className='text-sm text-muted-foreground'>
                          <div>{schedule.location}</div>
                          <div>{schedule.instructor || '-'}</div>
                        </TableCell>
                        <TableCell>
                          <Badge variant='outline' className='rounded-full'>
                            {schedule.availableSeats}/{schedule.quota}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <div className='flex justify-end gap-2'>
                            <Button
                              variant='outline'
                              size='sm'
                              className='rounded-xl'
                              onClick={() => navigate({ to: '/schedules/$scheduleId', params: { scheduleId: String(schedule.id) } })}
                            >
                              <PencilLine />
                              Düzenle
                            </Button>
                            <Button
                              variant='destructive'
                              size='sm'
                              className='rounded-xl'
                              onClick={() => setScheduleToDelete(schedule)}
                            >
                              <Trash2 />
                              Sil
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  ) : (
                    <TableRow>
                      <TableCell colSpan={5} className='h-28 text-center text-muted-foreground'>
                        Filtreye uygun takvim 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 {schedulesQuery.data?.meta.total ?? 0} kayıt. Sayfa {page} / {schedulesQuery.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(schedulesQuery.data?.meta.lastPage ?? 1, c + 1)))} disabled={page === (schedulesQuery.data?.meta.lastPage ?? 1)}>
                  <ChevronRight />
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      </Main>

      <ConfirmDialog
        open={!!scheduleToDelete}
        onOpenChange={(open) => { if (!open) setScheduleToDelete(null) }}
        title='Takvimi silmek istediğinize emin misiniz?'
        desc={`${scheduleToDelete?.courseTitle ?? 'Bu program'} kalıcı olarak silinecek. Bu işlem geri alınamaz.`}
        confirmText='Evet, sil'
        cancelBtnText='İptal'
        destructive
        isLoading={deleteMutation.isPending}
        handleConfirm={() => { if (scheduleToDelete) deleteMutation.mutate(scheduleToDelete.id) }}
      />
    </>
  )
}
