"use client";
// components/modals/ui/PaperSizeWizardModal.tsx

import { ModalShell, StepProgress, StepEyebrow, InfoBanner, SaveButton } from "./ModalShell";
import { PAGE_SIZE_OPTIONS, PageSize, UserPreferences } from "@/app/types/preferences";
import { usePreferencesStore } from "@/app/store/usePreferencesStore";
import { useMasterDataStore } from "@/app/store/masterDataStore";
import { useState, useEffect } from "react";

interface WizardState {
    selectedSize: PageSize;
    usePrintedLetterpad: boolean;
    headerMm: string;
    footerMm: string;
    leftMm: string;
    rightMm: string;
}

const TOTAL_STEPS = 4;

export default function PaperSizeWizardModal({

    open,
    onClose,
    initial,
    onSaved,
}: {
    open: boolean;
    onClose: () => void;
    initial: Partial<UserPreferences>;
    /** Called after successful save — parent opens Print Info modal */
    onSaved: (updated: Partial<UserPreferences>) => void;
}) {
    const { fetchMasterData } = useMasterDataStore();
    const { savePreferences } = usePreferencesStore();
    const [step, setStep] = useState(1);
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState("");

    const [state, setState] = useState<WizardState>(() => ({
        selectedSize: (initial.page_size as PageSize) ?? "A4",
        usePrintedLetterpad: initial.printed_letterhead ?? true,

        headerMm: String(initial.page_header_size_mm ?? 42),
        footerMm: String(initial.page_footer_size_mm ?? 30),
        leftMm: String(initial.page_left_side_spacing ?? 8),
        rightMm: String(initial.page_right_side_spacing ?? 8),
    }));

    const patch = (p: Partial<WizardState>) => setState((s) => ({ ...s, ...p }));

    const handleClose = () => {
        setStep(1);
        setError("");
        onClose();
    };

    const canNext = () => {
        if (step === 1) return !!state.selectedSize;
        if (step === 3) return state.headerMm !== "" && state.footerMm !== "";
        if (step === 4) return state.leftMm !== "" && state.rightMm !== "";
        return true;
    };

    const handleNext = async () => {
        setError("");

        if (step < TOTAL_STEPS) {
            setStep(step + 1);
            return;
        }

        setSaving(true);

        const payload = {
            page_size: state.selectedSize,
            page_header_size_mm: Number(state.headerMm),
            page_footer_size_mm: Number(state.footerMm),
            page_left_side_spacing: Number(state.leftMm),
            page_right_side_spacing: Number(state.rightMm),
            printed_letterhead: state.usePrintedLetterpad,
        };

        const success = await savePreferences(payload as any);

        setSaving(false);

        if (!success) {
            setError("Could not save preferences.");
            return;
        }

        await fetchMasterData();

        handleClose();

        onSaved(payload);
    };
    useEffect(() => {
        if (!open) return;

        setState({
            selectedSize: (initial.page_size as PageSize) ?? "A4",
            usePrintedLetterpad: initial.printed_letterhead ?? true,
            
            headerMm: String(initial.page_header_size_mm ?? 42),
            footerMm: String(initial.page_footer_size_mm ?? 30),
            leftMm: String(initial.page_left_side_spacing ?? 8),
            rightMm: String(initial.page_right_side_spacing ?? 8),
        });

        setStep(1);
    }, [initial, open]);

    return (
        <ModalShell
            open={open}
            onClose={handleClose}
            footer={
                <div>
                    {error && (
                        <p className="text-sm text-[#ef4444] text-center mb-3">{error}</p>
                    )}
                    <SaveButton
                        onClick={handleNext}
                        loading={saving}
                        disabled={!canNext()}
                        label={step < TOTAL_STEPS ? "Next" : "Save"}
                    />
                </div>
            }
        >
            <StepProgress step={step} total={TOTAL_STEPS} />

            {step === 1 && (
                <Step1PaperSize
                    selected={state.selectedSize}
                    onSelect={(s) => patch({ selectedSize: s })}
                />
            )}
            {step === 2 && (
                <Step2PageType
                    usePrinted={state.usePrintedLetterpad}
                    onSelect={(v) => patch({ usePrintedLetterpad: v })}
                />
            )}
            {step === 3 && (
                <Step3Margins
                    headerMm={state.headerMm}
                    footerMm={state.footerMm}
                    onChange={patch}
                />
            )}
            {step === 4 && (
                <Step4Horizontal
                    leftMm={state.leftMm}
                    rightMm={state.rightMm}
                    onChange={patch}
                />
            )}
        </ModalShell>
    );
}

