"use client";

import { useTransition } from "react";
import { format } from "date-fns";
import { de } from "date-fns/locale";
import { NotdienstPlanStatus } from "@prisma/client";
import { Loader2, Wand2, CheckSquare } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  generatePlanAction,
  publishPlanAction,
  updateAssignmentAction,
} from "./actions";

interface PlanViewProps {
  planId?: string;
  status?: NotdienstPlanStatus;
  days: {
    date: string; // ISO
    assignmentId: string | null;
    childId: string | null;
  }[];
  allChildren: {
    id: string;
    name: string;
    parentName: string;
  }[];
}

export function PlanView({ planId, status, days, allChildren }: PlanViewProps) {
  const [isPending, startTransition] = useTransition();

  const handleGenerate = () => {
    startTransition(async () => {
      const result = await generatePlanAction();
      if ("error" in result && result.error) {
        toast.error(result.error as string);
      } else {
        toast.success("Plan erfolgreich generiert.");
      }
    });
  };

  const handlePublish = () => {
    if (!planId) return;
    startTransition(async () => {
      const result = await publishPlanAction(planId);
      if ("error" in result && result.error) {
        toast.error(result.error as string);
      } else {
        toast.success("Plan veröffentlicht! Er ist nun fix.");
      }
    });
  };

  const handleAssignmentChange = (date: string, newChildId: string) => {
    if (!planId || status !== "DRAFT") return;
    const valueToSet = newChildId === "empty" ? null : newChildId;

    startTransition(async () => {
      const result = await updateAssignmentAction(planId, date, valueToSet);
      if ("error" in result && result.error) {
        toast.error(result.error as string);
      } else {
        toast.success("Zuteilung aktualisiert.");
      }
    });
  };

  if (!planId) {
    return (
      <div className="flex flex-col items-center justify-center rounded-lg border border-dashed bg-card p-12 text-center">
        <div className="mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-primary/10 text-primary">
          <Wand2 className="h-6 w-6" />
        </div>
        <h3 className="mb-1 text-lg font-semibold">Noch kein Plan vorhanden</h3>
        <p className="mb-6 max-w-sm text-sm text-muted-foreground">
          Generiere den Plan basierend auf den Verfügbarkeiten der Eltern
          automatisch.
        </p>
        <Button onClick={handleGenerate} disabled={isPending}>
          {isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
          Plan automatisch generieren
        </Button>
      </div>
    );
  }

  const isDraft = status === "DRAFT";

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between rounded-lg border bg-card p-4">
        <div className="flex items-center gap-3">
          <Badge variant={isDraft ? "warning" : "success"}>
            {isDraft ? "Entwurf" : "Veröffentlicht"}
          </Badge>
          <span className="text-sm text-muted-foreground">
            {isDraft
              ? "Du kannst die Liste jetzt manuell anpassen."
              : "Dieser Plan ist verbindlich."}
          </span>
        </div>

        {isDraft && (
          <Button onClick={handlePublish} disabled={isPending}>
            {isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            <CheckSquare className="mr-2 h-4 w-4" />
            Plan veröffentlichen
          </Button>
        )}
      </div>

      <div className="rounded-lg border bg-card">
        <div className="grid grid-cols-[1fr_2fr] border-b bg-muted/30 p-4 text-sm font-medium">
          <div>Datum</div>
          <div>Eingeteilte Familie</div>
        </div>
        <div className="divide-y">
          {days.map((day) => {
            const dateObj = new Date(day.date);
            const isUnbesetzt = !day.childId;

            return (
              <div
                key={day.date}
                className="grid grid-cols-[1fr_2fr] items-center p-4 transition-colors hover:bg-muted/10"
              >
                <div className="font-medium">
                  {format(dateObj, "EE, dd.MM.", { locale: de })}
                </div>
                <div>
                  {isDraft ? (
                    <select
                      className="w-full max-w-sm rounded-md border border-input bg-background px-3 py-1.5 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                      value={day.childId || "empty"}
                      disabled={isPending}
                      onChange={(e) =>
                        handleAssignmentChange(day.date, e.target.value)
                      }
                    >
                      <option value="empty" className="text-destructive">
                        -- Unbesetzt --
                      </option>
                      {allChildren.map((c) => (
                        <option key={c.id} value={c.id}>
                          {c.parentName} ({c.name})
                        </option>
                      ))}
                    </select>
                  ) : (
                    <div>
                      {isUnbesetzt ? (
                        <span className="text-sm font-medium text-destructive">
                          Unbesetzt!
                        </span>
                      ) : (
                        <span className="text-sm">
                          {
                            allChildren.find((c) => c.id === day.childId)
                              ?.parentName
                          }{" "}
                          <span className="text-muted-foreground">
                            (
                            {
                              allChildren.find((c) => c.id === day.childId)
                                ?.name
                            }
                            )
                          </span>
                        </span>
                      )}
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}
