"use client"

import { useState } from "react"
import {
  useConsentCheckQuery,
  useDeleteAccountMutation,
  useGrantConsentMutation,
} from "@/services/consent"
import { signOut } from "next-auth/react"
import { useTranslations } from "next-intl"
import { CheckCircle, Shield } from "lucide-react"

/**
 * DSGVO Consent Banner — fullscreen modal overlay.
 * Shows when a logged-in user has NOT yet granted DATA_PROCESSING consent.
 * Cannot be dismissed without action.
 */
export function ConsentBanner() {
  const t = useTranslations("consent")
  const [marketingChecked, setMarketingChecked] = useState(false)

  const { data: consentCheck, isLoading, isError } = useConsentCheckQuery()
  const grantMutation = useGrantConsentMutation()
  const deleteMutation = useDeleteAccountMutation()

  // Don't show if loading, errored (fail open), or consent already granted
  if (isLoading || isError || consentCheck?.hasDataProcessingConsent) {
    return null
  }

  const handleAccept = async () => {
    // Grant DATA_PROCESSING consent (required)
    await grantMutation.mutateAsync({ type: "DATA_PROCESSING", version: 1 })
    // Grant MARKETING if checked
    if (marketingChecked) {
      await grantMutation.mutateAsync({ type: "MARKETING", version: 1 })
    }
  }

  const handleReject = async () => {
    // Delete account and sign out — dismisses the dialog by leaving the app
    await deleteMutation.mutateAsync()
    await signOut({ callbackUrl: "/login" })
  }

  const isPending = grantMutation.isPending || deleteMutation.isPending

  return (
    <div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/70 backdrop-blur-sm p-4">
      <div className="flex max-h-[min(90vh,600px)] w-full max-w-lg flex-col rounded-xl bg-card shadow-2xl">
        {/* Header — fixed */}
        <div className="flex shrink-0 items-center gap-3 border-b px-6 pt-6 pb-4">
          <Shield className="h-8 w-8 text-primary" />
          <h2 className="text-xl font-semibold">{t("title")}</h2>
        </div>

        {/* Scrollable content */}
        <div className="flex-1 overflow-y-auto px-6 py-4">
          {/* Required: Data Processing */}
          <div className="mb-4 rounded-lg border border-primary/20 bg-primary/5 p-4">
            <h3 className="mb-1 font-medium">{t("dataProcessing")}</h3>
            <p className="text-sm text-muted-foreground">
              {t("dataProcessingDesc")}
            </p>
            <p className="mt-2 text-xs font-medium text-primary">
              {t("required")}
            </p>
          </div>

          {/* Optional: Marketing */}
          <div className="rounded-lg border p-4">
            <label className="flex cursor-pointer items-start gap-3">
              <input
                type="checkbox"
                checked={marketingChecked}
                onChange={(e) => setMarketingChecked(e.target.checked)}
                className="mt-1 h-4 w-4 rounded border-gray-300"
              />
              <div>
                <h3 className="font-medium">{t("marketing")}</h3>
                <p className="text-sm text-muted-foreground">
                  {t("marketingDesc")}
                </p>
              </div>
            </label>
          </div>
        </div>

        {/* Actions — fixed at bottom */}
        <div className="flex shrink-0 flex-col gap-3 border-t px-6 pt-4 pb-6">
          <button
            onClick={handleAccept}
            disabled={isPending}
            className="flex w-full items-center justify-center gap-2 rounded-lg bg-primary px-4 py-3 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-50"
          >
            <CheckCircle className="h-4 w-4" />
            {grantMutation.isPending ? "..." : t("accept")}
          </button>

          <button
            onClick={handleReject}
            disabled={isPending}
            className="w-full text-center text-sm text-destructive underline transition-colors hover:text-destructive/80 disabled:opacity-50"
          >
            {deleteMutation.isPending ? "..." : t("reject")}
          </button>
        </div>
      </div>
    </div>
  )
}
