"use client";

import React, { useState } from "react";
import { Modal } from "@/components/ui/Modal";
import { Button } from "@/components/ui/Button";
import { Badge } from "@/components/ui/Badge";
import {
  SKLRecord,
  SKLConfig,
  SKLPaperSettings,
  DEFAULT_PAPER_SETTINGS,
} from "@/data/mockSKLData";
import { SKLDocumentSheet } from "./SKLDocumentSheet";
import { SKLPaperSettingsModal } from "./SKLPaperSettingsModal";
import {
  Printer,
  Sliders,
  CheckCircle,
  HelpCircle,
  FileText,
  Maximize2,
  Sparkles,
} from "lucide-react";
import { PrintOrientationToggle } from "@/components/ui/PrintOrientationToggle";
import { triggerPrint, PrintOrientation } from "@/lib/printUtils";

interface SKLPreviewModalProps {
  isOpen: boolean;
  onClose: () => void;
  record: SKLRecord | null;
  config: SKLConfig;
  onPrint: () => void;
  onConfigChange?: (updatedConfig: SKLConfig) => void;
}

export const SKLPreviewModal: React.FC<SKLPreviewModalProps> = ({
  isOpen,
  onClose,
  record,
  config,
  onPrint,
  onConfigChange,
}) => {
  const [isPaperSettingsOpen, setIsPaperSettingsOpen] = useState(false);
  const [activeConfig, setActiveConfig] = useState<SKLConfig>(config);
  const [printOrientation, setPrintOrientation] = useState<PrintOrientation>("portrait");

  React.useEffect(() => {
    setActiveConfig(config);
  }, [config, isOpen]);

  if (!record) return null;

  const currentPaper = activeConfig.paperSettings || DEFAULT_PAPER_SETTINGS;

  const updatePaperSettings = (newPaper: SKLPaperSettings) => {
    const updated = {
      ...activeConfig,
      paperSettings: newPaper,
    };
    setActiveConfig(updated);
    if (onConfigChange) {
      onConfigChange(updated);
    }
  };

  const handleQuickScale = (scale: number) => {
    updatePaperSettings({
      ...currentPaper,
      paperSize: "F4",
      scale,
    });
  };

  const handleToggleStamp = () => {
    const updated = {
      ...activeConfig,
      showStampAndSignature: !activeConfig.showStampAndSignature,
    };
    setActiveConfig(updated);
    if (onConfigChange) {
      onConfigChange(updated);
    }
  };

  return (
    <>
      <Modal
        isOpen={isOpen}
        onClose={onClose}
        title={`Pratinjau SKL — ${record.fullName} (${record.nis})`}
        description="Format resmi Surat Keterangan Lulus (SKL) Kurikulum Merdeka SMA BPI 1 Bandung ukuran kertas F4 (215mm x 330mm)."
        maxWidth="max-w-4xl"
      >
        <div className="space-y-3">
          {/* Quick Paper Settings Toolbar */}
          <div className="p-3 bg-slate-50 border border-slate-200 rounded-xl flex flex-wrap items-center justify-between gap-3 text-xs">
            <div className="flex flex-wrap items-center gap-3">
              {/* Paper Orientation selector */}
              <div className="flex items-center gap-1.5">
                <span className="font-bold text-slate-600">Orientasi:</span>
                <PrintOrientationToggle orientation={printOrientation} onChange={setPrintOrientation} />
              </div>

              {/* Format Resmi F4 Indicator */}
              <div className="flex items-center gap-1.5 px-2.5 py-1 bg-white border border-slate-200 rounded-lg text-slate-700 font-semibold text-xs">
                <span>Kertas: <strong>F4 (215×330 mm)</strong></span>
              </div>

              {/* Scale selector */}
              <div className="flex items-center gap-1.5">
                <span className="font-bold text-slate-600">Skala Cetak:</span>
                <div className="inline-flex rounded-lg border border-slate-200 bg-white p-0.5 font-mono">
                  {[100, 95, 92, 88].map((s) => (
                    <button
                      key={s}
                      type="button"
                      onClick={() => handleQuickScale(s)}
                      className={`px-2 py-1 text-[11px] rounded-md transition-all ${
                        currentPaper.scale === s
                          ? "bg-blue-600 text-white font-bold shadow-xs"
                          : "text-slate-600 hover:text-slate-900"
                      }`}
                    >
                      {s}%
                    </button>
                  ))}
                </div>
              </div>

              {/* Cap & TTD Info */}
              <div className="px-2.5 py-1 text-xs rounded-lg font-medium border bg-amber-50 text-amber-800 border-amber-200 flex items-center gap-1.5">
                <span className="w-2 h-2 rounded-full bg-amber-500" />
                <span>TTD &amp; Cap: <strong>Manual Basah</strong> (Sesuai Standar F4 BPI)</span>
              </div>
            </div>

            <div className="flex items-center gap-2">
              <span className="inline-flex items-center gap-1 text-[11px] font-semibold text-emerald-700 bg-emerald-50 border border-emerald-200 px-2 py-1 rounded-md">
                <CheckCircle className="w-3.5 h-3.5" /> Pas 1 Lembar Utuh
              </span>
              <Button
                type="button"
                variant="outline"
                size="sm"
                className="h-8 text-xs bg-white"
                leftIcon={<Sliders className="w-3.5 h-3.5 text-blue-600" />}
                onClick={() => setIsPaperSettingsOpen(true)}
              >
                Atur Margin &amp; Kertas
              </Button>
            </div>
          </div>

          {/* Document Sheet Display */}
          <div className="max-h-[64vh] overflow-y-auto p-4 bg-slate-100/80 rounded-xl border border-slate-200">
            <SKLDocumentSheet
              record={record}
              config={activeConfig}
              isPrintMode={false}
            />
          </div>

          {/* Tips Info & Modal Action Footer */}
          <div className="pt-2 border-t border-slate-200 space-y-2 print:hidden">
            <div className="flex items-center justify-between text-[11px] text-slate-600 bg-blue-50/70 p-2.5 rounded-lg border border-blue-100">
              <div className="flex items-center gap-2">
                <HelpCircle className="w-4 h-4 text-brand-blue shrink-0" />
                <span>
                  <strong>Tips Cetak:</strong> Pada jendela cetak browser, pilih Margins <strong>Default</strong> dan <strong>hilangkan centang &quot;Headers and footers&quot;</strong> agar tanda tangan dan stempel tidak terpotong.
                </span>
              </div>
            </div>

            <div className="flex items-center justify-between pt-1">
              <p className="text-xs text-slate-500 font-mono">
                Ukuran: {currentPaper.paperSize} • Skala: {currentPaper.scale}% • Mode: {currentPaper.spacing === "compact" ? "Rapat" : "Standar"}
              </p>
              <div className="flex items-center gap-2">
                <Button type="button" variant="outline" size="sm" onClick={onClose}>
                  Tutup
                </Button>
                <Button
                  type="button"
                  variant="primary"
                  size="sm"
                  leftIcon={<Printer className="w-4 h-4" />}
                  onClick={() => {
                    if (typeof document !== "undefined") {
                      document.body.style.overflow = "visible";
                    }
                    triggerPrint(printOrientation);
                    onPrint();
                  }}
                >
                  Cetak Dokumen F4
                </Button>
              </div>
            </div>
          </div>
        </div>
      </Modal>

      {/* Detailed Paper Settings Modal */}
      <SKLPaperSettingsModal
        isOpen={isPaperSettingsOpen}
        onClose={() => setIsPaperSettingsOpen(false)}
        paperSettings={currentPaper}
        onSave={updatePaperSettings}
      />
    </>
  );
};
