import { Button } from '@/components/ui/button';
import { SharedData } from '@/types';
import { usePage } from '@inertiajs/react';
import { XIcon } from '@phosphor-icons/react';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';

const STORAGE_KEY = 'gdpr_consent_accepted';

export default function GdprBanner() {
  const { branding } = usePage<SharedData>().props;
  const { t } = useTranslation();
  const gdpr = branding?.gdpr;

  const [accepted, setAccepted] = useState(
    () => localStorage.getItem(STORAGE_KEY) === '1',
  );

  if (gdpr?.enable_gdpr !== '1' || accepted) return null;

  const handleAccept = () => {
    localStorage.setItem(STORAGE_KEY, '1');
    setAccepted(true);
  };

  return (
    <div className="fixed bottom-4 left-4 z-50 flex max-w-[350px] flex-col items-start gap-2 rounded-2xl border border-black/10 bg-card px-4 py-5 shadow-box md:px-6">
      <Button
        variant="ghost"
        size="icon"
        className="absolute top-2 right-2 ml-auto"
        onClick={handleAccept}
      >
        <XIcon weight="bold" className="size-4 text-black" />
      </Button>

      <h3 className="text-xl font-medium">{t('We use cookies')}</h3>
      <p className="text-sm text-muted-foreground">{gdpr.gdpr_text}</p>

      <div className="mt-2 flex items-center gap-2">
        <Button size="sm" className="w-full" onClick={handleAccept}>
          {t('I agree')}
        </Button>
        {gdpr.gdpr_link && (
          <>
            <Button
              size="sm"
              variant="secondary"
              className="w-full"
              onClick={handleAccept}
            >
              {gdpr.gdpr_button_label || t('Learn more')}
            </Button>
          </>
        )}
      </div>
    </div>
  );
}
