"use client";

import { useState, useTransition } from "react";
import { toast } from "sonner";
import { Plus, Pencil } from "lucide-react";
import { createFaculty, updateFaculty, toggleFacultyActive } from "./actions";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import type { CoachingFaculty } from "@/lib/types";

export function AddFacultyDialog() {
  return <FacultyDialog />;
}

function FacultyDialog({ faculty }: { faculty?: CoachingFaculty }) {
  const editing = Boolean(faculty);
  const [open, setOpen] = useState(false);
  const [pending, startTransition] = useTransition();

  function onSubmit(formData: FormData) {
    startTransition(async () => {
      const res = editing
        ? await updateFaculty(undefined, formData)
        : await createFaculty(undefined, formData);
      if (res?.ok) {
        toast.success(editing ? "Faculty updated" : "Faculty created");
        setOpen(false);
      } else if (res?.error) {
        toast.error(res.error);
      }
    });
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        {editing ? (
          <Button size="icon" variant="ghost">
            <Pencil className="size-4" />
          </Button>
        ) : (
          <Button>
            <Plus className="size-4" /> Add Faculty
          </Button>
        )}
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{editing ? "Edit Faculty" : "Add Faculty"}</DialogTitle>
        </DialogHeader>
        <form action={onSubmit} className="grid grid-cols-2 gap-4">
          {editing && <input type="hidden" name="id" value={faculty!.id} />}
          <div className="col-span-2 space-y-2">
            <Label htmlFor="name">Name *</Label>
            <Input id="name" name="name" required defaultValue={faculty?.name ?? ""} />
          </div>
          <div className="col-span-2 space-y-2">
            <Label htmlFor="subject">Subject</Label>
            <Input id="subject" name="subject" defaultValue={faculty?.subject ?? ""} />
          </div>
          <div className="space-y-2">
            <Label htmlFor="email">Email</Label>
            <Input
              id="email"
              name="email"
              type="email"
              defaultValue={faculty?.email ?? ""}
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="phone">Phone</Label>
            <Input id="phone" name="phone" defaultValue={faculty?.phone ?? ""} />
          </div>
          <div className="col-span-2 flex justify-end">
            <Button type="submit" disabled={pending}>
              {pending ? "Saving…" : editing ? "Save changes" : "Save faculty"}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}

export function FacultyRowActions({ faculty }: { faculty: CoachingFaculty }) {
  const [pending, start] = useTransition();

  function toggle(next: boolean) {
    start(async () => {
      await toggleFacultyActive(faculty.id, next);
      toast.success(next ? "Activated" : "Deactivated");
    });
  }

  return (
    <div className="flex items-center justify-end gap-2">
      <Switch checked={faculty.is_active} onCheckedChange={toggle} disabled={pending} />
      <FacultyDialog faculty={faculty} />
    </div>
  );
}
