"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import {
  useConsentsQuery,
  useDeleteAccountMutation,
  useExportDataMutation,
  useGrantConsentMutation,
  useRevokeConsentMutation,
} from "@/services/consent"
import { useTranslations } from "next-intl"
import { Download, Shield, ToggleLeft, ToggleRight, Trash2 } from "lucide-react"

export default function PrivacySettingsPage() {
  const t = useTranslations("dsgvo")
  const tc = useTranslations("consent")
  const router = useRouter()
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)

  const { data: consents, isLoading } = useConsentsQuery()
  const grantMutation = useGrantConsentMutation()
  const revokeMutation = useRevokeConsentMutation()
  const exportMutation = useExportDataMutation()
  const deleteMutation = useDeleteAccountMutation()

  const consentTypes = [
    {
      type: "DATA_PROCESSING" as const,
      label: tc("dataProcessing"),
      description: tc("dataProcessingDesc"),
      required: true,
    },
    {
      type: "MARKETING" as const,
      label: tc("marketing"),
      description: tc("marketingDesc"),
      required: false,
    },
    {
      type: "ANALYTICS" as const,
      label: "Analytics",
      description: "Nutzungsanalysen zur Verbesserung des Dienstes.",
      required: false,
    },
  ]

  const isGranted = (type: string) =>
    consents?.find((c) => c.type === type)?.granted ?? false

  const getGrantedDate = (type: string) =>
    consents?.find((c) => c.type === type)?.grantedAt

  const handleToggle = async (type: string, currentlyGranted: boolean) => {
    if (currentlyGranted) {
      if (type === "DATA_PROCESSING") {
        setShowDeleteConfirm(true)
        return
      }
      await revokeMutation.mutateAsync(type)
    } else {
      await grantMutation.mutateAsync({
        type: type as "DATA_PROCESSING" | "MARKETING" | "ANALYTICS",
        version: 1,
      })
    }
  }

  const handleExport = () => {
    exportMutation.mutate()
  }

  const handleDelete = async () => {
    await deleteMutation.mutateAsync()
    router.push("/login")
  }

  return (
    <div className="mx-auto max-w-2xl space-y-8 p-6">
      <div className="flex items-center gap-3">
        <Shield className="h-6 w-6 text-primary" />
        <h1 className="text-2xl font-bold">{t("title")}</h1>
      </div>

      {/* Consent Toggles */}
      <section className="space-y-4">
        <h2 className="text-lg font-semibold">{tc("title")}</h2>
        {isLoading ? (
          <div className="animate-pulse space-y-3">
            {[1, 2, 3].map((i) => (
              <div key={i} className="h-20 rounded-lg bg-muted" />
            ))}
          </div>
        ) : (
          consentTypes.map((ct) => {
            const granted = isGranted(ct.type)
            const grantedDate = getGrantedDate(ct.type)
            return (
              <div
                key={ct.type}
                className="flex items-start justify-between rounded-lg border p-4"
              >
                <div className="flex-1">
                  <div className="flex items-center gap-2">
                    <h3 className="font-medium">{ct.label}</h3>
                    {ct.required && (
                      <span className="rounded bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary">
                        {tc("required")}
                      </span>
                    )}
                  </div>
                  <p className="mt-1 text-sm text-muted-foreground">
                    {ct.description}
                  </p>
                  {granted && grantedDate && (
                    <p className="mt-1 text-xs text-muted-foreground">
                      {tc("granted")}{" "}
                      {new Date(grantedDate).toLocaleDateString("de-DE")}
                    </p>
                  )}
                </div>
                <button
                  onClick={() => handleToggle(ct.type, granted)}
                  disabled={grantMutation.isPending || revokeMutation.isPending}
                  className="ml-4 shrink-0"
                  aria-label={granted ? tc("revoke") : tc("accept")}
                >
                  {granted ? (
                    <ToggleRight className="h-8 w-8 text-primary" />
                  ) : (
                    <ToggleLeft className="h-8 w-8 text-muted-foreground" />
                  )}
                </button>
              </div>
            )
          })
        )}
      </section>

      {/* Data Export */}
      <section className="space-y-3 rounded-lg border p-4">
        <div className="flex items-center gap-2">
          <Download className="h-5 w-5" />
          <h2 className="text-lg font-semibold">{t("export")}</h2>
        </div>
        <p className="text-sm text-muted-foreground">{t("exportDesc")}</p>
        <button
          onClick={handleExport}
          disabled={exportMutation.isPending}
          className="inline-flex items-center gap-2 rounded-lg bg-secondary px-4 py-2 text-sm font-medium transition-colors hover:bg-secondary/80 disabled:opacity-50"
        >
          <Download className="h-4 w-4" />
          {exportMutation.isPending ? t("exporting") : t("exportButton")}
        </button>
        {exportMutation.isSuccess && (
          <p className="text-sm text-green-600">{t("exported")}</p>
        )}
      </section>

      {/* Account Deletion */}
      <section className="space-y-3 rounded-lg border border-destructive/30 bg-destructive/5 p-4">
        <div className="flex items-center gap-2">
          <Trash2 className="h-5 w-5 text-destructive" />
          <h2 className="text-lg font-semibold text-destructive">
            {t("delete")}
          </h2>
        </div>
        <p className="text-sm text-muted-foreground">{t("deleteDesc")}</p>

        {!showDeleteConfirm ? (
          <button
            onClick={() => setShowDeleteConfirm(true)}
            className="inline-flex items-center gap-2 rounded-lg bg-destructive px-4 py-2 text-sm font-medium text-destructive-foreground transition-colors hover:bg-destructive/90"
          >
            <Trash2 className="h-4 w-4" />
            {t("deleteButton")}
          </button>
        ) : (
          <div className="space-y-3 rounded-lg border border-destructive/50 bg-destructive/10 p-4">
            <p className="text-sm font-medium text-destructive">
              {t("deleteConfirm")}
            </p>
            <div className="flex gap-3">
              <button
                onClick={handleDelete}
                disabled={deleteMutation.isPending}
                className="inline-flex items-center gap-2 rounded-lg bg-destructive px-4 py-2 text-sm font-medium text-destructive-foreground transition-colors hover:bg-destructive/90 disabled:opacity-50"
              >
                {deleteMutation.isPending ? "..." : t("deleteButton")}
              </button>
              <button
                onClick={() => setShowDeleteConfirm(false)}
                className="rounded-lg border px-4 py-2 text-sm font-medium transition-colors hover:bg-muted"
              >
                Abbrechen
              </button>
            </div>
          </div>
        )}
      </section>
    </div>
  )
}
