import { defineRouteConfig } from "@medusajs/admin-sdk"
import { Container, Heading, Text, Button } from "@medusajs/ui"
import { useEffect, useMemo, useState } from "react"
import { DocumentTextSolid } from "@medusajs/icons"
import { toAbsoluteMediaUrl } from "../../../lib/media-url"
import { CmsLanguageDropdown } from "../../../components/CmsLanguageDropdown"
import Swal from "sweetalert2"

/**
 * The slug of the page whose brochure we are managing.
 */
const SERVICES_PAGE_SLUG = "services"

const getFileTypeLabel = (filename: string, mimeType?: string) => {
    if (mimeType) return mimeType
    const ext = filename.split(".").pop()?.toLowerCase()
    if (!ext) return "unknown"
    return ext.toUpperCase()
}

const uploadFile = async (file: File): Promise<string> => {
    const dataUrl = await new Promise<string>((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = () => resolve(String(reader.result || ""))
        reader.onerror = reject
        reader.readAsDataURL(file)
    })

    const uploadRes = await fetch("/admin/upload", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ file: dataUrl, filename: file.name }),
    })

    const uploadJson = await uploadRes.json()

    if (!uploadRes.ok || !uploadJson?.url) {
        throw new Error(uploadJson?.error || "Upload failed")
    }

    return uploadJson.url as string
}

type PageRecord = {
    id: string
    slug: string
    title: string
    meta: Record<string, unknown> | null
}

