'use client';

import Link from 'next/link';
import { DataTable } from '@/components/ui/table/data-table';
import { Button, buttonVariants } 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 { useDataTable } from '@/hooks/use-data-table';
import { useSuspenseQuery } from '@tanstack/react-query';
import { parseAsInteger, parseAsString, useQueryStates } from 'nuqs';
import { getSortingStateParser } from '@/lib/parsers';
import { Icons } from '@/components/icons';
import { cn } from '@/lib/utils';
import { trainingRecordsQueryOptions } from '../../api/queries';
import {
  approvalStatusFilterOptions,
  normalizeTrainingTypeForUi,
  trainingTypeFilterOptions
} from '../../constants/training-record-options';
import { columns } from './columns';

const columnIds = columns.map((c) => c.id).filter(Boolean) as string[];

function normalizeFilterValue(value: string | string[] | null) {
  if (Array.isArray(value)) {
    const values = value.map((item) => item.trim()).filter((item) => item && item !== 'all');
    return values.length ? values.join(',') : null;
  }

  const normalized = value?.trim();
  return normalized && normalized !== 'all' ? normalized : null;
}

function getSelectValue(primary: string | null, alias: string | null) {
  if (primary && primary !== 'all') {
    return primary;
  }

  if (alias && alias !== 'all') {
    return alias;
  }

  return 'all';
}

export function TrainingRecordsTable() {
  const [params, setParams] = useQueryStates({
    page: parseAsInteger.withDefault(1),
    perPage: parseAsInteger.withDefault(10),
    name: parseAsString,
    user_name: parseAsString,
    status: parseAsString,
    approval_status: parseAsString.withDefault('all'),
    type: parseAsString,
    training_type: parseAsString.withDefault('all'),
    sort: getSortingStateParser(columnIds).withDefault([])
  });

  const search = normalizeFilterValue(params.user_name ?? params.name);
  const selectedStatus = getSelectValue(params.approval_status, params.status);
  const selectedTrainingTypeValue = getSelectValue(params.training_type, params.type);
  const selectedTrainingType =
    selectedTrainingTypeValue === 'all'
      ? selectedTrainingTypeValue
      : normalizeTrainingTypeForUi(selectedTrainingTypeValue);
  const statuses = normalizeFilterValue(selectedStatus);
  const types = normalizeFilterValue(selectedTrainingType);

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

  const { data, isFetching } = useSuspenseQuery(trainingRecordsQueryOptions(filters));
  const hasActiveFilters = Boolean(search || statuses || types);

  const pageCount = Math.ceil(data.total_training_records / params.perPage);

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

  if (data.training_records.length === 0 && !hasActiveFilters) {
    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.calendar 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/training-records/new' className={cn(buttonVariants(), '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'>
      <div className='flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between'>
        <div className='flex min-w-0 flex-1 flex-col gap-2 md:flex-row'>
          <Input
            value={params.user_name ?? params.name ?? ''}
            onChange={(event) =>
              void setParams({
                page: 1,
                name: null,
                user_name: event.target.value || null
              })
            }
            placeholder='ค้นหาจากชื่อพนักงาน หลักสูตร หรือผู้จัดอบรม'
            className='md:max-w-md'
          />
          <Select
            value={selectedTrainingType}
            onValueChange={(value) =>
              void setParams({
                page: 1,
                type: null,
                training_type: value
              })
            }
          >
            <SelectTrigger className='w-full md:w-[240px]'>
              <SelectValue placeholder='ประเภทการอบรม' />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value='all'>ทุกประเภทการอบรม</SelectItem>
              {trainingTypeFilterOptions.map((option) => (
                <SelectItem key={option.value} value={option.value}>
                  {option.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Select
            value={selectedStatus}
            onValueChange={(value) =>
              void setParams({
                page: 1,
                status: null,
                approval_status: value
              })
            }
          >
            <SelectTrigger className='w-full md:w-[180px]'>
              <SelectValue placeholder='สถานะ' />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value='all'>ทุกสถานะ</SelectItem>
              {approvalStatusFilterOptions.map((option) => (
                <SelectItem key={option.value} value={option.value}>
                  {option.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <div className='flex flex-wrap items-center gap-2 lg: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}
          {hasActiveFilters ? (
            <Button
              variant='outline'
              size='sm'
              onClick={() =>
                void setParams({
                  page: 1,
                  name: null,
                  user_name: null,
                  status: null,
                  approval_status: 'all',
                  type: null,
                  training_type: 'all'
                })
              }
            >
              ล้างตัวกรอง
            </Button>
          ) : null}
        </div>
      </div>

      <DataTable table={table} />
    </div>
  );
}
