'use client';

import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { DurationPicker } from '@/components/ui/duration-picker';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useAppForm } from '@/components/ui/tanstack-form';
import { reviewTrainingRecordMutation } from '../api/review-mutations';
import type { TrainingRecord } from '../api/types';
import {
  trainingRecordReviewSchema,
  type TrainingRecordReviewFormValues
} from '../schemas/training-record';
import { trainingCategoryOptions } from '../constants/training-record-options';
import { getDurationMinutes } from '../utils/time-utils';

export function TrainingRecordReviewForm({ record }: { record: TrainingRecord }) {
  const router = useRouter();
  const [decision, setDecision] = useState<'approved' | 'needs_revision'>('approved');

  const reviewMutation = useMutation({
    ...reviewTrainingRecordMutation,
    onSuccess: (_data, variables) => {
      toast.success(
        variables.values.status === 'approved'
          ? 'อนุมัติรายการอบรมเรียบร้อยแล้ว'
          : 'ตีกลับรายการอบรมเรียบร้อยแล้ว'
      );
      router.push('/dashboard/pending-review?status=pending');
      router.refresh();
    },
    onError: (error) => {
      toast.error(
        error instanceof Error ? error.message : 'ไม่สามารถตรวจสอบรายการอบรมได้'
      );
    }
  });

  const form = useAppForm({
    defaultValues: {
      status: 'approved',
      category: record.category ?? 'K',
      approvedMinutes:
        getDurationMinutes(record.approved_minutes, record.approved_hours ?? record.hours) ??
        undefined,
      reviewerNote: record.reviewer_note ?? '',
      rejectReason: record.reject_reason ?? ''
    } as TrainingRecordReviewFormValues,
    validators: {
      onSubmit: trainingRecordReviewSchema
    },
    onSubmit: async ({ value }) => {
      await reviewMutation.mutateAsync({
        id: record.id,
        values: value
      });
    }
  });

  const isLocked = record.approval_status !== 'pending';

  return (
    <Card>
      <CardHeader>
        <CardTitle>ตรวจสอบโดย HRD</CardTitle>
      </CardHeader>
      <CardContent className='space-y-6'>
        <Tabs
          value={decision}
          onValueChange={(value) => {
            const nextDecision = value as 'approved' | 'needs_revision';
            setDecision(nextDecision);
            form.setFieldValue('status', nextDecision);
          }}
        >
          <TabsList className='grid w-full grid-cols-2'>
            <TabsTrigger value='approved' disabled={isLocked}>
              อนุมัติ
            </TabsTrigger>
            <TabsTrigger value='needs_revision' disabled={isLocked}>
              ขอแก้ไข
            </TabsTrigger>
          </TabsList>
          <form.AppForm>
            <form.Form className='space-y-6'>
              <TabsContent value='approved' className='space-y-4'>
                <form.AppField name='category'>
                  {(field) => (
                    <field.FieldSet>
                      <field.Field>
                        <field.FieldLabel htmlFor={field.name}>หมวดหมู่ *</field.FieldLabel>
                        <Select
                          value={field.state.value}
                          onValueChange={(value) =>
                            field.handleChange(value as 'K' | 'S' | 'A')
                          }
                          disabled={reviewMutation.isPending || isLocked}
                        >
                          <SelectTrigger id={field.name}>
                            <SelectValue placeholder='เลือกหมวดหมู่' />
                          </SelectTrigger>
                          <SelectContent>
                            {trainingCategoryOptions.map((option) => (
                              <SelectItem key={option.value} value={option.value}>
                                {option.label}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </field.Field>
                      <field.FieldError />
                    </field.FieldSet>
                  )}
                </form.AppField>

                <form.AppField name='approvedMinutes'>
                  {(field) => (
                    <field.FieldSet>
                      <field.Field>
                        <field.FieldLabel htmlFor={field.name}>
                          ชั่วโมงที่อนุมัติ *
                        </field.FieldLabel>
                        <DurationPicker
                          valueMinutes={field.state.value ?? null}
                          onChange={(minutes) => field.handleChange(minutes ?? undefined)}
                          maxHours={30}
                          minuteStep={5}
                          disabled={reviewMutation.isPending || isLocked}
                        />
                      </field.Field>
                      <field.FieldError />
                    </field.FieldSet>
                  )}
                </form.AppField>

                <form.AppField name='reviewerNote'>
                  {(field) => (
                    <field.FieldSet>
                      <field.Field>
                        <field.FieldLabel htmlFor={field.name}>หมายเหตุจาก HRD</field.FieldLabel>
                        <Textarea
                          id={field.name}
                          rows={4}
                          placeholder='ระบุหมายเหตุเพิ่มเติม'
                          value={field.state.value ?? ''}
                          disabled={reviewMutation.isPending || isLocked}
                          onBlur={field.handleBlur}
                          onChange={(event) => field.handleChange(event.target.value)}
                        />
                      </field.Field>
                      <field.FieldError />
                    </field.FieldSet>
                  )}
                </form.AppField>
              </TabsContent>

              <TabsContent value='needs_revision' className='space-y-4'>
                <form.AppField name='rejectReason'>
                  {(field) => (
                    <field.FieldSet>
                      <field.Field>
                        <field.FieldLabel htmlFor={field.name}>เหตุผลที่ตีกลับ *</field.FieldLabel>
                        <Textarea
                          id={field.name}
                          rows={5}
                          placeholder='อธิบายเหตุผลที่ตีกลับรายการนี้เพื่อให้พนักงานแก้ไขและส่งใหม่'
                          value={field.state.value ?? ''}
                          disabled={reviewMutation.isPending || isLocked}
                          onBlur={field.handleBlur}
                          onChange={(event) => field.handleChange(event.target.value)}
                        />
                      </field.Field>
                      <field.FieldError />
                    </field.FieldSet>
                  )}
                </form.AppField>
              </TabsContent>

              <div className='flex flex-col-reverse gap-2 sm:flex-row sm:justify-end'>
                <Button
                  type='button'
                  variant='outline'
                  onClick={() => router.push('/dashboard/pending-review?status=pending')}
                  className='w-full sm:w-auto'
                >
                  กลับ
                </Button>
                <form.SubmitButton
                  disabled={reviewMutation.isPending || isLocked}
                  className='w-full sm:w-auto'
                >
                  {isLocked
                    ? 'ตรวจสอบแล้ว'
                    : decision === 'approved'
                      ? 'อนุมัติรายการ'
                      : 'ส่งกลับให้แก้ไข'}
                </form.SubmitButton>
              </div>
            </form.Form>
          </form.AppForm>
        </Tabs>
      </CardContent>
    </Card>
  );
}
