/* eslint-disable @typescript-eslint/no-explicit-any */

'use client';

/* IMPORT */
import { Button } from '@/components/ui/button';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { 
  getRegEvalCriteriaWithDetails, 
  modifyRegEvalCriteriaFixed,
  modifyRegEvalCriteriaVariable,
} from '../service';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Plus, Trash2 } from 'lucide-react';
import {
  REG_EVAL_CRITERIA_CATEGORY,
  REG_EVAL_CRITERIA_CATEGORY2,
  REG_EVAL_CRITERIA_ITEM,
  type RegEvalCriteriaDetails,
  type RegEvalCriteria, // RegEvalCriteriaView 대신 RegEvalCriteria 사용
} from '@/db/schema';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
} from '@/components/ui/sheet';
import { Separator } from '@/components/ui/separator';
import { Textarea } from '@/components/ui/textarea';
import { toast } from 'sonner';
import { useForm, useFieldArray } from 'react-hook-form';
import { useEffect, useTransition } from 'react';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';

// ----------------------------------------------------------------------------------------------------

/* TYPES */
const regEvalCriteriaFormSchema = z.object({
  category: z.string().min(1, '평가부문은 필수 항목입니다.'),
  category2: z.string().min(1, '점수구분은 필수 항목입니다.'),
  item: z.string().min(1, '항목은 필수 항목입니다.'),
  classification: z.string().min(1, '구분은 필수 항목입니다.'),
  range: z.string().nullable().optional(),
  remarks: z.string().nullable().optional(),
  scoreType: z.enum(['fixed', 'variable']).default('fixed'),
  variableScoreMin: z.coerce.number().nullable().optional(),
  variableScoreMax: z.coerce.number().nullable().optional(),
  variableScoreUnit: z.string().nullable().optional(),
  criteriaDetails: z.array(
    z.object({
      id: z.number().optional(),
      detail: z.string().optional(),
      scoreEquipShip: z.coerce.number().nullable().optional(),
      scoreEquipMarine: z.coerce.number().nullable().optional(),
      scoreBulkShip: z.coerce.number().nullable().optional(),
      scoreBulkMarine: z.coerce.number().nullable().optional(),
    })
  ).optional(),
});

type RegEvalCriteriaFormData = z.infer<typeof regEvalCriteriaFormSchema>;

interface CriteriaDetailFormProps {
  index: number
  form: any
  onRemove: () => void
  canRemove: boolean
  disabled?: boolean
  scoreType: 'fixed' | 'variable'
}

interface RegEvalCriteriaUpdateSheetProps {
  open: boolean,
  onOpenChange: (open: boolean) => void,
  criteriaData: RegEvalCriteria, // criteriaViewData → criteriaData로 변경
  onSuccess: () => void,
};

// ----------------------------------------------------------------------------------------------------