// ─────────────────────────────────────────────────────────────────────────────
// Step 1 — Paper size grid
// ─────────────────────────────────────────────────────────────────────────────
function Step1PaperSize({
    selected,
    onSelect,
}: {
    selected: PageSize;
    onSelect: (s: PageSize) => void;
}) {
    return (
        <div className="pb-4">
            <StepEyebrow>STEP 1 · PAPER SIZE</StepEyebrow>
            <div className="px-6 mt-5 text-center">
                <h2 className="text-2xl font-bold text-[#111111] leading-snug">
                    What paper are you<br />printing on?
                </h2>
                <p className="text-sm text-[#6b7280] mt-2">Choose the paper your clinic printer uses.</p>
            </div>

            <div className="grid grid-cols-3 gap-3 px-6 mt-6">
                {PAGE_SIZE_OPTIONS.map((opt: typeof PAGE_SIZE_OPTIONS[number]) => {
                    const active = selected === opt.label;
                    return (
                        <button
                            key={opt.label}
                            onClick={() => onSelect(opt.label)}
                            className={`flex flex-col items-center rounded-2xl py-4 px-2 border-2 cursor-pointer transition-all ${active
                                ? "border-[#d4537e] bg-[#fceef3]"
                                : "border-transparent bg-[#ececef] hover:bg-[#e2e2e6]"
                                }`}
                        >
                            {/* Paper icon */}
                            <div className={`w-10 h-13 rounded-sm shadow-sm flex flex-col p-1.5 gap-0.5 mb-2 ${active ? "bg-white" : "bg-white"}`}>
                                <div className="w-full h-[2.5px] rounded-full bg-[#d1d5db]" />
                                <div className="w-3/4 h-[2.5px] rounded-full bg-[#d1d5db]" />
                                <div className="w-full h-[2.5px] rounded-full bg-[#d1d5db]" />
                                <div className="w-2/3 h-[2.5px] rounded-full bg-[#d1d5db]" />
                            </div>
                            <p className={`text-sm font-semibold ${active ? "text-[#d4537e]" : "text-[#111111]"}`}>
                                {opt.label}
                            </p>
                            <p className="text-[9px] text-[#9ca3af] text-center mt-0.5 leading-tight">
                                {opt.dims}
                            </p>
                        </button>
                    );
                })}
            </div>

            <InfoBanner>
                Most clinics use A4 for full prescriptions and A5 for short visits. If your printer
                tray is different, choose accordingly.
            </InfoBanner>
        </div>
    );
}