const BrochureUploadPage = () => {
    const [page, setPage] = useState<PageRecord | null>(null)
    const [isLoadingPage, setIsLoadingPage] = useState(true)

    const [brochureUrl, setBrochureUrl] = useState("")
    const [brochureFilename, setBrochureFilename] = useState("")
    const [brochureType, setBrochureType] = useState("")

    const [selectedFile, setSelectedFile] = useState<File | null>(null)
    const [isUploading, setIsUploading] = useState(false)
    const [isSaving, setIsSaving] = useState(false)

    // Load the services page on mount
    useEffect(() => {
        const loadPage = async () => {
            try {
                setIsLoadingPage(true)
                const res = await fetch(`/admin/pages`, {
                    credentials: "include",
                })
                const json = await res.json()
                const pages: PageRecord[] = json?.pages ?? []
                const found = pages.find(
                    (p) => (p.slug ?? "").trim().toLowerCase() === SERVICES_PAGE_SLUG
                )
                if (found) {
                    setPage(found)
                    const meta = found.meta || {}
                    setBrochureUrl(
                        (typeof meta.brochure_url === "string" && meta.brochure_url) || ""
                    )
                    setBrochureFilename(
                        (typeof meta.brochure_filename === "string" &&
                            meta.brochure_filename) ||
                        ""
                    )
                    setBrochureType(
                        (typeof meta.brochure_type === "string" && meta.brochure_type) ||
                        ""
                    )
                }
            } catch (err) {
                console.error("Failed to load pages:", err)
            } finally {
                setIsLoadingPage(false)
            }
        }

        loadPage()
    }, [])

    const previewUrl = useMemo(() => toAbsoluteMediaUrl(brochureUrl), [brochureUrl])

    const handleSave = async () => {
        if (!page?.id) {
            await Swal.fire({
                icon: "error",
                title: "Error",
                text: `No "${SERVICES_PAGE_SLUG}" page found. Please create it in the Page Builder first.`,
            })
            return
        }

        setIsSaving(true)

        try {
            let nextUrl = brochureUrl
            let nextFilename = brochureFilename
            let nextType = brochureType

            if (selectedFile) {
                setIsUploading(true)
                nextUrl = await uploadFile(selectedFile)
                nextFilename = selectedFile.name
                nextType = getFileTypeLabel(selectedFile.name, selectedFile.type)
                setIsUploading(false)
            }

            const updatedMeta = {
                ...(page.meta || {}),
                brochure_url: nextUrl,
                brochure_filename: nextFilename,
                brochure_type: nextType,
            }

            const saveRes = await fetch(`/admin/pages/${page.id}`, {
                method: "PUT",
                headers: { "Content-Type": "application/json" },
                credentials: "include",
                body: JSON.stringify({ meta: updatedMeta }),
            })

            if (!saveRes.ok) {
                const err = await saveRes.json().catch(() => ({}))
                throw new Error(err?.message || "Failed to save brochure")
            }

            setBrochureUrl(nextUrl)
            setBrochureFilename(nextFilename)
            setBrochureType(nextType)
            setSelectedFile(null)

            await Swal.fire({
                icon: "success",
                title: "Saved",
                text: "Brochure saved successfully!",
                timer: 1800,
                showConfirmButton: false,
            })
        } catch (error) {
            console.error(error)
            await Swal.fire({
                icon: "error",
                title: "Save Failed",
                text: (error as Error).message || "Something went wrong",
            })
        } finally {
            setIsUploading(false)
            setIsSaving(false)
        }
    }

    const handleRemove = async () => {
        if (!page?.id) return

        const confirm = await Swal.fire({
            icon: "warning",
            title: "Remove Brochure?",
            text: "This will remove the brochure link from the services page.",
            showCancelButton: true,
            confirmButtonText: "Yes, remove",
            cancelButtonText: "Cancel",
        })

        if (!confirm.isConfirmed) return

        setIsSaving(true)
        try {
            const updatedMeta = {
                ...(page.meta || {}),
                brochure_url: "",
                brochure_filename: "",
                brochure_type: "",
            }

            const saveRes = await fetch(`/admin/pages/${page.id}`, {
                method: "PUT",
                headers: { "Content-Type": "application/json" },
                credentials: "include",
                body: JSON.stringify({ meta: updatedMeta }),
            })

            if (!saveRes.ok) {
                const err = await saveRes.json().catch(() => ({}))
                throw new Error(err?.message || "Failed to remove brochure")
            }

            setBrochureUrl("")
            setBrochureFilename("")
            setBrochureType("")
            setSelectedFile(null)

            await Swal.fire({
                icon: "success",
                title: "Removed",
                text: "Brochure removed successfully!",
                timer: 1500,
                showConfirmButton: false,
            })
        } catch (error) {
            console.error(error)
            await Swal.fire({
                icon: "error",
                title: "Failed",
                text: (error as Error).message || "Something went wrong",
            })
        } finally {
            setIsSaving(false)
        }
    }

    const isBusy = isSaving || isUploading

    return (
        <Container className="p-6 max-w-2xl">
            <CmsLanguageDropdown />
            <Heading level="h1" className="mb-2">
                Download Brochure — File Upload
            </Heading>
            <Text size="small" className="text-ui-fg-subtle mb-6">
                Upload the brochure PDF for the Services page. The "Download Brochure"
                button on your website will link to this file.
            </Text>

            {isLoadingPage ? (
                <Text size="small" className="text-ui-fg-subtle">
                    Loading services page...
                </Text>
            ) : !page ? (
                <div className="rounded border border-red-300 bg-red-50 p-4">
                    <Text size="small" className="text-red-700 font-medium">
                        ⚠ Services page not found
                    </Text>
                    <Text size="small" className="text-red-600 mt-1">
                        Please create a page with slug{" "}
                        <code className="bg-red-100 px-1 rounded">
                            {SERVICES_PAGE_SLUG}
                        </code>{" "}
                        in the Page Builder first.
                    </Text>
                </div>
            ) : (
                <div className="flex flex-col gap-6">
                    {/* Current brochure status */}
                    {brochureUrl ? (
                        <div className="rounded border border-ui-border-base bg-ui-bg-subtle p-4 flex flex-col gap-3">
                            <Text size="small" weight="plus">
                                Current Brochure
                            </Text>
                            <div className="flex items-center gap-3 flex-wrap">
                                <Button
                                    variant="secondary"
                                    size="small"
                                    onClick={() =>
                                        window.open(previewUrl, "_blank", "noopener,noreferrer")
                                    }
                                    type="button"
                                >
                                    Preview / Download
                                </Button>
                                <Text size="small" className="text-ui-fg-subtle">
                                    {(brochureFilename || "Uploaded file") +
                                        (brochureType ? ` (${brochureType})` : "")}
                                </Text>
                            </div>
                            <Button
                                variant="transparent"
                                size="small"
                                onClick={handleRemove}
                                disabled={isBusy}
                                type="button"
                                className="self-start text-red-500 hover:text-red-700"
                            >
                                Remove brochure
                            </Button>
                        </div>
                    ) : (
                        <div className="rounded border border-ui-border-base bg-ui-bg-subtle p-4">
                            <Text size="small" className="text-ui-fg-subtle">
                                No brochure uploaded yet. The "Download Brochure" button will
                                not work until a file is uploaded.
                            </Text>
                        </div>
                    )}

                    {/* Upload new file */}
                    <div className="flex flex-col gap-2">
                        <Text size="small" weight="plus">
                            {brochureUrl ? "Replace Brochure" : "Upload Brochure"}
                        </Text>
                        <Text size="small" className="text-ui-fg-subtle">
                            Accepted formats: PDF, DOC, DOCX, PPT, PPTX
                        </Text>
                        <input
                            type="file"
                            accept=".pdf,.doc,.docx,.ppt,.pptx"
                            onChange={(e) => setSelectedFile(e.target.files?.[0] || null)}
                            disabled={isBusy}
                            className="text-sm"
                        />
                        {selectedFile ? (
                            <Text size="small" className="text-ui-fg-subtle">
                                Selected: <strong>{selectedFile.name}</strong> (
                                {(selectedFile.size / 1024).toFixed(1)} KB)
                            </Text>
                        ) : null}
                    </div>

                    <div className="flex justify-end">
                        <Button
                            variant="primary"
                            isLoading={isBusy}
                            onClick={handleSave}
                            disabled={!selectedFile && !brochureUrl}
                        >
                            {selectedFile ? "Upload & Save" : "Save"}
                        </Button>
                    </div>

                    <div className="rounded border border-ui-border-base bg-ui-bg-subtle p-3">
                        <Text size="small" className="text-ui-fg-subtle">
                            <strong>How it works:</strong> After uploading, the file URL is
                            stored in the Services page&apos;s metadata. Your website reads it
                            from{" "}
                            <code className="bg-gray-100 px-1 rounded text-xs">
                                GET /store/pages/services
                            </code>{" "}
                            via{" "}
                            <code className="bg-gray-100 px-1 rounded text-xs">
                                page.meta.brochure_url
                            </code>
                            .
                        </Text>
                    </div>
                </div>
            )}
        </Container>
    )
}

export const config = defineRouteConfig({
    label: "Brochure Upload",
    icon: DocumentTextSolid,
})

export default BrochureUploadPage
