'use client';

import { useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { trainingRecordCourseOptionsQueryOptions } from '../api/queries';
import type { TrainingRecordCourseOption } from '../api/types';

const CUSTOM_COURSE_VALUE = '__custom__';

function getCourseLabel(course: Pick<TrainingRecordCourseOption, 'course_code' | 'name'>) {
  return course.course_code ? `${course.course_code} - ${course.name}` : course.name;
}

interface TrainingRecordCourseComboboxProps {
  value: number | null | undefined;
  customCourseName: string;
  selectedCourseName: string;
  useCustomCourse: boolean;
  disabled?: boolean;
  onBlur: () => void;
  onSelectCourse: (course: TrainingRecordCourseOption) => void;
  onSelectCustom: () => void;
  onBackToCourseSelect: () => void;
  onCustomCourseNameChange: (value: string) => void;
  customCourseNameError?: string;
  selectionError?: string;
}

export function TrainingRecordCourseCombobox({
  value,
  customCourseName,
  selectedCourseName,
  useCustomCourse,
  disabled = false,
  onBlur,
  onSelectCourse,
  onSelectCustom,
  onBackToCourseSelect,
  onCustomCourseNameChange,
  customCourseNameError,
  selectionError
}: TrainingRecordCourseComboboxProps) {
  const { data: fetchedCourses = [] } = useQuery(trainingRecordCourseOptionsQueryOptions(''));

  const courseOptions = useMemo(() => {
    if (
      value !== null &&
      value !== undefined &&
      selectedCourseName &&
      !fetchedCourses.some((course) => course.id === value)
    ) {
      return [
        {
          id: value,
          course_code: null,
          name: selectedCourseName,
          category: '',
          standard_hours: 0,
          organizer: null,
          certificate_required: false
        },
        ...fetchedCourses
      ];
    }

    return fetchedCourses;
  }, [fetchedCourses, selectedCourseName, value]);

  if (useCustomCourse) {
    return (
      <div className='w-full space-y-3'>
        <div className='space-y-2'>
          <div className='text-sm font-medium'>ชื่อหลักสูตรอื่น ๆ *</div>
          <Input
            value={customCourseName}
            onChange={(event) => onCustomCourseNameChange(event.target.value)}
            onBlur={onBlur}
            placeholder='กรอกชื่อหลักสูตร'
            disabled={disabled}
            aria-invalid={Boolean(customCourseNameError)}
          />
          {customCourseNameError ? (
            <p className='text-destructive text-sm'>{customCourseNameError}</p>
          ) : null}
        </div>
        <div>
          <Button
            type='button'
            variant='link'
            className='h-auto px-0 text-left text-sm whitespace-normal'
            onClick={onBackToCourseSelect}
            disabled={disabled}
          >
            เปลี่ยนกลับไปเลือกจากหลักสูตร
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className='w-full space-y-2'>
      <div className='text-sm font-medium'>ชื่อหลักสูตร *</div>
      <Select
        value={value !== null && value !== undefined ? String(value) : undefined}
        onValueChange={(selectedValue) => {
          if (selectedValue === CUSTOM_COURSE_VALUE) {
            onSelectCustom();
            return;
          }

          const course = courseOptions.find((item) => String(item.id) === selectedValue);
          if (course) {
            onSelectCourse(course);
          }
        }}
        onOpenChange={(open) => {
          if (!open) onBlur();
        }}
        disabled={disabled}
      >
        <SelectTrigger className='w-full max-w-full' aria-invalid={Boolean(selectionError)}>
          <SelectValue placeholder='เลือกหลักสูตร' />
        </SelectTrigger>
        <SelectContent className='w-[min(var(--radix-select-trigger-width),calc(100vw-2rem))] max-w-[calc(100vw-2rem)]'>
          {courseOptions.map((course) => (
            <SelectItem key={course.id} value={String(course.id)}>
              <span className='block truncate'>{getCourseLabel(course)}</span>
            </SelectItem>
          ))}
          <SelectItem value={CUSTOM_COURSE_VALUE}>
            <span className='block truncate'>อื่น ๆ</span>
          </SelectItem>
        </SelectContent>
      </Select>
      {selectionError ? <p className='text-destructive text-sm'>{selectionError}</p> : null}
    </div>
  );
}
