"use client";

import { useState, useTransition } from "react";
import { toast } from "sonner";
import { Plus } from "lucide-react";
import { createUser } from "./actions";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import type { Branch, Role } from "@/lib/types";

export function AddUserDialog({
  roles,
  branches,
}: {
  roles: Role[];
  branches: Branch[];
}) {
  const [open, setOpen] = useState(false);
  const [pending, startTransition] = useTransition();

  function onSubmit(formData: FormData) {
    startTransition(async () => {
      const res = await createUser(undefined, formData);
      if (res?.ok) {
        toast.success("User created", {
          description: `An invite has been sent. The user can also sign in manually at /login with Email: ${formData.get("email")} and Temporary Password: ${res.tempPassword}`,
          duration: 15000,
        });
        setOpen(false);
      } else if (res?.error) {
        toast.error(res.error);
      }
    });
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button>
          <Plus className="size-4" /> Add User
        </Button>
      </DialogTrigger>
      <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-2xl">
        <DialogHeader>
          <DialogTitle>Add User</DialogTitle>
        </DialogHeader>
        <form action={onSubmit} className="grid grid-cols-2 gap-4">
          <div className="space-y-2">
            <Label htmlFor="full_name">Full name *</Label>
            <Input id="full_name" name="full_name" required />
          </div>
          <div className="space-y-2">
            <Label htmlFor="email">Email *</Label>
            <Input id="email" name="email" type="email" required />
          </div>
          <div className="space-y-2">
            <Label htmlFor="phone">Phone</Label>
            <Input id="phone" name="phone" />
          </div>
          <div className="space-y-2">
            <Label htmlFor="role_id">Role *</Label>
            <Select name="role_id" required>
              <SelectTrigger id="role_id">
                <SelectValue placeholder="Select role" />
              </SelectTrigger>
              <SelectContent>
                {roles.map((r) => (
                  <SelectItem key={r.id} value={r.id}>
                    {r.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label htmlFor="primary_branch_id">Branch *</Label>
            <Select name="primary_branch_id" required>
              <SelectTrigger id="primary_branch_id">
                <SelectValue placeholder="Select branch" />
              </SelectTrigger>
              <SelectContent>
                {branches.map((b) => (
                  <SelectItem key={b.id} value={b.id}>
                    {b.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label htmlFor="joining_date">Joining date</Label>
            <Input id="joining_date" name="joining_date" type="date" />
          </div>
          <div className="space-y-2">
            <Label htmlFor="date_of_birth">Date of birth</Label>
            <Input id="date_of_birth" name="date_of_birth" type="date" />
          </div>
          <div className="space-y-2">
            <Label htmlFor="b2b_country">B2B country</Label>
            <Input id="b2b_country" name="b2b_country" placeholder="Partners only" />
          </div>
          <div className="space-y-2">
            <Label htmlFor="b2b_state">B2B state</Label>
            <Input id="b2b_state" name="b2b_state" />
          </div>
          <div className="col-span-2 space-y-2">
            <Label htmlFor="allowed_ips">Allowed IPs (comma-separated)</Label>
            <Input id="allowed_ips" name="allowed_ips" placeholder="Optional — restricts login" />
          </div>
          <div className="col-span-2 flex justify-end">
            <Button type="submit" disabled={pending}>
              {pending ? "Creating…" : "Create user"}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}
