'use client';

import type { Table } from '@tanstack/react-table';
import { useSuspenseQuery } from '@tanstack/react-query';
import Link from 'next/link';
import { parseAsInteger, parseAsString, useQueryStates } from 'nuqs';
import { Icons } from '@/components/icons';
import { buttonVariants, Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { DataTable } from '@/components/ui/table/data-table';
import { DataTableViewOptions } from '@/components/ui/table/data-table-view-options';
import { useDataTable } from '@/hooks/use-data-table';
import { getSortingStateParser } from '@/lib/parsers';
import { cn } from '@/lib/utils';
import { coursesQueryOptions } from '../../api/queries';
import type { Course } from '../../api/types';
import { courseCategoryFilterOptions } from '../../constants/course-options';
import { columns } from './columns';

const columnIds = columns.map((column) => column.id).filter(Boolean) as string[];
const ALL_FILTER_VALUE = 'all';
const statusOptions = [
  { value: 'active', label: 'ใช้งานอยู่' },
  { value: 'inactive', label: 'ปิดใช้งาน' }
];

function normalizeSingleSelectValue(value?: string | null) {
  const normalized = value
    ?.split(/[.,]/)
    .map((item) => item.trim())
    .find(Boolean);

  return normalized && normalized !== ALL_FILTER_VALUE ? normalized : null;
}

type CoursesToolbarProps = {
  category: string | null;
  hasActiveFilters: boolean;
  isFetching: boolean;
  name: string | null;
  onCategoryChange: (value: string) => void;
  onClearFilters: () => void;
  onNameChange: (value: string) => void;
  onStatusChange: (value: string) => void;
  status: string | null;
  table: Table<Course>;
};

function CoursesToolbar({
  category,
  hasActiveFilters,
  isFetching,
  name,
  onCategoryChange,
  onClearFilters,
  onNameChange,
  onStatusChange,
  status,
  table
}: CoursesToolbarProps) {
  return (
    <>
      <div className='flex w-full min-w-0 flex-col gap-3 xl:flex-row xl:items-start xl:justify-between'>
        <Input
          aria-label='ค้นหาหลักสูตร'
          placeholder='ค้นหาจากชื่อหลักสูตร รหัสหลักสูตร หรือผู้จัด'
          value={name ?? ''}
          onChange={(event) => onNameChange(event.target.value)}
          className='h-10 w-full xl:max-w-[460px]'
        />

        <div className='flex w-full flex-wrap items-center justify-end gap-2 xl:w-auto xl:shrink-0'>
          {isFetching ? (
            <span className='text-muted-foreground inline-flex items-center gap-2 text-sm'>
              <Icons.spinner className='h-4 w-4 animate-spin' />
              กำลังโหลด
            </span>
          ) : null}
          <div className='hidden xl:flex'>
            <DataTableViewOptions
              table={table}
              triggerLabel='แสดงคอลัมน์'
              searchPlaceholder='ค้นหาคอลัมน์...'
              emptyLabel='ไม่พบคอลัมน์'
            />
          </div>
        </div>
      </div>

      <div className='flex w-full min-w-0 flex-wrap items-center gap-2'>
        <Select value={category ?? ALL_FILTER_VALUE} onValueChange={onCategoryChange}>
          <SelectTrigger aria-label='เลือกหมวดหมู่' className='h-10 w-full sm:w-[180px]'>
            <SelectValue placeholder='เลือกหมวดหมู่' />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value={ALL_FILTER_VALUE}>เลือกหมวดหมู่</SelectItem>
            {courseCategoryFilterOptions.map((option) => (
              <SelectItem key={option.value} value={option.value}>
                {option.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        <Select value={status ?? ALL_FILTER_VALUE} onValueChange={onStatusChange}>
          <SelectTrigger aria-label='เลือกสถานะ' className='h-10 w-full sm:w-[180px]'>
            <SelectValue placeholder='เลือกสถานะ' />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value={ALL_FILTER_VALUE}>เลือกสถานะ</SelectItem>
            {statusOptions.map((option) => (
              <SelectItem key={option.value} value={option.value}>
                {option.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        {hasActiveFilters ? (
          <Button
            type='button'
            variant='outline'
            size='sm'
            className='h-10 w-full sm:ml-auto sm:w-auto'
            onClick={onClearFilters}
          >
            ล้างตัวกรอง
          </Button>
        ) : null}
      </div>
    </>
  );
}

export function CoursesTable() {
  const [params, setParams] = useQueryStates({
    page: parseAsInteger.withDefault(1),
    perPage: parseAsInteger.withDefault(10),
    name: parseAsString,
    category: parseAsString.withDefault(ALL_FILTER_VALUE),
    status: parseAsString.withDefault(ALL_FILTER_VALUE),
    sort: getSortingStateParser(columnIds).withDefault([])
  });
  const search = params.name?.trim() ? params.name : null;
  const category = normalizeSingleSelectValue(params.category);
  const status = normalizeSingleSelectValue(params.status);

  const filters = {
    page: params.page,
    limit: params.perPage,
    ...(search && { search }),
    ...(category && { category }),
    ...(status && { status }),
    ...(params.sort.length > 0 && { sort: JSON.stringify(params.sort) })
  };

  const { data, isFetching } = useSuspenseQuery(coursesQueryOptions(filters));
  const hasActiveFilters = Boolean(search || category || status);
  const pageCount = Math.max(1, Math.ceil(data.total_courses / params.perPage));

  const { table } = useDataTable({
    data: data.courses,
    columns,
    pageCount,
    shallow: true,
    debounceMs: 500,
    initialState: {
      columnPinning: { right: ['actions'] }
    }
  });

  const resetFilters = () =>
    void setParams({
      page: 1,
      name: null,
      category: ALL_FILTER_VALUE,
      status: ALL_FILTER_VALUE
    });

  const toolbar = (
    <CoursesToolbar
      category={category}
      hasActiveFilters={hasActiveFilters}
      isFetching={isFetching}
      name={params.name}
      onCategoryChange={(value) =>
        void setParams({
          page: 1,
          category: value
        })
      }
      onClearFilters={resetFilters}
      onNameChange={(value) =>
        void setParams({
          page: 1,
          name: value || null
        })
      }
      onStatusChange={(value) =>
        void setParams({
          page: 1,
          status: value
        })
      }
      status={status}
      table={table}
    />
  );

  if (data.courses.length === 0 && hasActiveFilters) {
    return (
      <div className='w-full min-w-0 max-w-full space-y-4 overflow-hidden'>
        {toolbar}
        <Card className='border-dashed'>
          <CardContent className='flex flex-col items-center justify-center gap-4 py-12 text-center'>
            <div className='bg-muted flex h-12 w-12 items-center justify-center rounded-full'>
              <Icons.post className='text-muted-foreground h-6 w-6' />
            </div>
            <div className='space-y-1'>
              <h3 className='text-lg font-semibold'>ไม่พบหลักสูตรที่ตรงกับตัวกรอง</h3>
              <p className='text-muted-foreground max-w-md text-sm'>
                ลองปรับคำค้นหา หมวดหมู่ หรือสถานะ แล้วค้นหาอีกครั้ง
              </p>
            </div>
            <Button variant='outline' onClick={resetFilters}>
              ล้างตัวกรอง
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (data.courses.length === 0) {
    return (
      <Card className='border-dashed'>
        <CardContent className='flex flex-col items-center justify-center gap-4 py-12 text-center'>
          <div className='bg-muted flex h-12 w-12 items-center justify-center rounded-full'>
            <Icons.post className='text-muted-foreground h-6 w-6' />
          </div>
          <div className='space-y-1'>
            <h3 className='text-lg font-semibold'>ยังไม่มีหลักสูตรในข้อมูลหลัก</h3>
            <p className='text-muted-foreground max-w-md text-sm'>
              สร้างหลักสูตรแรกเพื่อกำหนดหมวดหมู่เริ่มต้น ค่าใช้จ่าย และเงื่อนไขใบรับรอง
            </p>
          </div>
          <Link
            href='/dashboard/courses/new'
            className={cn(buttonVariants({ variant: 'outline' }), 'text-sm')}
          >
            <Icons.add className='mr-2 h-4 w-4' />
            เพิ่มหลักสูตร
          </Link>
        </CardContent>
      </Card>
    );
  }

  return (
    <div className='w-full min-w-0 max-w-full space-y-4 overflow-hidden'>
      {toolbar}
      <DataTable table={table} />
    </div>
  );
}
