'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { useLocale } from 'next-intl';
import { motion } from 'framer-motion';
import { Loader2, Palette, ArrowRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { useToast } from '@/hooks/use-toast';

export default function BrandingPage() {
  const t = useTranslations('installer.branding');
  const router = useRouter();
  const locale = useLocale();
  const { toast } = useToast();

  const [form, setForm] = useState({ appName: 'tOS', companyName: '', logoUrl: '' });
  const [isLoading, setIsLoading] = useState(false);

  const handleSave = async () => {
    setIsLoading(true);
    const token = sessionStorage.getItem('setup-token') ?? '';
    const apiUrl = process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:3001/api/v1';

    try {
      const body: Record<string, string> = { appName: form.appName };
      if (form.companyName) body.companyName = form.companyName;
      if (form.logoUrl) body.logoUrl = form.logoUrl;

      const res = await fetch(`${apiUrl}/setup/branding`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'x-setup-token': token,
        },
        body: JSON.stringify(body),
      });

      if (!res.ok) throw new Error(`Error ${res.status}`);
      router.push(`/${locale}/setup/complete`);
    } catch (err) {
      toast({
        title: 'Fehler',
        description: err instanceof Error ? err.message : 'Unbekannter Fehler',
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleSkip = () => router.push(`/${locale}/setup/complete`);

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
    >
      <Card>
        <CardHeader>
          <CardTitle>{t('title')}</CardTitle>
          <CardDescription>{t('description')}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          <div className="space-y-2">
            <Label htmlFor="appName">{t('appName')}</Label>
            <Input
              id="appName"
              placeholder={t('appNamePlaceholder')}
              value={form.appName}
              onChange={(e) => setForm((f) => ({ ...f, appName: e.target.value }))}
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="companyName">{t('companyName')}</Label>
            <Input
              id="companyName"
              placeholder={t('companyNamePlaceholder')}
              value={form.companyName}
              onChange={(e) => setForm((f) => ({ ...f, companyName: e.target.value }))}
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="logoUrl">{t('logoUrl')}</Label>
            <Input
              id="logoUrl"
              type="url"
              placeholder={t('logoUrlPlaceholder')}
              value={form.logoUrl}
              onChange={(e) => setForm((f) => ({ ...f, logoUrl: e.target.value }))}
            />
            {form.logoUrl && (
              <div className="mt-3 p-3 border rounded-lg bg-muted/30">
                <p className="text-xs text-muted-foreground mb-2">{t('logoPreview')}</p>
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src={form.logoUrl}
                  alt="Logo Preview"
                  className="h-12 max-w-48 object-contain"
                  onError={(e) => {
                    (e.target as HTMLImageElement).style.display = 'none';
                  }}
                />
              </div>
            )}
          </div>

          <div className="flex justify-between pt-2">
            <Button variant="ghost" onClick={handleSkip}>
              {t('skip')}
            </Button>
            <Button onClick={handleSave} disabled={isLoading || !form.appName.trim()}>
              {isLoading ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  {t('saving')}
                </>
              ) : (
                <>
                  <Palette className="mr-2 h-4 w-4" />
                  {t('save')}
                  <ArrowRight className="ml-2 h-4 w-4" />
                </>
              )}
            </Button>
          </div>
        </CardContent>
      </Card>
    </motion.div>
  );
}
