import { A, useNavigate } from "@solidjs/router";
import { createResource, createSignal, For, onMount, Show } from "solid-js";

const API = "";

type Role = { id: string; name: string; key: string };
type Dept = { id: string; name: string };
type Desig = { id: string; name: string };

function parseEmployeeCodeNumber(code: string): number | null {
  const normalized = String(code || "")
    .trim()
    .toUpperCase();
  if (!normalized) return null;
  const explicit = normalized.match(/^EMP[-_]?0*(\d+)$/);
  if (explicit) return Number(explicit[1]);
  const trailing = normalized.match(/(\d+)$/);
  if (trailing) return Number(trailing[1]);
  return null;
}

function formatEmployeeCode(value: number): string {
  return `EMP-${String(Math.max(1, value)).padStart(4, "0")}`;
}

async function fetchRoles(): Promise<Role[]> {
  try {
    const accessToken =
      typeof sessionStorage !== "undefined"
        ? (sessionStorage.getItem("nxtgauge_admin_access_token") || "").trim()
        : "";
    const res = await fetch(`${API}/api/admin/roles?audience=INTERNAL&per_page=100`, {
      headers: {
        Accept: "application/json",
        ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
      },
      credentials: "include",
    });
    if (!res.ok) throw new Error();
    const data = await res.json();
    return Array.isArray(data) ? data : (data.roles ?? []);
  } catch {
    return [];
  }
}
async function fetchDepts(): Promise<Dept[]> {
  try {
    const accessToken =
      typeof sessionStorage !== "undefined"
        ? (sessionStorage.getItem("nxtgauge_admin_access_token") || "").trim()
        : "";
    const res = await fetch(`${API}/api/admin/departments?per_page=100`, {
      headers: {
        Accept: "application/json",
        ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
      },
      credentials: "include",
    });
    if (!res.ok) throw new Error();
    const data = await res.json();
    return Array.isArray(data) ? data : (data.departments ?? []);
  } catch {
    return [];
  }
}
async function fetchDesigs(): Promise<Desig[]> {
  try {
    const accessToken =
      typeof sessionStorage !== "undefined"
        ? (sessionStorage.getItem("nxtgauge_admin_access_token") || "").trim()
        : "";
    const res = await fetch(`${API}/api/admin/designations?per_page=100`, {
      headers: {
        Accept: "application/json",
        ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
      },
      credentials: "include",
    });
    if (!res.ok) throw new Error();
    const data = await res.json();
    return Array.isArray(data) ? data : (data.designations ?? []);
  } catch {
    return [];
  }
}

