'use client';

/* IMPORT */
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  getRegEvalCriteriaWithDetails,
  removeRegEvalCriteria,
} from '../service';
import { LoaderCircle } from 'lucide-react';
import { toast } from 'sonner';
import {
  REG_EVAL_CRITERIA_CATEGORY,
  REG_EVAL_CRITERIA_CATEGORY2,
  REG_EVAL_CRITERIA_ITEM,
  type RegEvalCriteriaView,
  type RegEvalCriteriaWithDetails,
} from '@/db/schema';
import { useEffect, useState } from 'react';

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

/* TYPES */
interface RegEvalCriteriaDeleteDialogProps {
  open: boolean,
  onOpenChange: (open: boolean) => void,
  criteriaViewData: RegEvalCriteriaView,
  onSuccess: () => void,
}

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

/* REGULAR EVALUATION CRITERIA DELETE DIALOG COMPONENT */
function RegEvalCriteriaDeleteDialog(props: RegEvalCriteriaDeleteDialogProps) {
  const { open, onOpenChange, criteriaViewData, onSuccess } = props;
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [isDeleting, setIsDeleting] = useState<boolean>(false);
  const [targetData, setTargetData] = useState<RegEvalCriteriaWithDetails | null>();

  useEffect(() => {
    const fetchData = async () => {
      if (!criteriaViewData?.criteriaId) {
        return;
      }
      setIsLoading(true);
      try {
        const result = await getRegEvalCriteriaWithDetails(criteriaViewData.criteriaId);
        setTargetData(result);
      } catch (error) {
        console.error('Error in Loading Target Data for Deletion: ', error);
      } finally {
        setIsLoading(false);
      }
    }
    fetchData();
  }, [criteriaViewData.criteriaId]);
  
  const handleDelete = async () => {
    if (!criteriaViewData || !criteriaViewData.criteriaId) {
      return;
    }

    try {
      setIsDeleting(true);
      await removeRegEvalCriteria(criteriaViewData.criteriaId);
      toast.success('평가 기준이 삭제되었습니다.');
      onSuccess();
    } catch (error) {
      console.error('Error in Deleting Regular Evaluation Criteria: ', error);
      toast.error(
        error instanceof Error ? error.message : '삭제 중 오류가 발생했습니다.'
      );
    } finally {
      setIsDeleting(false);
    }
  }

  if (!criteriaViewData) {
    return null;
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        {isLoading ? (
          <DialogHeader className="flex flex-col items-center justify-center h-32">
            <LoaderCircle className="h-8 w-8 animate-spin" />
            <p className="mt-4 text-base text-gray-700">Loading...</p>
          </DialogHeader>
        ) : (
          <>
            <DialogHeader>
              <DialogTitle>협력업체 평가 기준 삭제</DialogTitle>
              <DialogDescription>
                정말로 이 협력업체 평가 기준을 삭제하시겠습니까?
                <br />
                <br />
                <strong>삭제될 평가 기준:</strong>
                <br />
                • 평가부문: {REG_EVAL_CRITERIA_CATEGORY.find((c) => c.value === criteriaViewData.category)?.label ?? '-'}
                <br />
                • 점수구분: {REG_EVAL_CRITERIA_CATEGORY2.find((c) => c.value === criteriaViewData.category2)?.label ?? '-'}
                <br />
                • 항목: {REG_EVAL_CRITERIA_ITEM.find((c) => c.value === criteriaViewData.item)?.label ?? '-'}
                <br />
                • 구분: {criteriaViewData.classification || '-'}
                <br />
                • 범위: {criteriaViewData.range || '-'}
                <br />
                <br />
                <b>이 작업은 되돌릴 수 없으며</b>, 평가기준과 그에 속한 <b>{targetData?.criteriaDetails.length}개의 평가항목도 함께 삭제</b>됩니다.
              </DialogDescription>
            </DialogHeader>
            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => onOpenChange(false)}
                disabled={isDeleting}
              >
                Cancel
              </Button>
              <Button
                variant="destructive"
                onClick={handleDelete}
                disabled={isDeleting}
              >
                {isDeleting ? 'Deleting...' : 'Delete'}
              </Button>
            </DialogFooter>
          </>
        )}
      </DialogContent>
    </Dialog>
  )
}

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

/* EXPORT */
export default RegEvalCriteriaDeleteDialog;