"use client";

import { useState } from "react";
import { X, UserCog } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useFormDraft } from "@/lib/use-form-draft";
import { useUserCreationOptions } from "../hooks/use-user-creation-options";
import type { ManageUserCreateRequestDTO, ManageUserResponseDTO } from "../dtos/manage-users.dto";
import { formatPhoneNumber, statusLabel } from "@/lib/display-format";
import { CommunityMultiSelect } from "./community-multi-select";
import { useUserStatusConfirmation } from "../hooks/use-user-status-confirmation";

const INITIAL_DATA = {
  firstName: "", lastName: "", email: "", companyId: "", departmentId: "",
  departmentIds: [] as string[],
  role: "", phone: "", jobTitle: "",
  status: "active" as "active" | "inactive",
};

interface AddUserFormProps {
  onClose: () => void;
  onSubmit: (data: ManageUserCreateRequestDTO) => Promise<boolean>;
  companyId?: string;
  departmentId?: string;
  submissionError?: string | null;
  user?: ManageUserResponseDTO;
  companyOnly?: boolean;
  lockContext?: boolean;
  presentation?: "modal" | "page";
}

export function AddUserForm({ onClose, onSubmit, companyId, departmentId, submissionError, user, companyOnly = false, lockContext = false, presentation = "modal" }: AddUserFormProps) {
  const { formData, setFormData, markSaved, confirmDiscard } = useFormDraft({
    ...INITIAL_DATA,
    companyId: user?.companyId ?? companyId ?? "",
    departmentId: user?.departmentId ?? departmentId ?? "",
    departmentIds: user?.departmentIds ?? (user?.departmentId || departmentId ? [user?.departmentId ?? departmentId!] : []),
    firstName: user?.firstName ?? user?.name.split(" ")[0] ?? "",
    lastName: user?.lastName ?? user?.name.split(" ").slice(1).join(" ") ?? "",
    email: user?.email ?? "", role: user?.role ?? "",
    phone: formatPhoneNumber(user?.phone), jobTitle: user?.jobTitle ?? "",
    status: user?.status ?? "active",
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { requestStatusChange, statusConfirmation } = useUserStatusConfirmation();
  const [validationError, setValidationError] = useState<string | null>(null);
  const { options, error, isLoading, retry } = useUserCreationOptions(true, formData.companyId, formData.departmentId, user?.id);
  const fixedCommunityRole = companyOnly || Boolean(formData.companyId);
  const selectedRole = fixedCommunityRole ? "department_user" : formData.role;
  const close = () => { if (!isSubmitting && confirmDiscard()) onClose(); };
  const inputClass = "w-full rounded-lg border border-gray-200 bg-gray-50 px-4 py-2.5 text-sm text-gray-900 focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500";

  const submit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (user && user.status !== formData.status) {
      await requestStatusChange(user, () => save(event));
      return;
    }
    await save(event);
  };

  const save = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (formData.companyId && formData.departmentIds.length === 0) {
      setValidationError("Select at least one community.");
      return;
    }
    if (isSubmitting || isLoading || error) return;
    if (!options?.roles.some((role) => role.slug === selectedRole)) {
      setValidationError("Select an available role before updating the user.");
      return;
    }
    setIsSubmitting(true);
    try {
      const success = await onSubmit({
        name: `${formData.firstName.trim()} ${formData.lastName.trim()}`,
        firstName: formData.firstName.trim(), lastName: formData.lastName.trim(),
        email: formData.email.trim(), companyId: formData.companyId || null,
        departmentId: formData.departmentId || null, role: selectedRole,
        departmentIds: formData.departmentIds,
        phone: formatPhoneNumber(formData.phone.trim()) || null, jobTitle: formData.jobTitle.trim() || null,
        sendWelcomeEmail: !user, status: formData.status,
      });
      if (success) { markSaved(); onClose(); }
    } finally { setIsSubmitting(false); }
  };

  return (
    <div className={presentation === "page" ? "w-full" : "fixed inset-0 z-50 flex items-center justify-center"}>
      {presentation === "modal" && <div className="absolute inset-0 bg-black/50 backdrop-blur-sm" onClick={close} />}
      <div role={presentation === "modal" ? "dialog" : undefined} aria-modal={presentation === "modal" ? true : undefined} aria-labelledby="add-user-title" className={presentation === "page" ? "w-full rounded-2xl border border-gray-200 bg-white shadow-sm" : "relative z-10 mx-4 max-h-[90vh] w-full max-w-lg overflow-y-auto rounded-2xl border border-gray-200 bg-white shadow-2xl"}>
        <div className="flex items-center justify-between border-b border-gray-200 px-6 py-4">
          <div className="flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-blue-50"><UserCog className="h-5 w-5 text-blue-600" /></div>
            <div><h2 id="add-user-title" className="text-lg font-semibold text-gray-900">{user ? "Edit User" : "Add New User"}</h2><p className="text-xs text-gray-500">{user ? "Update user information" : "Fill in the details to create a new user"}</p></div>
          </div>
          {presentation === "modal" && <button type="button" aria-label="Close" disabled={isSubmitting} onClick={close} className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100"><X className="h-5 w-5" /></button>}
        </div>
        <form onSubmit={submit} className="space-y-4 p-6">
          <fieldset disabled={isSubmitting} className="grid min-w-0 grid-cols-1 gap-4 sm:grid-cols-2 [&>div]:min-w-0">
              {([['firstName', 'First Name'], ['lastName', 'Last Name']] as const).map(([name, label]) => (
                <div key={name} className="space-y-1.5"><label htmlFor={`add-${name}`} className="block text-sm font-medium text-gray-700">{label} <span className="text-red-500">*</span></label><input id={`add-${name}`} name={name} required pattern=".*\S.*" maxLength={127} value={formData[name]} onChange={(event) => setFormData((prev) => ({ ...prev, [name]: event.target.value }))} className={inputClass} /></div>
              ))}
            <div className="space-y-1.5"><label htmlFor="add-email" className="block text-sm font-medium text-gray-700">Email Address <span className="text-red-500">*</span></label><input id="add-email" type="email" required maxLength={255} value={formData.email} onChange={(event) => setFormData((prev) => ({ ...prev, email: event.target.value }))} className={inputClass} /></div>
            <div className="space-y-1.5">
              <label htmlFor="add-company" className="block text-sm font-medium text-gray-700">Company {companyOnly && <span className="text-red-500">*</span>}</label>
              <select id="add-company" required={companyOnly} value={formData.companyId} disabled={isLoading || lockContext} onChange={(event) => { setValidationError(null); setFormData((prev) => ({ ...prev, companyId: event.target.value, departmentId: "", departmentIds: [], role: "" })); }} className={inputClass}>
                <option value="">{companyOnly ? "Select a company" : "No company (system user)"}</option>
                {options?.companies.map((company) => <option key={company.id} value={String(company.id)}>{company.name}</option>)}
              </select>
              {!isLoading && formData.companyId && options?.communities.length === 0 && <p className="text-xs text-gray-500">This company has no available communities.</p>}
            </div>
            <div className="space-y-1.5">
              <label className="block text-sm font-medium text-gray-700">Community {formData.companyId && <span className="text-red-500">*</span>}</label>
              {!formData.companyId && <p className="text-xs text-gray-500">Select a company first</p>}
              <CommunityMultiSelect id="add-community" value={formData.departmentIds} options={options?.communities ?? []} disabled={!formData.companyId || isLoading || lockContext} onChange={(departmentIds) => { setValidationError(null); setFormData((prev) => ({ ...prev, departmentIds, departmentId: departmentIds[0] ?? "" })); }} />
            </div>
            <div className="space-y-1.5">
              <label htmlFor="add-role" className="block text-sm font-medium text-gray-700">Role <span className="text-red-500">*</span></label>
              <select id="add-role" required disabled={fixedCommunityRole || isLoading || !options?.roles.length} value={selectedRole} onChange={(event) => setFormData((prev) => ({ ...prev, role: event.target.value }))} className={inputClass}>
                <option value="">Select a role</option>
                {fixedCommunityRole ? <option value="department_user">Community User</option> : options?.roles.map((role) => <option key={role.id} value={role.slug}>{role.name}</option>)}
              </select>
            </div>
            <div className="space-y-1.5"><label htmlFor="add-phone" className="block text-sm font-medium text-gray-700">Phone</label><input id="add-phone" type="tel" maxLength={20} value={formData.phone} onChange={(event) => setFormData((prev) => ({ ...prev, phone: formatPhoneNumber(event.target.value) }))} className={inputClass} /></div>
            <div className="space-y-1.5">
              <label htmlFor="add-jobTitle" className="block text-sm font-medium text-gray-700">Job Title</label>
              <select id="add-jobTitle" disabled={isLoading || !!error} value={formData.jobTitle} onChange={(event) => setFormData((prev) => ({ ...prev, jobTitle: event.target.value }))} className={inputClass}>
                <option value="">Select a job title</option>
                {user?.jobTitle && !options?.jobTitles?.includes(user.jobTitle) && <option value={user.jobTitle}>{user.jobTitle} (existing)</option>}
                {options?.jobTitles?.map((title) => <option key={title} value={title}>{title}</option>)}
              </select>
            </div>
            <div className="space-y-1.5"><label htmlFor="add-status" className="block text-sm font-medium text-gray-700">Status</label><select id="add-status" value={formData.status} onChange={(event) => setFormData((prev) => ({ ...prev, status: event.target.value as "active" | "inactive" }))} className={inputClass}>{(["active", "inactive"] as const).map((status) => <option key={status} value={status}>{statusLabel(status)}</option>)}</select></div>
          </fieldset>
          {isLoading && <p role="status" className="text-sm text-gray-500">Loading available options...</p>}
          {error && <div role="alert" className="text-sm text-red-600">{error} <button type="button" onClick={retry} className="underline">Retry</button></div>}
          {submissionError && <p role="alert" className="text-sm text-red-600">{submissionError}</p>}
          {validationError && <p role="alert" className="text-sm text-red-600">{validationError}</p>}
          <div className="flex justify-end gap-3 border-t border-gray-200 pt-4"><Button type="button" variant="secondary" onClick={close} disabled={isSubmitting}>Cancel</Button><Button type="submit" disabled={isSubmitting || isLoading || !!error}>{isSubmitting ? (user ? "Updating..." : "Creating...") : (user ? "Update User" : "Create User")}</Button></div>
        </form>
      </div>
      {statusConfirmation}
    </div>
  );
}