export default function CreateEmployeePage() {
  const navigate = useNavigate();
  const [roles] = createResource(fetchRoles);
  const [depts] = createResource(fetchDepts);
  const [desigs] = createResource(fetchDesigs);

  const [firstName, setFirstName] = createSignal("");
  const [lastName, setLastName] = createSignal("");
  const [email, setEmail] = createSignal("");
  const [employeeCode, setEmployeeCode] = createSignal("");
  const [createLoginCreds, setCreateLoginCreds] = createSignal(true);
  const [loginPassword, setLoginPassword] = createSignal("");
  const [confirmLoginPassword, setConfirmLoginPassword] = createSignal("");
  const [showLoginPassword, setShowLoginPassword] = createSignal(false);
  const [showConfirmPassword, setShowConfirmPassword] = createSignal(false);
  const [roleId, setRoleId] = createSignal("");
  const [deptId, setDeptId] = createSignal("");
  const [desigId, setDesigId] = createSignal("");
  const [saving, setSaving] = createSignal(false);
  const [generatingCode, setGeneratingCode] = createSignal(false);
  const [error, setError] = createSignal("");

  const fetchNextEmployeeCode = async (): Promise<string> => {
    const accessToken =
      typeof sessionStorage !== "undefined"
        ? (sessionStorage.getItem("nxtgauge_admin_access_token") || "").trim()
        : "";
    let page = 1;
    let maxNum = 0;
    while (page <= 100) {
      const res = await fetch(
        `${API}/api/admin/employees?page=${page}&per_page=100&sort=joined_desc`,
        {
          headers: {
            Accept: "application/json",
            ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
          },
          credentials: "include",
        }
      ).catch(() => null);
      if (!res?.ok) break;
      const payload = await res.json().catch(() => null);
      const list: any[] = Array.isArray(payload)
        ? payload
        : Array.isArray(payload?.employees)
          ? payload.employees
          : Array.isArray(payload?.items)
            ? payload.items
            : [];
      if (!Array.isArray(list) || list.length === 0) break;
      for (const item of list) {
        const raw = String(item?.employee_id ?? item?.employeeId ?? item?.employee_code ?? "");
        const parsed = parseEmployeeCodeNumber(raw);
        if (parsed && parsed > maxNum) maxNum = parsed;
      }
      if (list.length < 100) break;
      page += 1;
    }
    return formatEmployeeCode(maxNum + 1);
  };

  onMount(() => {
    void (async () => {
      setGeneratingCode(true);
      try {
        setEmployeeCode(await fetchNextEmployeeCode());
      } catch {
        setEmployeeCode("");
      } finally {
        setGeneratingCode(false);
      }
    })();
  });

  const handleSave = async (e: Event) => {
    e.preventDefault();
    if (!firstName().trim()) {
      setError("First name is required");
      return;
    }
    if (!lastName().trim()) {
      setError("Last name is required");
      return;
    }
    if (!email().trim()) {
      setError("Email is required");
      return;
    }
    if (!roleId()) {
      setError("Internal role is required");
      return;
    }
    if (!deptId()) {
      setError("Department is required");
      return;
    }
    if (!desigId()) {
      setError("Designation is required");
      return;
    }
    if (createLoginCreds()) {
      if (loginPassword().trim().length < 8) {
        setError("Password must be at least 8 characters");
        return;
      }
      if (loginPassword().trim() !== confirmLoginPassword().trim()) {
        setError("Password and confirm password do not match");
        return;
      }
    }
    setError("");
    setSaving(true);
    try {
      const accessToken =
        typeof sessionStorage !== "undefined"
          ? (sessionStorage.getItem("nxtgauge_admin_access_token") || "").trim()
          : "";
      const res = await fetch(`${API}/api/admin/employees/provision`, {
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
          ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
        },
        method: "POST",
        credentials: "include",
        body: JSON.stringify({
          email: email().trim(),
          first_name: firstName().trim(),
          last_name: lastName().trim(),
          role_code: roleId(),
          department_id: deptId().trim(),
          designation_id: desigId().trim(),
          employee_code: employeeCode().trim() || undefined,
          generate_login: createLoginCreds(),
          password: createLoginCreds() ? loginPassword().trim() : undefined,
        }),
      });
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(
          (body as any).error || (body as any).message || "Failed to create employee"
        );
      }
      navigate("/admin/employees");
    } catch (err: any) {
      setError(err.message || "Failed to create employee");
    } finally {
      setSaving(false);
    }
  };

  return (
    <div class="w-full space-y-8 pb-8">
      {/* Page header */}
      <div class="flex items-end justify-between">
        <div>
          <p class="text-[12px] font-semibold uppercase tracking-widest text-[#FF5E13]">
            Internal Team
          </p>
          <h1 class="mt-1 text-[28px] font-bold leading-tight text-[#111827]">Add Employee</h1>
          <p class="mt-1 text-[14px] text-[#6B7280]">
            Dashboard / Employee Management / Add Employee
          </p>
        </div>
        <A
          href="/admin/employees"
          class="inline-flex items-center gap-2 rounded-xl border border-[#E5E7EB] bg-white px-4 py-2.5 text-[13px] font-semibold text-[#374151] hover:bg-[#F9FAFB] transition-colors"
        >
          ← Back to Employees
        </A>
      </div>

      {/* Form card */}
      <div class="rounded-2xl border border-[#E5E7EB] bg-white shadow-sm overflow-hidden">
        <div class="border-b border-[#F3F4F6] px-6 py-4">
          <h2 class="text-[15px] font-semibold text-[#111827]">Employee Details</h2>
          <p class="mt-0.5 text-[13px] text-[#6B7280]">
            Login credentials will be emailed to the employee automatically.
          </p>
        </div>

        <form onSubmit={handleSave} class="p-6 space-y-5">
          <div class="grid grid-cols-2 gap-5">
            {/* First Name */}
            <div>
              <label class="block text-[13px] font-medium text-[#111827] mb-1.5">
                First Name <span class="text-red-500">*</span>
              </label>
              <input
                type="text"
                required
                placeholder="e.g. Arjun"
                value={firstName()}
                onInput={(e) => setFirstName(e.currentTarget.value)}
                maxlength="100"
                class="w-full px-3 py-2.5 text-[13px] border border-[#E5E7EB] rounded-lg outline-none focus:border-[#FF5E13] focus:ring-1 focus:ring-[#FF5E13] text-[#111827] placeholder-[#9CA3AF]"
              />
            </div>

            {/* Last Name */}
            <div>
              <label class="block text-[13px] font-medium text-[#111827] mb-1.5">
                Last Name <span class="text-red-500">*</span>
              </label>
              <input
                type="text"
                required
                placeholder="e.g. Sharma"
                value={lastName()}
                onInput={(e) => setLastName(e.currentTarget.value)}
                maxlength="100"
                class="w-full px-3 py-2.5 text-[13px] border border-[#E5E7EB] rounded-lg outline-none focus:border-[#FF5E13] focus:ring-1 focus:ring-[#FF5E13] text-[#111827] placeholder-[#9CA3AF]"
              />
            </div>

            {/* Email */}
            <div>
              <label class="block text-[13px] font-medium text-[#111827] mb-1.5">
                Email Address <span class="text-red-500">*</span>
              </label>
              <input
                type="email"
                required
                placeholder="e.g. arjun@nxtgauge.com"
                value={email()}
                onInput={(e) => setEmail(e.currentTarget.value)}
                class="w-full px-3 py-2.5 text-[13px] border border-[#E5E7EB] rounded-lg outline-none focus:border-[#FF5E13] focus:ring-1 focus:ring-[#FF5E13] text-[#111827] placeholder-[#9CA3AF]"
              />
            </div>

            {/* Employee ID */}
            <div>
              <label class="block text-[13px] font-medium text-[#111827] mb-1.5">
                Employee ID <span class="text-red-500">*</span>
              </label>
              <input
                type="text"
                readOnly
                value={employeeCode()}
                placeholder={generatingCode() ? "Generating..." : "Auto generated"}
                class="w-full px-3 py-2.5 text-[13px] border border-[#E5E7EB] rounded-lg bg-[#F9FAFB] text-[#111827] placeholder-[#9CA3AF]"
              />
            </div>

            {/* Login Credential Controls */}
            <div class="col-span-2 rounded-lg border border-[#E5E7EB] bg-[#F9FAFB] px-4 py-3">
              <label class="flex items-center gap-2 text-[13px] font-medium text-[#111827]">
                <input
                  type="checkbox"
                  checked={createLoginCreds()}
                  onChange={(e) => setCreateLoginCreds(e.currentTarget.checked)}
                  class="h-4 w-4 accent-[#FF5E13]"
                />
                Create login credentials if this email does not exist
              </label>
              <p class="mt-1 text-[12px] text-[#6B7280]">
                When enabled, a user account is created with the password below and then linked as
                employee.
              </p>
            </div>

            <Show when={createLoginCreds()}>
              <>
                <div>
                  <label class="block text-[13px] font-medium text-[#111827] mb-1.5">
                    Login Password <span class="text-red-500">*</span>
                  </label>
                  <div style="position:relative">
                    <input
                      type={showLoginPassword() ? "text" : "password"}
                      value={loginPassword()}
                      onInput={(e) => setLoginPassword(e.currentTarget.value)}
                      placeholder="Minimum 8 characters"
                      class="w-full px-3 py-2.5 pr-10 text-[13px] border border-[#E5E7EB] rounded-lg outline-none focus:border-[#FF5E13] focus:ring-1 focus:ring-[#FF5E13] text-[#111827] placeholder-[#9CA3AF]"
                    />
                    <button
                      type="button"
                      onClick={() => setShowLoginPassword((v) => !v)}
                      style="position:absolute;right:10px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:#6B7280;padding:4px"
                    >
                      <Show
                        when={showLoginPassword()}
                        fallback={
                          <svg
                            width="18"
                            height="18"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            stroke-width="2"
                          >
                            <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
                            <circle cx="12" cy="12" r="3" />
                          </svg>
                        }
                      >
                        <svg
                          width="18"
                          height="18"
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                        >
                          <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24" />
                          <line x1="1" y1="1" x2="23" y2="23" />
                        </svg>
                      </Show>
                    </button>
                  </div>
                </div>
                <div>
                  <label class="block text-[13px] font-medium text-[#111827] mb-1.5">
                    Confirm Password <span class="text-red-500">*</span>
                  </label>
                  <div style="position:relative">
                    <input
                      type={showConfirmPassword() ? "text" : "password"}
                      value={confirmLoginPassword()}
                      onInput={(e) => setConfirmLoginPassword(e.currentTarget.value)}
                      placeholder="Repeat password"
                      class="w-full px-3 py-2.5 pr-10 text-[13px] border border-[#E5E7EB] rounded-lg outline-none focus:border-[#FF5E13] focus:ring-1 focus:ring-[#FF5E13] text-[#111827] placeholder-[#9CA3AF]"
                    />
                    <button
                      type="button"
                      onClick={() => setShowConfirmPassword((v) => !v)}
                      style="position:absolute;right:10px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:#6B7280;padding:4px"
                    >
                      <Show
                        when={showConfirmPassword()}
                        fallback={
                          <svg
                            width="18"
                            height="18"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            stroke-width="2"
                          >
                            <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
                            <circle cx="12" cy="12" r="3" />
                          </svg>
                        }
                      >
                        <svg
                          width="18"
                          height="18"
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                        >
                          <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24" />
                          <line x1="1" y1="1" x2="23" y2="23" />
                        </svg>
                      </Show>
                    </button>
                  </div>
                </div>
              </>
            </Show>

            {/* Internal Role */}
            <div>
              <label class="block text-[13px] font-medium text-[#111827] mb-1.5">
                Internal Role <span class="text-red-500">*</span>
              </label>
              <select
                value={roleId()}
                onChange={(e) => setRoleId(e.currentTarget.value)}
                class="w-full px-3 py-2.5 text-[13px] border border-[#E5E7EB] rounded-lg outline-none focus:border-[#FF5E13] focus:ring-1 focus:ring-[#FF5E13] bg-white text-[#111827]"
              >
                <option value="">Select role…</option>
                <For each={roles() ?? []}>{(r) => <option value={r.key}>{r.name}</option>}</For>
              </select>
            </div>

            {/* Department */}
            <div>
              <label class="block text-[13px] font-medium text-[#111827] mb-1.5">
                Department <span class="text-red-500">*</span>
              </label>
              <select
                value={deptId()}
                onChange={(e) => setDeptId(e.currentTarget.value)}
                class="w-full px-3 py-2.5 text-[13px] border border-[#E5E7EB] rounded-lg outline-none focus:border-[#FF5E13] focus:ring-1 focus:ring-[#FF5E13] bg-white text-[#111827]"
              >
                <option value="">Select department…</option>
                <For each={depts() ?? []}>{(d) => <option value={d.id}>{d.name}</option>}</For>
              </select>
            </div>

            {/* Designation */}
            <div>
              <label class="block text-[13px] font-medium text-[#111827] mb-1.5">
                Designation <span class="text-red-500">*</span>
              </label>
              <select
                value={desigId()}
                onChange={(e) => setDesigId(e.currentTarget.value)}
                class="w-full px-3 py-2.5 text-[13px] border border-[#E5E7EB] rounded-lg outline-none focus:border-[#FF5E13] focus:ring-1 focus:ring-[#FF5E13] bg-white text-[#111827]"
              >
                <option value="">Select designation…</option>
                <For each={desigs() ?? []}>{(d) => <option value={d.id}>{d.name}</option>}</For>
              </select>
            </div>
          </div>

          {/* Info note */}
          <div class="rounded-lg border border-[#EFF6FF] bg-[#EFF6FF] px-4 py-3 text-[13px] text-[#2563EB]">
            Login credentials will be auto-generated and sent to the employee's email address.
          </div>

          {/* Error */}
          {error() && (
            <div class="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-[13px] text-red-700">
              {error()}
            </div>
          )}

          {/* Footer */}
          <div class="flex items-center justify-end gap-3 border-t border-[#F3F4F6] pt-5">
            <A
              href="/admin/employees"
              class="h-[40px] inline-flex items-center rounded-xl border border-[#E5E7EB] bg-white px-5 text-[13px] font-semibold text-[#374151] hover:bg-[#F9FAFB] transition-colors"
            >
              Cancel
            </A>
            <button
              type="submit"
              disabled={saving()}
              class="h-[40px] rounded-xl bg-[#FF5E13] px-6 text-[13px] font-semibold text-white hover:bg-[#e04d0a] transition-colors disabled:opacity-60"
            >
              {saving() ? "Creating…" : "Add Employee"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