/* CRITERIA DETAIL FORM COPONENT */
function CriteriaDetailForm({
  index,
  form,
  onRemove,
  canRemove,
  disabled = false,
  scoreType,
}: CriteriaDetailFormProps) {

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <CardTitle className="text-lg">평가 옵션 {index + 1}</CardTitle>
          {canRemove && (
            <Button
              type="button"
              variant="ghost"
              size="sm"
              onClick={onRemove}
              className="text-destructive hover:text-destructive"
              disabled={disabled}
            >
              <Trash2 className="w-4 h-4" />
            </Button>
          )}
        </div>
      </CardHeader>
      <CardContent className="space-y-4">
        <FormField
          control={form.control}
          name={`criteriaDetails.${index}.id`}
          render={({ field }) => (
            <Input type="hidden" {...field} />
          )}
        />
        <FormField
          control={form.control}
          name={`criteriaDetails.${index}.detail`}
          render={({ field }) => (
            <FormItem>
              <FormLabel>평가 옵션 내용</FormLabel>
              <FormControl>
                <Textarea
                  placeholder="평가 옵션 내용을 입력하세요. (예: 우수, 보통, 미흡)"
                  {...field}
                  disabled={disabled}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        {/* 고정점수인 경우에만 점수 입력 필드들 표시 - 한 줄에 4개 */}
        {scoreType === 'fixed' && (
          <div className="grid grid-cols-4 gap-4">
            <FormField
              control={form.control}
              name={`criteriaDetails.${index}.scoreEquipShip`}
              render={({ field }) => (
                <FormItem>
                  <FormLabel>기자재-조선</FormLabel>
                  <FormControl>
                    <Input
                      type="number"
                      step="0.01"
                      placeholder="0.00"
                      {...field}
                      value={field.value ?? ''}
                      disabled={disabled}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name={`criteriaDetails.${index}.scoreEquipMarine`}
              render={({ field }) => (
                <FormItem>
                  <FormLabel>기자재-해양</FormLabel>
                  <FormControl>
                    <Input
                      type="number"
                      step="0.01"
                      placeholder="0.00"
                      {...field}
                      value={field.value ?? ''}
                      disabled={disabled}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name={`criteriaDetails.${index}.scoreBulkShip`}
              render={({ field }) => (
                <FormItem>
                  <FormLabel>벌크-조선</FormLabel>
                  <FormControl>
                    <Input
                      type="number"
                      step="0.01"
                      placeholder="0.00"
                      {...field}
                      value={field.value ?? ''}
                      disabled={disabled}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name={`criteriaDetails.${index}.scoreBulkMarine`}
              render={({ field }) => (
                <FormItem>
                  <FormLabel>벌크-해양</FormLabel>
                  <FormControl>
                    <Input
                      type="number"
                      step="0.01"
                      placeholder="0.00"
                      {...field}
                      value={field.value ?? ''}
                      disabled={disabled}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>
        )}

        {/* 변동점수인 경우 안내 메시지 */}
        {scoreType === 'variable' && (
          <div className="p-4 bg-muted rounded-lg">
            <p className="text-sm text-muted-foreground">
              변동점수 유형에서는 개별 점수를 입력하지 않습니다. 
              기본 정보에서 설정한 최소/최대 점수 범위가 적용됩니다.
            </p>
          </div>
        )}
      </CardContent>
    </Card>
  )
}

/* CRITERIA FORM SHEET COPONENT */
function RegEvalCriteriaUpdateSheet({
  open,
  onOpenChange,
  criteriaData,
  onSuccess,
}: RegEvalCriteriaUpdateSheetProps) {

  const [isPending, startTransition] = useTransition();
  const form = useForm<RegEvalCriteriaFormData>({
    resolver: zodResolver(regEvalCriteriaFormSchema),
    defaultValues: {
      category: '',
      category2: '',
      item: '',
      classification: '',
      range: '',
      remarks: '',
      scoreType: 'fixed',
      variableScoreMin: null,
      variableScoreMax: null,
      variableScoreUnit: '',
      criteriaDetails: [
        {
          id: undefined,
          detail: '',
          scoreEquipShip: null,
          scoreEquipMarine: null,
          scoreBulkShip: null,
          scoreBulkMarine: null,
        },
      ],
    },
  });

  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: 'criteriaDetails',
  });

  // 현재 점수 유형 감시
  const scoreType = form.watch('scoreType');

  useEffect(() => {
    if (open && criteriaData?.id) {
      startTransition(async () => {
        try {
          const targetData = await getRegEvalCriteriaWithDetails(criteriaData.id);
          if (targetData) {
            form.reset({
              category: targetData.category,
              category2: targetData.category2,
              item: targetData.item,
              classification: targetData.classification,
              range: targetData.range,
              remarks: targetData.remarks,
              scoreType: targetData.scoreType || 'fixed',
              variableScoreMin: targetData.variableScoreMin 
                ? Number(targetData.variableScoreMin) : null,
              variableScoreMax: targetData.variableScoreMax 
                ? Number(targetData.variableScoreMax) : null,
              variableScoreUnit: targetData.variableScoreUnit,
              criteriaDetails: targetData.criteriaDetails?.map((detailItem: RegEvalCriteriaDetails) => ({
                id: detailItem.id,
                detail: detailItem.detail,
                scoreEquipShip: detailItem.scoreEquipShip !== null
                  ? Number(detailItem.scoreEquipShip) : null,
                scoreEquipMarine: detailItem.scoreEquipMarine !== null
                  ? Number(detailItem.scoreEquipMarine) : null,
                scoreBulkShip: detailItem.scoreBulkShip !== null
                  ? Number(detailItem.scoreBulkShip) : null,
                scoreBulkMarine: detailItem.scoreBulkMarine !== null
                  ? Number(detailItem.scoreBulkMarine) : null,
              })) || [],
            })
          }
        } catch (error) {
          console.error('Error in Loading Regular Evaluation Criteria for Updating:', error)
          toast.error(error instanceof Error ? error.message : '편집할 데이터를 불러오는 데 실패했습니다.')
        }
      });
    }
  }, [open, criteriaData, form]);

  const onSubmit = async (data: RegEvalCriteriaFormData) => {
    startTransition(async () => {
      try {
        if (data.scoreType === 'fixed') {
          // 고정 점수 검증
          if (!data.criteriaDetails || data.criteriaDetails.length === 0) {
            toast.error('고정 점수 유형에서는 최소 1개의 평가내용이 필요합니다.');
            return;
          }

          // 평가내용이 비어있는지 확인
          const hasEmptyDetail = data.criteriaDetails.some((detail: NonNullable<RegEvalCriteriaFormData['criteriaDetails']>[0]) => 
            !detail.detail || (detail.detail && detail.detail.trim() === '')
          );
          if (hasEmptyDetail) {
            toast.error('평가내용을 입력해주세요.');
            return;
          }

          const criteriaDataToUpdate = {
            category: data.category,
            category2: data.category2,
            item: data.item,
            classification: data.classification,
            range: data.range || null,
            remarks: data.remarks || null,
            scoreType: data.scoreType,
            variableScoreMin: null, // 고정 점수에서는 null
            variableScoreMax: null, // 고정 점수에서는 null
            variableScoreUnit: null, // 고정 점수에서는 null
          };

          const detailList = data.criteriaDetails.map((detailItem: NonNullable<RegEvalCriteriaFormData['criteriaDetails']>[0]) => ({
            id: detailItem.id,
            detail: detailItem.detail?.trim() || '',
            scoreEquipShip: detailItem.scoreEquipShip != null ? String(detailItem.scoreEquipShip) : null,
            scoreEquipMarine: detailItem.scoreEquipMarine != null ? String(detailItem.scoreEquipMarine) : null,
            scoreBulkShip: detailItem.scoreBulkShip != null ? String(detailItem.scoreBulkShip) : null,
            scoreBulkMarine: detailItem.scoreBulkMarine != null ? String(detailItem.scoreBulkMarine) : null,
          }));

          await modifyRegEvalCriteriaFixed(criteriaData.id, criteriaDataToUpdate, detailList);

        } else if (data.scoreType === 'variable') {
          // 변동 점수 검증
          if (data.variableScoreMin == null) {
            toast.error('변동 점수 유형에서는 최소 점수가 필수입니다.');
            return;
          }
          if (data.variableScoreMax == null) {
            toast.error('변동 점수 유형에서는 최대 점수가 필수입니다.');
            return;
          }
          if (!data.variableScoreUnit || data.variableScoreUnit.trim() === '') {
            toast.error('변동 점수 유형에서는 단위가 필수입니다.');
            return;
          }
          if (Number(data.variableScoreMin) >= Number(data.variableScoreMax)) {
            toast.error('최소 점수는 최대 점수보다 작아야 합니다.');
            return;
          }

          const criteriaDataToUpdate = {
            category: data.category,
            category2: data.category2,
            item: data.item,
            classification: data.classification,
            range: data.range || null,
            remarks: data.remarks || null,
            scoreType: data.scoreType,
            variableScoreMin: String(data.variableScoreMin),
            variableScoreMax: String(data.variableScoreMax),
            variableScoreUnit: data.variableScoreUnit.trim(),
          };

          await modifyRegEvalCriteriaVariable(criteriaData.id, criteriaDataToUpdate);
        } else {
          toast.error('올바른 점수 유형을 선택해주세요.');
          return;
        }

        toast.success('평가 기준이 수정되었습니다.');
        onSuccess();
        onOpenChange(false);
      } catch (error) {
        console.error('Error in Saving Regular Evaluation Criteria:', error);
        toast.error(
          error instanceof Error ? error.message : '평가 기준 저장 중 오류가 발생했습니다.'
        );
      }
    })
  }

  if (!open) {
    return null;
  }

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="w-[900px] sm:max-w-[900px] flex flex-col" style={{width:900, height: '100vh'}}>
        {/* 고정 헤더 */}
        <SheetHeader className="flex-shrink-0 pb-4 border-b">
          <SheetTitle className="font-bold">
            평가 기준 수정
          </SheetTitle>
          <SheetDescription>
            평가 기준의 정보를 수정합니다.
          </SheetDescription>
        </SheetHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col flex-1 min-h-0">
            {/* 스크롤 가능한 메인 콘텐츠 영역 */}
            <div className="flex-1 overflow-y-auto py-4 min-h-0">
              <div className="space-y-6 pr-4">
                <Card>
                  <CardHeader>
                    <CardTitle>기본 정보</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      <FormField
                        control={form.control}
                        name="category"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>평가부문</FormLabel>
                            <FormControl>
                              <Select onValueChange={field.onChange} value={field.value || ""}>
                                <SelectTrigger>
                                  <SelectValue placeholder="선택" />
                                </SelectTrigger>
                                <SelectContent>
                                  {REG_EVAL_CRITERIA_CATEGORY.map((option) => (
                                    <SelectItem key={option.value} value={option.value}>
                                      {option.label}
                                    </SelectItem>
                                  ))}
                                </SelectContent>
                              </Select>
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={form.control}
                        name="category2"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>점수구분</FormLabel>
                            <FormControl>
                              <Select onValueChange={field.onChange} value={field.value || ""}>
                                <SelectTrigger>
                                  <SelectValue placeholder="선택" />
                                </SelectTrigger>
                                <SelectContent>
                                  {REG_EVAL_CRITERIA_CATEGORY2.map((option) => (
                                    <SelectItem key={option.value} value={option.value}>
                                      {option.label}
                                    </SelectItem>
                                  ))}
                                </SelectContent>
                              </Select>
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                      <FormField
                        control={form.control}
                        name="item"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>항목</FormLabel>
                            <FormControl>
                              <Select onValueChange={field.onChange} value={field.value || ""}>
                                <SelectTrigger>
                                  <SelectValue placeholder="선택" />
                                </SelectTrigger>
                                <SelectContent>
                                  {REG_EVAL_CRITERIA_ITEM.map((option) => (
                                    <SelectItem key={option.value} value={option.value}>
                                      {option.label}
                                    </SelectItem>
                                  ))}
                                </SelectContent>
                              </Select>
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={form.control}
                        name="classification"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>구분</FormLabel>
                            <FormControl>
                              <Input placeholder="구분을 입력하세요." {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>
                      <FormField
                        control={form.control}
                        name="range"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>평가명</FormLabel>
                            <FormControl>
                              <Input
                                placeholder="평가명을 입력하세요." {...field}
                                value={field.value ?? ''}
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />

                    

                    <FormField
                      control={form.control}
                      name="remarks"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>비고</FormLabel>
                          <FormControl>
                            <Textarea
                              placeholder="비고를 입력하세요."
                              {...field}
                              value={field.value ?? ''}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                        control={form.control}
                        name="scoreType"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>점수유형</FormLabel>
                            <FormControl>
                              <Select onValueChange={field.onChange} value={field.value}>
                                <SelectTrigger>
                                  <SelectValue placeholder="선택" />
                                </SelectTrigger>
                                <SelectContent>
                                  <SelectItem value="fixed">고정점수</SelectItem>
                                  <SelectItem value="variable">변동점수</SelectItem>
                                </SelectContent>
                              </Select>
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      {/* 변동점수 설정 */}
                    {scoreType === 'variable' && (
                      <>
                        <Separator />
                        <div className="space-y-4">
                          <h4 className="font-medium">변동점수 설정</h4>
                          <div className="grid grid-cols-3 gap-4">
                          <FormField
                              control={form.control}
                              name="variableScoreMin"
                              render={({ field }) => (
                                <FormItem>
                                  <FormLabel>최소점수</FormLabel>
                                  <FormControl>
                                    <Input
                                      type="number"
                                      min="0"
                                      step="1"
                               placeholder="점수 입력 (0 이상)"
                                      {...field}
                                      value={field.value ?? ''}
                                    />
                                  </FormControl>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />
                            <FormField
                              control={form.control}
                              name="variableScoreMax"
                              render={({ field }) => (
                                <FormItem>
                                  <FormLabel>최대점수</FormLabel>
                                  <FormControl>
                                    <Input
                                      type="number"
                                      min="0"
                                      step="1"
                               placeholder="점수 입력 (0 이상)"
                                      {...field}
                                      value={field.value ?? ''}
                                    />
                                  </FormControl>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />
                            <FormField
                              control={form.control}
                              name="variableScoreUnit"
                              render={({ field }) => (
                                <FormItem>
                                  <FormLabel>점수단위</FormLabel>
                                  <FormControl>
                                    <Input
                                      placeholder="예: 감점, 가점"
                                      {...field}
                                      value={field.value ?? ''}
                                    />
                                  </FormControl>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />
                          </div>
                        </div>
                      </>
                    )}
                  </CardContent>
                </Card>
                {scoreType === 'fixed' && (
                <Card>
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <div>
                        <CardTitle>평가 옵션</CardTitle>
                        <CardDescription>
                          {scoreType === 'fixed' 
                            ? '각 평가 옵션별 점수를 설정하세요.'
                            : '평가 옵션을 설정하세요. (점수는 변동점수 설정을 따릅니다.)'}
                        </CardDescription>
                      </div>
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        className="ml-4"
                        onClick={() =>
                          append({
                            id: undefined,
                            detail: '',
                            scoreEquipShip: null,
                            scoreEquipMarine: null,
                            scoreBulkShip: null,
                            scoreBulkMarine: null,
                          })
                        }
                        disabled={isPending}
                      >
                        <Plus className="w-4 h-4 mr-2" />
                        옵션 추가
                      </Button>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      {fields.map((field, index) => (
                        <CriteriaDetailForm
                          key={field.id}
                          index={index}
                          form={form}
                          onRemove={() => remove(index)}
                          canRemove={fields.length > 1}
                          disabled={isPending}
                          scoreType={scoreType}
                        />
                      ))}
                    </div>
                  </CardContent>
                </Card>
                )}
                {scoreType === 'variable' && (
                  <Card>
                    <CardHeader>
                      <CardTitle>변동 점수 설정</CardTitle>
                      <CardDescription>
                        변동 점수 유형에서는 개별 평가 옵션을 설정할 수 없습니다. 
                        최소/최대 점수와 단위를 설정하여 점수 범위를 정의하세요.
                      </CardDescription>
                    </CardHeader>
                  </Card>
                )}
              </div>
            </div>

            {/* 고정 푸터 */}
            <div className="flex-shrink-0 flex justify-end gap-2 bg-background">
              <Button
                type="button"
                variant="outline"
                onClick={() => onOpenChange(false)}
                disabled={isPending}
              >
                취소
              </Button>
              <Button type="submit" disabled={isPending}>
                {isPending ? '저장 중...' : '수정'}
              </Button>
            </div>
          </form>
        </Form>
      </SheetContent>
    </Sheet>
  )
}

// ----------------------------------------------------------------------------------------------------

/* EXPORT */
export default RegEvalCriteriaUpdateSheet;