/* 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 { createRegEvalCriteriaWithDetails } from '../service';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
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,
} from '@/db/schema';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
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(),
  criteriaDetails: z.array(
    z.object({
      id: z.number().optional(),
      detail: z.string().min(1, '평가내용은 필수 항목입니다.'),
      scoreEquipShip: z.coerce.number().nullable().optional(),
      scoreEquipMarine: z.coerce.number().nullable().optional(),
      scoreBulkShip: z.coerce.number().nullable().optional(),
      scoreBulkMarine: z.coerce.number().nullable().optional(),
    })
  ).min(1, '최소 1개의 평가 내용이 필요합니다.'),
});
type RegEvalCriteriaFormData = z.infer<typeof regEvalCriteriaFormSchema>;
interface CriteriaDetailFormProps {
  index: number
  form: any
  onRemove: () => void
  canRemove: boolean
  disabled?: boolean
}
interface RegEvalCriteriaFormSheetProps {
  open: boolean,
  onOpenChange: (open: boolean) => void,
  onSuccess: () => void,
};

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

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

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <CardTitle className="text-lg">Detail Item - {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>
          )}
        />
        <FormField
          control={form.control}
          name={`criteriaDetails.${index}.scoreEquipShip`}
          render={({ field }) => (
            <FormItem>
              <FormLabel>배점/기자재/조선</FormLabel>
              <FormControl>
                <Input
                  type="number"
                  step="0.1"
                  placeholder="배점/기자재/조선"
                  {...field}
                  value={field.value ?? 0}
                  disabled={disabled}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name={`criteriaDetails.${index}.scoreEquipMarine`}
          render={({ field }) => (
            <FormItem>
              <FormLabel>배점/기자재/해양</FormLabel>
              <FormControl>
                <Input
                  type="number"
                  step="0.1"
                  placeholder="배점/기자재/해양"
                  {...field}
                  value={field.value ?? 0}
                  disabled={disabled}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name={`criteriaDetails.${index}.scoreBulkShip`}
          render={({ field }) => (
            <FormItem>
              <FormLabel>배점/벌크/조선</FormLabel>
              <FormControl>
                <Input
                  type="number"
                  step="0.1"
                  placeholder="배점/벌크/조선"
                  {...field}
                  value={field.value ?? 0}
                  disabled={disabled}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name={`criteriaDetails.${index}.scoreBulkMarine`}
          render={({ field }) => (
            <FormItem>
              <FormLabel>배점/벌크/해양</FormLabel>
              <FormControl>
                <Input
                  type="number"
                  step="0.1"
                  placeholder="배점/벌크/해양"
                  {...field}
                  value={field.value ?? 0}
                  disabled={disabled}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
      </CardContent>
    </Card>
  )
}

/* CRITERIA FORM SHEET COPONENT */
function RegEvalCriteriaCreateDialog({
  open,
  onOpenChange,
  onSuccess,
}: RegEvalCriteriaFormSheetProps) {
  const [isPending, startTransition] = useTransition();
  const form = useForm<RegEvalCriteriaFormData>({
    resolver: zodResolver(regEvalCriteriaFormSchema),
    defaultValues: {
      category: '',
      category2: '',
      item: '',
      classification: '',
      range: '',
      remarks: '',
      criteriaDetails: [
        {
          id: undefined,
          detail: '',
          scoreEquipShip: null,
          scoreEquipMarine: null,
          scoreBulkShip: null,
          scoreBulkMarine: null,
        },
      ],
    },
  });

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

  useEffect(() => {
    if (open) {
      form.reset({
        category: '',
        category2: '',
        item: '',
        classification: '',
        range: '',
        remarks: '',
        criteriaDetails: [
          {
            id: undefined,
            detail: '',
            scoreEquipShip: null,
            scoreEquipMarine: null,
            scoreBulkShip: null,
            scoreBulkMarine: null,
          },
        ],
      })
    }
  }, [open, form]);

  const onSubmit = async (data: RegEvalCriteriaFormData) => {
    startTransition(async () => {
      try {
        const criteriaData = {
          category: data.category,
          category2: data.category2,
          item: data.item,
          classification: data.classification,
          range: data.range,
          remarks: data.remarks,
        };
        const detailList = data.criteriaDetails.map((detailItem) => ({
          id: detailItem.id,
          detail: detailItem.detail,
          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 createRegEvalCriteriaWithDetails(criteriaData, detailList);
        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 (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="w-1/3 max-w-[50vw] max-h-[90vh] overflow-y-auto">
        <DialogHeader className="mb-4">
          <DialogTitle className="font-bold">
            새 협력업체 평가 기준표 생성
          </DialogTitle>
          <DialogDescription>
            새로운 협력업체 평가 기준표를 생성합니다.
          </DialogDescription>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
            <ScrollArea className="overflow-y-auto">
              <div className="space-y-6">
                <Card className="w-full">
                  <CardHeader>
                    <CardTitle>Criterion Info</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-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>
                      )}
                    />
                    <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>
                      )}
                    />
                    <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>
                      )}
                    />
                  </CardContent>
                </Card>
                <Card>
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <div>
                        <CardTitle>Evaluation Criteria Item</CardTitle>
                        <CardDescription>
                          Set Evaluation Criteria Item.
                        </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" />
                        New Item
                      </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}
                        />
                      ))}
                    </div>
                  </CardContent>
                </Card>
              </div>
            </ScrollArea>
            <div className="flex justify-end gap-2 pt-4 border-t">
              <Button
                type="button"
                variant="outline"
                onClick={() => onOpenChange(false)}
                disabled={isPending}
              >
                Cancel
              </Button>
              <Button type="submit" disabled={isPending}>
                {isPending ? 'Saving...' : 'Create'}
              </Button>
            </div>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}

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

/* EXPORT */
export default RegEvalCriteriaCreateDialog;