"use client";

import { Button } from "@/components/ui/button";
import { Save, Eye, RotateCcw, ArrowLeft, Loader2 } from "lucide-react";
import { useRouter } from "next/navigation";
import { useReportDesigner } from "@/contexts/ReportDesignerContext";
import { useState } from "react";
import { ReportPreviewModal } from "./ReportPreviewModal";

export function ReportDesignerToolbar() {
  const router = useRouter();
  const { reportDetail, saveLayout, isSaving, loadLayout } = useReportDesigner();
  const [showPreview, setShowPreview] = useState(false);

  const handleSave = async () => {
    await saveLayout();
  };

  const handleReset = async () => {
    if (confirm("현재 변경사항을 모두 취소하고 마지막 저장 상태로 되돌리시겠습니까?")) {
      await loadLayout();
    }
  };

  const handleBack = () => {
    if (confirm("저장하지 않은 변경사항이 있을 수 있습니다. 목록으로 돌아가시겠습니까?")) {
      router.push("/admin/report");
    }
  };

  return (
    <>
      <div className="flex items-center justify-between border-b bg-white px-4 py-3 shadow-sm">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="sm" onClick={handleBack} className="gap-2">
            <ArrowLeft className="h-4 w-4" />
            목록으로
          </Button>
          <div className="h-6 w-px bg-gray-300" />
          <div>
            <h2 className="text-lg font-semibold text-gray-900">
              {reportDetail?.report.report_name_kor || "리포트 디자이너"}
            </h2>
            {reportDetail?.report.report_name_eng && (
              <p className="text-sm text-gray-500">{reportDetail.report.report_name_eng}</p>
            )}
          </div>
        </div>

        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm" onClick={handleReset} className="gap-2">
            <RotateCcw className="h-4 w-4" />
            초기화
          </Button>
          <Button variant="outline" size="sm" onClick={() => setShowPreview(true)} className="gap-2">
            <Eye className="h-4 w-4" />
            미리보기
          </Button>
          <Button size="sm" onClick={handleSave} disabled={isSaving} className="gap-2">
            {isSaving ? (
              <>
                <Loader2 className="h-4 w-4 animate-spin" />
                저장 중...
              </>
            ) : (
              <>
                <Save className="h-4 w-4" />
                저장
              </>
            )}
          </Button>
        </div>
      </div>

      <ReportPreviewModal isOpen={showPreview} onClose={() => setShowPreview(false)} />
    </>
  );
}
