'use client';

import Link from 'next/link';
import { useMemo } from 'react';
import type { ColumnDef } from '@tanstack/react-table';
import { useMutation, useQueryClient, useSuspenseQuery } from '@tanstack/react-query';
import { parseAsInteger, parseAsString, useQueryStates } from 'nuqs';
import { toast } from 'sonner';
import { Icons } from '@/components/icons';
import { 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 { ContentApprovalStatusBadge } from '@/features/content-approval/components/content-approval-status-badge';
import { contentApprovalStatusLabels } from '@/features/content-approval/lib/workflow';
import { useDataTable } from '@/hooks/use-data-table';
import { formatDate } from '@/lib/format';
import { invalidateContentWorkflowData } from '@/lib/query-invalidation';
import { deleteOnlineLessonMutation, updateOnlineLessonStateMutation } from '../api/mutations';
import { onlineLessonsQueryOptions } from '../api/queries';
import type {
  OnlineLesson,
  OnlineLessonCategory,
  OnlineLessonStatus,
  OnlineLessonWorkflowActionPayload
} from '../api/types';
import { getOnlineLessonCategoryLabel, onlineLessonCategoryOptions } from '../constants/categories';
import { OnlineLessonActionMenu } from './online-lesson-action-menu';

function OnlineLessonPlaceholderCover() {
  return (
    <div className='from-muted via-muted/80 to-muted/60 flex h-14 w-20 items-center justify-center rounded-md bg-gradient-to-br'>
      <Icons.video className='text-muted-foreground h-6 w-6' />
    </div>
  );
}

type BuildColumnsOptions = {
  currentUserId: string;
  permissions: readonly string[];
  canManageOnlineLessons: boolean;
  isUpdating: boolean;
  isDeleting: boolean;
  onUpdateStatus: (values: { id: number; values: OnlineLessonWorkflowActionPayload }) => void;
  onDelete: (id: number) => void;
};

function buildOnlineLessonColumns({
  currentUserId,
  permissions,
  canManageOnlineLessons,
  isUpdating,
  isDeleting,
  onUpdateStatus,
  onDelete
}: BuildColumnsOptions): ColumnDef<OnlineLesson>[] {
  return [
    {
      id: 'thumbnail',
      accessorKey: 'thumbnail_url',
      header: 'รูปปก / ไฟล์',
      cell: ({ row }) =>
        row.original.thumbnail_url ? (
          // eslint-disable-next-line @next/next/no-img-element
          <img
            src={row.original.thumbnail_url}
            alt={row.original.title}
            className='h-14 w-20 rounded-md object-cover'
          />
        ) : (
          <OnlineLessonPlaceholderCover />
        ),
      meta: {
        headerClassName: 'w-[120px]',
        cellClassName: 'w-[120px]'
      }
    },
    {
      id: 'title',
      accessorKey: 'title',
      header: 'ชื่อบทเรียน',
      cell: ({ row }) => (
        <div className='flex min-w-[220px] max-w-[360px] flex-col'>
          <div className='truncate font-medium'>{row.original.title}</div>
          <div className='text-muted-foreground line-clamp-2 text-xs break-words'>
            {row.original.description || 'ไม่มีรายละเอียดเพิ่มเติม'}
          </div>
        </div>
      ),
      meta: {
        headerClassName: 'w-[360px]',
        cellClassName: 'w-[360px]'
      }
    },
    {
      id: 'category',
      accessorKey: 'category',
      header: 'หมวดหมู่',
      cell: ({ row }) => (
        <span className='block min-w-[150px] text-sm'>
          {getOnlineLessonCategoryLabel(row.original.category)}
        </span>
      ),
      meta: {
        headerClassName: 'w-[180px]',
        cellClassName: 'w-[180px]'
      }
    },
    {
      id: 'status',
      accessorKey: 'status',
      header: 'สถานะ',
      cell: ({ row }) => (
        <div className='min-w-[140px]'>
          <ContentApprovalStatusBadge status={row.original.status} />
        </div>
      ),
      meta: {
        headerClassName: 'w-[150px]',
        cellClassName: 'w-[150px]'
      }
    },
    {
      id: 'published_at',
      accessorKey: 'published_at',
      header: 'วันที่เผยแพร่',
      cell: ({ row }) => (row.original.published_at ? formatDate(row.original.published_at) : '-'),
      meta: {
        headerClassName: 'w-[150px]',
        cellClassName: 'w-[150px]'
      }
    },
    ...(canManageOnlineLessons
      ? [
          {
            id: 'created_by_name',
            accessorKey: 'created_by_name',
            header: 'ผู้สร้าง',
            cell: ({ row }) => (
              <span className='block min-w-[160px] max-w-[220px] truncate'>
                {row.original.created_by_name || '-'}
              </span>
            ),
            meta: {
              headerClassName: 'w-[160px]',
              cellClassName: 'w-[160px]'
            }
          } satisfies ColumnDef<OnlineLesson>
        ]
      : []),
    {
      size: 50,
      id: 'actions',
      header: () => <span className='sr-only'>จัดการ</span>,
      cell: ({ row }) => (
        <div className='flex justify-end'>
          {canManageOnlineLessons ? (
            <OnlineLessonActionMenu
              lesson={row.original}
              currentUserId={currentUserId}
              permissions={permissions}
              isUpdating={isUpdating}
              isDeleting={isDeleting}
              onUpdateStatus={onUpdateStatus}
              onDelete={onDelete}
            />
          ) : (
            <Button asChild size='sm'>
              <Link href={`/dashboard/online-lessons/${row.original.id}`}>เปิดบทเรียน</Link>
            </Button>
          )}
        </div>
      )
    }
  ];
}

export default function OnlineLessonsPage({
  currentUserId,
  permissions,
  canManageOnlineLessons = false
}: {
  currentUserId: string;
  permissions: readonly string[];
  canManageOnlineLessons?: boolean;
}) {
  const queryClient = useQueryClient();
  const [params, setParams] = useQueryStates({
    page: parseAsInteger.withDefault(1),
    perPage: parseAsInteger.withDefault(10),
    search: parseAsString,
    category: parseAsString.withDefault('all'),
    status: parseAsString.withDefault('all')
  });

  const filters = {
    page: params.page,
    limit: params.perPage,
    ...(params.search ? { search: params.search } : {}),
    ...(params.category !== 'all' ? { category: params.category as OnlineLessonCategory } : {}),
    ...(canManageOnlineLessons && params.status !== 'all'
      ? { status: params.status as OnlineLessonStatus }
      : {})
  };

  const { data, isFetching } = useSuspenseQuery(onlineLessonsQueryOptions(filters));

  const stateMutation = useMutation({
    ...updateOnlineLessonStateMutation,
    onSuccess: async (response) => {
      await invalidateContentWorkflowData(queryClient);
      toast.success(response.message);
    },
    onError: (mutationError) => toast.error(mutationError.message || 'ไม่สามารถอัปเดตสถานะบทเรียนได้')
  });

  const deleteMutation = useMutation({
    ...deleteOnlineLessonMutation,
    onSuccess: async (response) => {
      await invalidateContentWorkflowData(queryClient);
      toast.success(response.message);
    },
    onError: (mutationError) => toast.error(mutationError.message || 'ไม่สามารถลบบทเรียนได้')
  });

  const columns = useMemo(
    () =>
      buildOnlineLessonColumns({
        currentUserId,
        permissions,
        canManageOnlineLessons,
        isUpdating: stateMutation.isPending,
        isDeleting: deleteMutation.isPending,
        onUpdateStatus: stateMutation.mutate,
        onDelete: deleteMutation.mutate
      }),
    [
      canManageOnlineLessons,
      currentUserId,
      deleteMutation.isPending,
      deleteMutation.mutate,
      permissions,
      stateMutation.isPending,
      stateMutation.mutate
    ]
  );

  const hasActiveFilters = Boolean(
    (params.search && params.search.trim()) ||
    params.category !== 'all' ||
    (canManageOnlineLessons && params.status !== 'all')
  );

  const pageCount = Math.max(1, Math.ceil(data.total_online_lessons / params.perPage));

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

  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.search ?? ''}
            onChange={(event) =>
              void setParams({
                page: 1,
                search: event.target.value || null
              })
            }
            placeholder='ค้นหาจากชื่อบทเรียนหรือหมวดหมู่'
            className='md:max-w-md'
          />
          <Select
            value={params.category}
            onValueChange={(value) => void setParams({ page: 1, category: value })}
          >
            <SelectTrigger className='w-full md:w-[220px]'>
              <SelectValue placeholder='หมวดหมู่' />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value='all'>ทุกหมวดหมู่</SelectItem>
              {onlineLessonCategoryOptions.map((category) => (
                <SelectItem key={category.value} value={category.value}>
                  {category.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          {canManageOnlineLessons ? (
            <Select
              value={params.status}
              onValueChange={(value) => void setParams({ page: 1, status: value })}
            >
              <SelectTrigger className='w-full md:w-[180px]'>
                <SelectValue placeholder='สถานะ' />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value='all'>ทุกสถานะ</SelectItem>
                {Object.entries(contentApprovalStatusLabels).map(([value, label]) => (
                  <SelectItem key={value} value={value}>
                    {label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          ) : null}
        </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,
                  search: null,
                  category: 'all',
                  ...(canManageOnlineLessons ? { status: 'all' } : {})
                })
              }
            >
              ล้างตัวกรอง
            </Button>
          ) : null}
        </div>
      </div>

      {/* <Card>
        <CardContent className='flex flex-col gap-3 p-4'>
          
        </CardContent>
      </Card> */}

      {data.online_lessons.length === 0 ? (
        <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.video className='text-muted-foreground h-6 w-6' />
            </div>
            <div className='space-y-1'>
              <h3 className='text-lg font-semibold'>
                {hasActiveFilters ? 'ไม่พบบทเรียนที่ตรงกับตัวกรอง' : 'ยังไม่มีบทเรียนออนไลน์'}
              </h3>
              <p className='text-muted-foreground max-w-md text-sm'>
                {hasActiveFilters
                  ? 'ลองปรับคำค้นหาหรือตัวกรอง แล้วค้นหาอีกครั้ง'
                  : 'เมื่อมีบทเรียนที่เผยแพร่แล้ว ระบบจะแสดงรายการที่หน้านี้'}
              </p>
            </div>
          </CardContent>
        </Card>
      ) : (
        <div className='w-full min-w-0 max-w-full'>
          <DataTable table={table} tableClassName='table-fixed' />
        </div>
      )}
    </div>
  );
}
