'use client';

import { useSuspenseQuery } from '@tanstack/react-query';
import { notFound } from 'next/navigation';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Icons } from '@/components/icons';
import { trainingRecordByIdOptions } from '../api/queries';
import { TrainingRecordCertificateManager } from './training-record-certificate-manager';
import { TrainingRecordReviewForm } from './training-record-review-form';
import {
  trainingRecordStatusLabelMap,
  trainingTypeLabelMap
} from '../constants/training-record-options';
import { formatDurationThai, getDurationMinutes } from '../utils/time-utils';

export default function TrainingRecordReviewPage({ trainingRecordId }: { trainingRecordId: number }) {
  const { data } = useSuspenseQuery(trainingRecordByIdOptions(trainingRecordId));

  if (!data?.success || !data.training_record) {
    notFound();
  }

  const record = data.training_record;

  return (
    <div className='space-y-6'>
      {record.approval_status !== 'pending' ? (
        <Alert>
          <Icons.info className='h-4 w-4' />
          <AlertTitle>รายการนี้ถูกตรวจสอบแล้ว</AlertTitle>
          <AlertDescription>
            รายการอบรมนี้มีสถานะ {trainingRecordStatusLabelMap[record.approval_status]}
          </AlertDescription>
        </Alert>
      ) : null}

      <Card>
        <CardHeader className='flex flex-col gap-4 md:flex-row md:items-start md:justify-between'>
          <div className='min-w-0 space-y-1'>
            <CardTitle>{record.course_name}</CardTitle>
            <p className='text-muted-foreground break-words text-sm'>
              {record.user_name}
              {record.company_name ? ` | ${record.company_name}` : ''}
              {record.department_name ? ` | ${record.department_name}` : ''}
            </p>
          </div>
          <Badge variant='outline' className='max-w-full self-start whitespace-normal'>
            {trainingRecordStatusLabelMap[record.approval_status]}
          </Badge>
        </CardHeader>
        <CardContent className='grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4'>
          <ReviewField
            label='วันที่อบรม'
            value={new Date(record.training_date).toLocaleDateString('th-TH')}
          />
          <ReviewField label='ประเภทการอบรม' value={trainingTypeLabelMap[record.training_type]} />
          <ReviewField
            label='ชั่วโมงที่ส่ง'
            value={formatDurationThai(getDurationMinutes(record.submitted_minutes, record.hours))}
          />
          <ReviewField label='ผู้จัดอบรม' value={record.organizer ?? '-'} />
          <ReviewField label='หมวดหมู่ที่ส่งมา' value={record.category ?? '-'} />
          <ReviewField
            label='ชั่วโมงที่อนุมัติ'
            value={formatDurationThai(
              getDurationMinutes(record.approved_minutes, record.approved_hours)
            )}
          />
          <ReviewField label='หมายเหตุจาก HRD' value={record.reviewer_note ?? '-'} />
          <ReviewField label='เหตุผลที่ไม่อนุมัติ' value={record.reject_reason ?? '-'} />
          <div className='md:col-span-2 xl:col-span-4'>
            <div className='text-muted-foreground text-xs uppercase'>หมายเหตุ</div>
            <div className='mt-1 rounded-md border px-3 py-2 text-sm whitespace-pre-wrap'>
              {record.note ?? '-'}
            </div>
          </div>
        </CardContent>
      </Card>

      <TrainingRecordReviewForm record={record} />

      <TrainingRecordCertificateManager trainingRecordId={record.id} canManage={false} />
    </div>
  );
}

function ReviewField({ label, value }: { label: string; value: string }) {
  return (
    <div className='space-y-1'>
      <div className='text-muted-foreground text-xs uppercase'>{label}</div>
      <div className='rounded-md border px-3 py-2 text-sm break-words whitespace-pre-wrap'>
        {value}
      </div>
    </div>
  );
}
