"use client"

import type { JSX } from "react"
import { useState } from "react"
import { useRouter } from "next/navigation"
import { useTranslations } from "next-intl"
import { toast } from "sonner"
import { Check, Trash2, X } from "lucide-react"

import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Textarea } from "@/shared/components/ui/textarea"
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/components/ui/dialog"

import {
  createCoursePlanItemAction,
  updateCoursePlanItemAction,
  deleteCoursePlanItemAction,
  toggleCoursePlanItemCompletedAction,
} from "../actions"
import type { CoursePlanItem } from "../types"

interface CoursePlanItemEditorProps {
  planId: string
  item?: CoursePlanItem
  mode: "create" | "edit"
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function CoursePlanItemEditor({
  planId,
  item,
  mode,
  open,
  onOpenChange,
}: CoursePlanItemEditorProps): JSX.Element {
  const t = useTranslations("coursePlans")
  const router = useRouter()
  const [isWorking, setIsWorking] = useState(false)

  const handleSubmit = async (formData: FormData): Promise<void> => {
    setIsWorking(true)
    try {
      formData.set("planId", planId)

      const res =
        mode === "create"
          ? await createCoursePlanItemAction(null, formData)
          : item
            ? await updateCoursePlanItemAction(item.id, null, formData)
            : null

      if (!res) {
        toast.error(t("item.invalidState"))
        return
      }

      if (res.success) {
        toast.success(res.message)
        onOpenChange(false)
        router.refresh()
      } else {
        toast.error(res.message || t("item.saveFailed"))
      }
    } catch {
      toast.error(t("item.saveFailed"))
    } finally {
      setIsWorking(false)
    }
  }

  const handleDelete = async (): Promise<void> => {
    if (!item) return
    setIsWorking(true)
    try {
      const res = await deleteCoursePlanItemAction(item.id)
      if (res.success) {
        toast.success(res.message)
        onOpenChange(false)
        router.refresh()
      } else {
        toast.error(res.message || t("item.deleteFailed"))
      }
    } catch {
      toast.error(t("item.deleteFailed"))
    } finally {
      setIsWorking(false)
    }
  }

  const handleToggleComplete = async (): Promise<void> => {
    if (!item) return
    setIsWorking(true)
    try {
      const res = await toggleCoursePlanItemCompletedAction(item.id, !item.isCompleted)
      if (res.success) {
        toast.success(res.message)
        router.refresh()
      } else {
        toast.error(res.message || t("item.updateFailed"))
      }
    } catch {
      toast.error(t("item.updateFailed"))
    } finally {
      setIsWorking(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[90vh] max-w-2xl overflow-y-auto">
        <DialogHeader>
          <DialogTitle>
            {mode === "create" ? t("item.addTitle") : t("item.editTitle")}
          </DialogTitle>
        </DialogHeader>
        <form action={handleSubmit} className="space-y-4">
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
            <div className="grid gap-2">
              <Label htmlFor="week">{t("item.week")}</Label>
              <Input
                id="week"
                name="week"
                type="number"
                min={1}
                defaultValue={item?.week ?? 1}
                required
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="hours">{t("item.hours")}</Label>
              <Input
                id="hours"
                name="hours"
                type="number"
                min={1}
                defaultValue={item?.hours ?? 2}
              />
            </div>
          </div>

          <div className="grid gap-2">
            <Label htmlFor="topic">{t("item.topic")}</Label>
            <Input
              id="topic"
              name="topic"
              placeholder={t("item.topicPlaceholder")}
              defaultValue={item?.topic ?? ""}
              required
            />
          </div>

          <div className="grid gap-2">
            <Label htmlFor="content">{t("item.content")}</Label>
            <Textarea
              id="content"
              name="content"
              placeholder={t("item.contentPlaceholder")}
              className="min-h-[100px]"
              defaultValue={item?.content ?? ""}
            />
          </div>

          <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
            <div className="grid gap-2">
              <Label htmlFor="textbookChapter">{t("item.chapter")}</Label>
              <Input
                id="textbookChapter"
                name="textbookChapter"
                placeholder={t("item.chapterPlaceholder")}
                defaultValue={item?.textbookChapter ?? ""}
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="completedAt">{t("item.completedAt")}</Label>
              <Input
                id="completedAt"
                name="completedAt"
                type="date"
                defaultValue={item?.completedAt ?? ""}
              />
            </div>
          </div>

          <div className="grid gap-2">
            <Label htmlFor="notes">{t("item.notes")}</Label>
            <Textarea
              id="notes"
              name="notes"
              placeholder={t("item.notesPlaceholder")}
              defaultValue={item?.notes ?? ""}
            />
          </div>

          <DialogFooter className="gap-2">
            {mode === "edit" && item ? (
              <>
                <Button
                  type="button"
                  variant="outline"
                  onClick={handleToggleComplete}
                  disabled={isWorking}
                >
                  {item.isCompleted ? (
                    <>
                      <X className="mr-2 h-4 w-4" />
                      {t("item.markIncomplete")}
                    </>
                  ) : (
                    <>
                      <Check className="mr-2 h-4 w-4" />
                      {t("item.markComplete")}
                    </>
                  )}
                </Button>
                <Button
                  type="button"
                  variant="destructive"
                  onClick={handleDelete}
                  disabled={isWorking}
                >
                  <Trash2 className="mr-2 h-4 w-4" />
                  {t("item.delete")}
                </Button>
              </>
            ) : null}
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              disabled={isWorking}
            >
              {t("item.cancel")}
            </Button>
            <Button type="submit" disabled={isWorking}>
              {isWorking ? t("item.saving") : t("item.save")}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}