// ─────────────────────────────────────────────────────────────────────────────
// Step 2 — Page type (Plain vs Printed letterpad)
// ─────────────────────────────────────────────────────────────────────────────
function Step2PageType({
    usePrinted,
    onSelect,
}: {
    usePrinted: boolean;
    onSelect: (v: boolean) => void;
}) {
    return (
        <div className="pb-4">
            <StepEyebrow>STEP 2 · PAGE TYPE</StepEyebrow>
            <div className="px-6 mt-5 text-center">
                <h2 className="text-2xl font-bold text-[#111111] leading-snug">
                    What type of page<br />are you printing on?
                </h2>
                <p className="text-sm text-[#6b7280] mt-2">
                    This helps us know whether to print your header & footer.
                </p>
            </div>

            <div className="flex flex-col gap-3 px-6 mt-6">
                {/* Plain page */}
                <button
                    onClick={() => onSelect(false)}
                    className={`flex items-center gap-4 text-left rounded-2xl p-4 border-2 w-full cursor-pointer transition-all ${!usePrinted
                        ? "border-[#d4537e] bg-[#fceef3]"
                        : "border-transparent bg-[#ececef] hover:bg-[#e2e2e6]"
                        }`}
                >
                    {/* Plain page illustration */}
                    <div className="w-12 h-14 rounded bg-white shadow-sm flex flex-col items-center p-1.5 gap-0.5 flex-shrink-0">
                        <div className="w-full h-[2.5px] rounded-full bg-[#d1d5db]" />
                        <div className="w-3/4 h-[2.5px] rounded-full bg-[#d1d5db]" />
                        <div className="w-full h-[2.5px] rounded-full bg-[#d1d5db]" />
                        <div className="w-2/3 h-[2.5px] rounded-full bg-[#d1d5db]" />
                    </div>
                    <div>
                        <p className="text-base font-semibold text-[#111111]">Plain page</p>
                        <p className="text-sm text-[#9ca3af] mt-0.5">
                            Header & footer will be printed on every prescription
                        </p>
                    </div>
                </button>

                {/* Printed letterpad */}
                <button
                    onClick={() => onSelect(true)}
                    className={`flex items-center gap-4 text-left rounded-2xl p-4 border-2 w-full cursor-pointer transition-all ${usePrinted
                        ? "border-[#d4537e] bg-[#fceef3]"
                        : "border-transparent bg-[#ececef] hover:bg-[#e2e2e6]"
                        }`}
                >
                    {/* Letterpad illustration */}
                    <div className="w-12 h-14 rounded bg-white shadow-sm flex flex-col overflow-hidden flex-shrink-0">
                        <div className="h-3 bg-[#fceef3] border-b border-[#f3c7d6]" />
                        <div className="flex-1 flex flex-col justify-center gap-0.5 px-1.5">
                            <div className="w-full h-[2px] rounded-full bg-[#d1d5db]" />
                            <div className="w-3/4 h-[2px] rounded-full bg-[#d1d5db]" />
                            <div className="w-full h-[2px] rounded-full bg-[#d1d5db]" />
                        </div>
                        <div className="h-2.5 bg-[#fceef3] border-t border-[#f3c7d6]" />
                    </div>
                    <div className="flex-1">
                        <p className="text-base font-semibold text-[#111111]">Printed letterpad</p>
                        <p className="text-sm text-[#9ca3af] mt-0.5">
                            My paper already has header & footer printed on it
                        </p>
                    </div>
                    {usePrinted && (
                        <span className="text-[#d4537e] text-lg font-bold flex-shrink-0">✓</span>
                    )}
                </button>
            </div>
        </div>
    );
}

// ─────────────────────────────────────────────────────────────────────────────
// Step 3 — Header & footer margins
// ─────────────────────────────────────────────────────────────────────────────
function Step3Margins({
    headerMm,
    footerMm,
    onChange,
}: {
    headerMm: string;
    footerMm: string;
    onChange: (p: { headerMm?: string; footerMm?: string }) => void;
}) {
    return (
        <div className="pb-4">
            <StepEyebrow>STEP 3 · MARGINS</StepEyebrow>
            <div className="px-6 mt-5 text-center">
                <h2 className="text-2xl font-bold text-[#111111] leading-snug">
                    Where is your<br />Header & Footer
                </h2>
                <p className="text-sm text-[#6b7280] mt-2">
                    Use a ruler on your printed paper and enter the height in mm.
                </p>
            </div>

            {/* Illustration */}
            <div className="mx-6 mt-6 bg-[#ececef] rounded-2xl p-5 flex items-center gap-5">
                <div className="w-20 h-28 rounded bg-white shadow-sm flex flex-col overflow-hidden flex-shrink-0">
                    <div className="h-6 bg-[#fceef3] border-b-2 border-[#d4537e] relative">
                        <div className="absolute right-1 top-0 bottom-0 flex items-center">
                            <span className="text-[8px] text-[#d4537e]">↕</span>
                        </div>
                    </div>
                    <div className="flex-1 flex flex-col justify-center gap-1 px-2">
                        {[1, 2, 3, 4, 5].map((i) => (
                            <div key={i} className="w-full h-[2px] bg-[#d1d5db] rounded-full" />
                        ))}
                    </div>
                    <div className="h-5 bg-[#fceef3] border-t-2 border-[#d4537e] relative">
                        <div className="absolute right-1 top-0 bottom-0 flex items-center">
                            <span className="text-[8px] text-[#d4537e]">↕</span>
                        </div>
                    </div>
                </div>
                <div className="flex flex-col gap-4 text-sm text-[#374151] flex-1">
                    <p>↕ Measure top edge to where header ends</p>
                    <div className="border-t border-[#e5e7eb]" />
                    <p>↕ Measure footer start to bottom edge</p>
                </div>
            </div>

            {/* Inputs */}
            <div className="grid grid-cols-2 gap-3 px-6 mt-5">
                <MmInput
                    label="Header Spacing (mm)"
                    value={headerMm}
                    onChange={(v) => onChange({ headerMm: v })}
                />
                <MmInput
                    label="Footer Spacing (mm)"
                    value={footerMm}
                    onChange={(v) => onChange({ footerMm: v })}
                />
            </div>

            <InfoBanner>
                Measure from the paper edge to where the printed content begins. Common: header 20–30 mm,
                footer 10–20 mm.
            </InfoBanner>
        </div>
    );
}

