'use client';

/* IMPORT */
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import { Download, Plus, Trash2, Upload } from 'lucide-react';
import { removeRegEvalCriteria, generateRegEvalCriteriaTemplate, generateRegEvalCriteriaExcel, importRegEvalCriteriaExcel } from '../service';
import { toast } from 'sonner';
import { type RegEvalCriteria } from '@/db/schema';
import { type Table } from '@tanstack/react-table';
import { ChangeEvent, useMemo, useRef, useState } from 'react';

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

/* TYPES */
interface RegEvalCriteriaTableToolbarActionsProps {
  table: Table<RegEvalCriteria>,
  onCreateCriteria: () => void,
  onRefresh: () => void,
}

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

/* REGULAR EVALUATION CRITERIA TABLE TOOLBAR ACTIONS COMPONENT */
function RegEvalCriteriaTableToolbarActions(props: RegEvalCriteriaTableToolbarActionsProps) {
  const { table, onCreateCriteria, onRefresh } = props;
  const [isDeleting, setIsDeleting] = useState<boolean>(false);
  const selectedRows = table.getFilteredSelectedRowModel().rows;
  const hasSelection = selectedRows.length > 0;
  const selectedIds = useMemo(() => {
    return [...new Set(selectedRows.map(row => row.original.id))];
  }, [selectedRows]);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Function for Create New Criteria
  const handleCreateNew = () => {
    onCreateCriteria();
  }

  const handleDeleteSelected = async () => {
    if (!hasSelection) {
      return;
    }
    try {
      setIsDeleting(true);

      for (const selectedId of selectedIds) {
        if (selectedId) {
          await removeRegEvalCriteria(selectedId);
        }
      }
      table.resetRowSelection();
      toast.success(`${selectedIds.length}개의 평가 기준이 삭제되었습니다.`);
      onRefresh();
    } catch (error) {
      console.error('Error in Deleting Regular Evaluation Critria: ', error);
      toast.error(
        error instanceof Error
          ? error.message
          : '평가 기준 삭제 중 오류가 발생했습니다.'
      );
    } finally {
      setIsDeleting(false);
    }
  }

  // Excel Import
  function handleImport() {
    fileInputRef.current?.click();
  };
  async function onFileChange(event: ChangeEvent<HTMLInputElement>) {
    const file = event.target.files?.[0];
    if (!file) {
      toast.error('가져올 파일을 선택해주세요.');
      return;
    }
    if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.xls')) {
      toast.error('.xlsx 또는 .xls 확장자인 Excel 파일만 업로드 가능합니다.');
      return;
    }
    event.target.value = '';

    try {
      const { errorFile, errorMessage, successMessage } = await importRegEvalCriteriaExcel(file);

      if (errorMessage) {
        toast.error(errorMessage);
 
        if (errorFile) {
          const url = URL.createObjectURL(errorFile);
          const link = document.createElement('a');
          link.href = url;
          link.download = 'errors.xlsx';
          link.click();
          URL.revokeObjectURL(url);
        }
      } else {
        toast.success(successMessage || 'Excel 파일이 성공적으로 업로드 되었습니다.');
      }
    } catch (error) {
      toast.error('Excel 파일 업로드 중 오류가 발생했습니다.');
      console.error('Error in Excel File Upload: ', error);
    } finally {
      onRefresh();
    }
  };

  // Excel Export (DB에서 1:n 관계 포함하여 전체 데이터 내보내기)
  const handleExport = async () => {
    try {
      const buffer = await generateRegEvalCriteriaExcel();
      const blob = new Blob([buffer], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = "평가_기준_전체.xlsx";
      link.click();
      URL.revokeObjectURL(url);
      toast.success('Excel 파일이 다운로드되었습니다. (모든 평가내용 포함)');
    } catch (error) {
      console.error('Error in Exporting to Excel: ', error);
      toast.error('Excel 내보내기 중 오류가 발생했습니다.');
    }
  };

  // Excel Template Download
  const handleTemplateDownload = async () => {
    try {
      const buffer = await generateRegEvalCriteriaTemplate();
      const blob = new Blob([buffer], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = "평가_기준_템플릿.xlsx";
      link.click();
      URL.revokeObjectURL(url);
      toast.success('템플릿 파일이 다운로드되었습니다.');
    } catch (error) {
      console.error('Error in Template Download: ', error);
      toast.error('템플릿 다운로드 중 오류가 발생했습니다.');
    }
  };

  return (
    <div className="flex items-center gap-2">
      <Button
        variant="default"
        size="sm"
        className="gap-2"
        onClick={handleCreateNew}
      >
        <Plus className="size-4" aria-hidden="true" />
        <span className="hidden sm:inline">New Criteria</span>
      </Button>
      {hasSelection && (
        <AlertDialog>
          <AlertDialogTrigger asChild>
            <Button
              variant="destructive"
              size="sm"
              className="gap-2"
              disabled={isDeleting}
            >
              <Trash2 className="size-4" aria-hidden="true" />
              <span className="hidden sm:inline">
                선택 삭제 ({selectedIds.length})
              </span>
            </Button>
          </AlertDialogTrigger>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>정말 삭제하시겠습니까?</AlertDialogTitle>
              <AlertDialogDescription>
                선택된 {selectedIds.length}개의 협력업체 평가 기준 항목이 영구적으로 삭제됩니다. 
                이 작업은 되돌릴 수 없으며, 연관된 평가 기준과 항목들도 함께 삭제됩니다.
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>Cancel</AlertDialogCancel>
              <AlertDialogAction
                onClick={handleDeleteSelected}
                className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              >
                {isDeleting ? 'Deleting...' : 'Delete'}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      )}
      <Button
        variant="outline"
        size="sm"
        className="gap-2"
        onClick={handleImport}
      >
        <Upload className="size-4" aria-hidden="true" />
        <span className="hidden sm:inline">Import</span>
      </Button>
      <input
        ref={fileInputRef}
        type="file"
        accept=".xlsx,.xls"
        className="hidden"
        onChange={onFileChange}
      />
      <Button
        variant="outline"
        size="sm"
        onClick={handleExport}
        className="gap-2"
      >
        <Download className="size-4" aria-hidden="true" />
        <span className="hidden sm:inline">Export</span>
      </Button>
      <Button
        variant="outline"
        size="sm"
        onClick={handleTemplateDownload}
        className="gap-2"
      >
        <Download className="size-4" aria-hidden="true" />
        <span className="hidden sm:inline">Template</span>
      </Button>
    </div>
  );
}

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

/* EXPORT */
export default RegEvalCriteriaTableToolbarActions;