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

import { Globe, ALargeSmall, Settings2, FileSignature, User } from "lucide-react";
import { ModalShell, SaveButton } from "./ModalShell";
import { LANGUAGE_OPTIONS, UserPreferences } from "@/app/types/preferences";
import { usePreferencesStore } from "@/app/store/usePreferencesStore";
import { useMasterDataStore } from "@/app/store/masterDataStore";
import { useState, useEffect } from "react";

export default function SavedPrintInfoModal({
    open,
    onClose,
    initial,
    onSaved,
}: {
    open: boolean;
    onClose: () => void;
    initial: Partial<UserPreferences>;
    onSaved: (updated: Partial<UserPreferences>) => void;
}) {
    const { fetchMasterData } = useMasterDataStore();
    const { savePreferences } = usePreferencesStore();
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState("");

    const [language, setLanguage] = useState(initial.prescription_language || "English");
    const [fontSize, setFontSize] = useState(initial.font_size ?? 12);
    const [showSig, setShowSig] = useState(initial.is_signature_required ?? false);
    const [showDoctor, setShowDoctor] = useState(initial.is_doctor_info_required ?? false);
    useEffect(() => {
        if (!open) return;

        setLanguage(
            initial.prescription_language || "English"
        );

        setFontSize(
            initial.font_size ?? 12
        );

        setShowSig(
            initial.is_signature_required ?? false
        );

        setShowDoctor(
            initial.is_doctor_info_required ?? false
        );
    }, [initial, open]);

    const handleSave = async () => {
        setSaving(true);
        setError("");

        const payload = {
            prescription_language: language,
            font_size: fontSize,
            is_signature_required: showSig,
            is_doctor_info_required: showDoctor,
        };

        const success = await savePreferences(payload as any);

        setSaving(false);

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

        await fetchMasterData();

        onSaved(payload);

        onClose();
    };



    return (
        <ModalShell
            open={open}
            onClose={onClose}
            footer={
                <div>
                    {error && (
                        <p className="text-sm text-[#ef4444] text-center mb-3">{error}</p>
                    )}
                    <SaveButton onClick={handleSave} loading={saving} label="Save" />
                </div>
            }
        >
            <div className="px-6 pt-8 pb-4">
                <h2 className="text-xl font-bold text-[#d4537e] border-b-2 border-[#d4537e] pb-2 inline-block mb-6">
                    Saved Print information
                </h2>

                {/* Prescription Language */}
                <Section icon={<Globe size={18} />} title="Prescription language">
                    <p className="text-sm text-[#6b7280] mb-4">Select the language for printed prescriptions</p>
                    <div className="flex flex-wrap gap-2">
                        {LANGUAGE_OPTIONS.map((lang) => (
                            <button
                                key={lang}
                                onClick={() => setLanguage(lang)}
                                className={`px-5 py-2 rounded-full text-sm font-medium border cursor-pointer transition-all ${language === lang
                                    ? "border-[#d4537e] bg-[#fceef3] text-[#d4537e]"
                                    : "border-[#e5e7eb] bg-white text-[#374151] hover:border-[#d4537e]"
                                    }`}
                            >
                                {lang}
                            </button>
                        ))}
                    </div>
                </Section>

                {/* Font Size */}
                <Section icon={<ALargeSmall size={18} />} title="Font Size">
                    <p className="text-sm text-[#6b7280] mb-5">Adjust text size for printed prescriptions</p>
                    <div className="flex items-center gap-3">
                        <span className="text-sm text-[#9ca3af]">A</span>
                        <div className="flex-1 relative">
                            <input
                                type="range"
                                min={8}
                                max={16}
                                step={1}
                                value={fontSize}
                                onChange={(e) => setFontSize(Number(e.target.value))}
                                className="w-full accent-[#d4537e] cursor-pointer"
                            />
                        </div>
                        <span className="text-lg text-[#374151] font-semibold">A</span>
                        <div className="bg-[#fceef3] border border-[#f3c7d6] rounded-xl px-3 py-1.5 min-w-[60px] text-center">
                            <span className="text-base font-bold text-[#d4537e]">{fontSize}</span>
                            <span className="text-xs text-[#d4537e] ml-0.5">px</span>
                        </div>
                    </div>
                    <div className="flex justify-between mt-1.5 text-xs text-[#9ca3af]">
                        <span>8 px (small)</span>
                        <span>16 px (large)</span>
                    </div>
                </Section>

                {/* Other Settings */}
                <Section icon={<Settings2 size={18} />} title="Other Settings">
                    <ToggleRow
                        icon={<FileSignature size={18} />}
                        title="Show signature box on prescription"
                        sub="signature box at the bottom of every prescription"
                        checked={showSig}
                        onChange={setShowSig}
                    />
                    <div className="border-t border-[#f3f4f6] my-1" />
                    <ToggleRow
                        icon={<User size={18} />}
                        title="Show Doctor Info in Prescription"
                        sub="show doctor's name, title, degree and specialty in the prescription header"
                        checked={showDoctor}
                        onChange={setShowDoctor}
                    />
                </Section>
            </div>
        </ModalShell>
    );
}

function Section({
    icon,
    title,
    children,
}: {
    icon: React.ReactNode;
    title: string;
    children: React.ReactNode;
}) {
    return (
        <div className="bg-white border border-[#e5e7eb] rounded-2xl p-5 mb-4">
            <div className="flex items-center gap-2.5 mb-4">
                <span className="text-[#d4537e]">{icon}</span>
                <p className="text-base font-semibold text-[#111111]">{title}</p>
            </div>
            {children}
        </div>
    );
}

function ToggleRow({
    icon,
    title,
    sub,
    checked,
    onChange,
}: {
    icon: React.ReactNode;
    title: string;
    sub: string;
    checked: boolean;
    onChange: (v: boolean) => void;
}) {
    return (
        <div className="flex items-start gap-3 py-3">
            <div className="w-9 h-9 rounded-xl bg-[#fceef3] text-[#d4537e] flex items-center justify-center flex-shrink-0 mt-0.5">
                {icon}
            </div>
            <div className="flex-1 min-w-0">
                <p className="text-sm font-semibold text-[#111111]">{title}</p>
                <p className="text-xs text-[#9ca3af] mt-0.5 leading-snug">{sub}</p>
            </div>
            {/* Toggle switch */}
            <button
                onClick={() => onChange(!checked)}
                className={`relative w-12 h-6 rounded-full cursor-pointer transition-colors flex-shrink-0 mt-1 ${checked ? "bg-[#d4537e]" : "bg-[#9ca3af]"
                    }`}
            >
                <span
                    className={`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full shadow transition-transform ${checked ? "translate-x-6" : "translate-x-0"
                        }`}
                />
            </button>
        </div>
    );
}