// ─────────────────────────────────────────────────────────────────────────────
// Step 4 — Horizontal spacing (left / right)
// ─────────────────────────────────────────────────────────────────────────────
function Step4Horizontal({
    leftMm,
    rightMm,
    onChange,
}: {
    leftMm: string;
    rightMm: string;
    onChange: (p: { leftMm?: string; rightMm?: string }) => void;
}) {
    return (
        <div className="pb-4">
            <StepEyebrow>STEP 4 · HORIZONTAL SPACING</StepEyebrow>
            <div className="px-6 mt-5 text-center">
                <h2 className="text-2xl font-bold text-[#111111] leading-snug">
                    What is your<br />Horizontal Spacing
                </h2>
                <p className="text-sm text-[#6b7280] mt-2">
                    Use a ruler on your printed paper and enter the width in mm.
                </p>
            </div>

            {/* Illustration */}
            <div className="mx-6 mt-6 bg-[#ececef] rounded-2xl p-6 flex justify-center">
                <div className="w-36 h-40 rounded bg-white shadow-sm flex flex-col overflow-hidden">
                    <div className="h-5 bg-[#fceef3] border-b-2 border-[#d4537e]" />
                    <div className="flex-1 flex">
                        <div className="w-3 bg-[#dbeafe] border-r border-[#93c5fd] flex items-center justify-center">
                            <span className="text-[7px] text-[#3b82f6] rotate-90">←→</span>
                        </div>
                        <div className="flex-1 flex flex-col justify-center gap-1 px-1.5">
                            {[1, 2, 3, 4, 5, 6].map((i) => (
                                <div key={i} className="w-full h-[2px] bg-[#d1d5db] rounded-full" />
                            ))}
                        </div>
                        <div className="w-3 bg-[#dbeafe] border-l border-[#93c5fd] flex items-center justify-center">
                            <span className="text-[7px] text-[#3b82f6] -rotate-90">←→</span>
                        </div>
                    </div>
                    <div className="h-4 bg-[#fceef3] border-t-2 border-[#d4537e]" />
                </div>
            </div>

            <div className="grid grid-cols-2 gap-3 px-6 mt-5">
                <MmInput
                    label="Left side spacing (in mm)"
                    value={leftMm}
                    onChange={(v) => onChange({ leftMm: v })}
                />
                <MmInput
                    label="Right side spacing (in mm)"
                    value={rightMm}
                    onChange={(v) => onChange({ rightMm: v })}
                />
            </div>

            <InfoBanner>Measure from the paper edge to where the printed content begins.</InfoBanner>
        </div>
    );
}

function MmInput({
    label,
    value,
    onChange,
}: {
    label: string;
    value: string;
    onChange: (v: string) => void;
}) {
    return (
        <div className="bg-[#ececef] rounded-xl px-4 py-3">
            <label className="text-[11px] text-[#6b7280] block mb-1">{label}</label>
            <input
                type="number"
                inputMode="decimal"
                value={value}
                onChange={(e) => onChange(e.target.value)}
                placeholder="0"
                className="w-full bg-transparent text-lg font-semibold text-[#111111] outline-none"
            />
        </div>
    );
}