'use client';

import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { useAction } from 'next-safe-action/hooks';
import { useRouter } from 'next/navigation';
import { Button } from '@kit/ui/button';
import { Input } from '@kit/ui/input';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@kit/ui/form';
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';
import { toast } from '@kit/ui/sonner';
import { CreateNewsletterSchema } from '../schema/newsletter.schema';
import { createNewsletter } from '../server/actions/newsletter-actions';

interface Props {
  accountId: string;
  account: string;
}

export function CreateNewsletterForm({ accountId, account }: Props) {
  const router = useRouter();
  const form = useForm({
    resolver: zodResolver(CreateNewsletterSchema),
    defaultValues: {
      accountId,
      subject: '',
      bodyHtml: '',
      bodyText: '',
      scheduledAt: '',
    },
  });

  const { execute, isPending } = useAction(createNewsletter, {
    onSuccess: ({ data }) => {
      if (data?.success) {
        toast.success('Newsletter erfolgreich erstellt');
        router.push(`/home/${account}/newsletter`);
      }
    },
    onError: ({ error }) => {
      toast.error(error.serverError ?? 'Fehler beim Erstellen des Newsletters');
    },
  });

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit((data) => execute(data))} className="space-y-6">
        <Card>
          <CardHeader><CardTitle>Newsletter-Inhalt</CardTitle></CardHeader>
          <CardContent className="space-y-4">
            <FormField control={form.control} name="subject" render={({ field }) => (
              <FormItem><FormLabel>Betreff *</FormLabel><FormControl><Input {...field} /></FormControl><FormMessage /></FormItem>
            )} />
            <FormField control={form.control} name="bodyHtml" render={({ field }) => (
              <FormItem><FormLabel>Inhalt (HTML) *</FormLabel><FormControl>
                <textarea
                  {...field}
                  rows={12}
                  className="flex min-h-[200px] w-full rounded-md border border-input bg-background px-3 py-2 font-mono text-sm"
                  placeholder="<h1>Hallo!</h1><p>Ihr Newsletter-Inhalt...</p>"
                />
              </FormControl><FormMessage /></FormItem>
            )} />
            <FormField control={form.control} name="bodyText" render={({ field }) => (
              <FormItem><FormLabel>Nur-Text-Version (optional)</FormLabel><FormControl>
                <textarea
                  {...field}
                  rows={4}
                  className="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                  placeholder="Nur-Text-Fallback für E-Mail-Clients ohne HTML-Unterstützung"
                />
              </FormControl><FormMessage /></FormItem>
            )} />
          </CardContent>
        </Card>

        <Card>
          <CardHeader><CardTitle>Zeitplan</CardTitle></CardHeader>
          <CardContent>
            <FormField control={form.control} name="scheduledAt" render={({ field }) => (
              <FormItem>
                <FormLabel>Geplanter Versand (optional)</FormLabel>
                <FormControl><Input type="datetime-local" {...field} /></FormControl>
                <p className="text-xs text-muted-foreground">
                  Leer lassen, um den Newsletter als Entwurf zu speichern.
                </p>
                <FormMessage />
              </FormItem>
            )} />
          </CardContent>
        </Card>

        <div className="flex justify-end gap-2">
          <Button type="button" variant="outline" onClick={() => router.back()}>Abbrechen</Button>
          <Button type="submit" disabled={isPending}>{isPending ? 'Wird erstellt...' : 'Newsletter erstellen'}</Button>
        </div>
      </form>
    </Form>
  );
}
