"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
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) {
  const router = useRouter()
  const [isWorking, setIsWorking] = useState(false)

  const handleSubmit = async (formData: FormData) => {
    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("Invalid form state")
        return
      }

      if (res.success) {
        toast.success(res.message)
        onOpenChange(false)
        router.refresh()
      } else {
        toast.error(res.message || "Failed to save week plan")
      }
    } catch {
      toast.error("Failed to save week plan")
    } finally {
      setIsWorking(false)
    }
  }

  const handleDelete = async () => {
    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 || "Failed to delete")
      }
    } catch {
      toast.error("Failed to delete")
    } finally {
      setIsWorking(false)
    }
  }

  const handleToggleComplete = async () => {
    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 || "Failed to update")
      }
    } catch {
      toast.error("Failed to update")
    } finally {
      setIsWorking(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[90vh] max-w-2xl overflow-y-auto">
        <DialogHeader>
          <DialogTitle>
            {mode === "create" ? "Add Week Plan" : "Edit Week Plan"}
          </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">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">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">Topic</Label>
            <Input
              id="topic"
              name="topic"
              placeholder="Week topic"
              defaultValue={item?.topic ?? ""}
              required
            />
          </div>

          <div className="grid gap-2">
            <Label htmlFor="content">Content</Label>
            <Textarea
              id="content"
              name="content"
              placeholder="Teaching content..."
              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">Textbook Chapter</Label>
              <Input
                id="textbookChapter"
                name="textbookChapter"
                placeholder="e.g. Chapter 3"
                defaultValue={item?.textbookChapter ?? ""}
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="completedAt">Completed At</Label>
              <Input
                id="completedAt"
                name="completedAt"
                type="date"
                defaultValue={item?.completedAt ?? ""}
              />
            </div>
          </div>

          <div className="grid gap-2">
            <Label htmlFor="notes">Notes</Label>
            <Textarea
              id="notes"
              name="notes"
              placeholder="Notes..."
              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" />
                      Mark Incomplete
                    </>
                  ) : (
                    <>
                      <Check className="mr-2 h-4 w-4" />
                      Mark Complete
                    </>
                  )}
                </Button>
                <Button
                  type="button"
                  variant="destructive"
                  onClick={handleDelete}
                  disabled={isWorking}
                >
                  <Trash2 className="mr-2 h-4 w-4" />
                  Delete
                </Button>
              </>
            ) : null}
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              disabled={isWorking}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={isWorking}>
              {isWorking ? "Saving..." : "Save"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}
