'use client';

import { useState } from 'react';

import { useRouter } from 'next/navigation';

import { Plus } from 'lucide-react';

import { createSession } from '@kit/course-management/actions/course-actions';
import { Button } from '@kit/ui/button';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@kit/ui/dialog';
import { Input } from '@kit/ui/input';
import { Label } from '@kit/ui/label';
import { useActionWithToast } from '@kit/ui/use-action-with-toast';

interface Props {
  courseId: string;
}

export function CreateSessionDialog({ courseId }: Props) {
  const router = useRouter();
  const [open, setOpen] = useState(false);

  const { execute, isPending } = useActionWithToast(createSession, {
    successMessage: 'Termin erstellt',
    errorMessage: 'Fehler beim Erstellen',
    onSuccess: () => {
      setOpen(false);
      router.refresh();
    },
  });

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="outline" size="sm">
          <Plus className="mr-2 h-4 w-4" />
          Neuer Termin
        </Button>
      </DialogTrigger>
      <DialogContent>
        <form
          onSubmit={(e) => {
            e.preventDefault();
            const fd = new FormData(e.currentTarget);
            execute({
              courseId,
              sessionDate: fd.get('sessionDate') as string,
              startTime: fd.get('startTime') as string,
              endTime: fd.get('endTime') as string,
              notes: (fd.get('notes') as string) || undefined,
            });
          }}
        >
          <DialogHeader>
            <DialogTitle>Neuen Termin erstellen</DialogTitle>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="sessionDate">Datum *</Label>
              <Input id="sessionDate" name="sessionDate" type="date" required />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="startTime">Beginn *</Label>
                <Input id="startTime" name="startTime" type="time" required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="endTime">Ende *</Label>
                <Input id="endTime" name="endTime" type="time" required />
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="notes">Notizen</Label>
              <Input id="notes" name="notes" />
            </div>
          </div>
          <DialogFooter>
            <Button
              type="submit"
              disabled={isPending}
              data-test="session-submit-btn"
            >
              {isPending ? 'Wird erstellt...' : 'Termin erstellen'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
