import { createFileRoute } from "@tanstack/react-router";
import { useState } from "react";
import { toast } from "sonner";
import { Plus } from "lucide-react";
import { Field, inputClass } from "@/components/partner/PartnerShell";
import { SectionCard } from "@/components/account/parts";

export const Route = createFileRoute("/_partner/settings/team")({
  head: () => ({
    meta: [
      { title: "Team Members — Airfis Partner" },
      { name: "description", content: "Manage people who have access to this business on Airfis." },
      { property: "og:title", content: "Team Members — Airfis Partner" },
      {
        property: "og:description",
        content: "Invite teammates and manage their roles and access.",
      },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary" },
      { name: "robots", content: "noindex" },
    ],
  }),
  component: TeamSettings,
});

const ROLES = ["Owner", "Admin", "Manager", "Staff", "Viewer"];

type Member = { id: string; name: string; role: string; status: "Active" | "Pending" };

function TeamSettings() {
  const [members, setMembers] = useState<Member[]>([
    { id: "1", name: "Edwin D", role: "Owner", status: "Active" },
    { id: "2", name: "Sujith", role: "Manager", status: "Active" },
    { id: "3", name: "Arun", role: "Staff", status: "Pending" },
  ]);
  const [inviteOpen, setInviteOpen] = useState(false);
  const [invite, setInvite] = useState({ email: "", role: "Staff", message: "" });

  function send() {
    if (!/^\S+@\S+\.\S+$/.test(invite.email)) return toast.error("Enter a valid email address.");
    setMembers((m) => [
      ...m,
      {
        id: crypto.randomUUID(),
        name: invite.email.split("@")[0]!,
        role: invite.role,
        status: "Pending",
      },
    ]);
    setInvite({ email: "", role: "Staff", message: "" });
    setInviteOpen(false);
    toast.success("Invitation sent successfully.");
  }

  return (
    <>
      <SectionCard
        title="Team Members"
        description="Manage people who have access to this business."
        actions={
          <button
            type="button"
            onClick={() => setInviteOpen(true)}
            className="btn-brand inline-flex shrink-0 items-center gap-2 text-sm"
          >
            <Plus className="h-4 w-4" /> Invite Member
          </button>
        }
      >
        <div className="overflow-x-auto">
          <table className="w-full min-w-[460px] text-sm">
            <thead>
              <tr className="border-b border-hairline text-left text-xs uppercase tracking-wide text-ink-3">
                <th className="py-2 pr-4 font-semibold">Name</th>
                <th className="py-2 pr-4 font-semibold">Role</th>
                <th className="py-2 pr-4 font-semibold">Status</th>
                <th className="py-2 font-semibold">Actions</th>
              </tr>
            </thead>
            <tbody>
              {members.map((m) => (
                <tr key={m.id} className="border-b border-hairline last:border-0">
                  <td className="py-3 pr-4 font-medium text-ink">{m.name}</td>
                  <td className="py-3 pr-4">
                    <select
                      className="rounded-lg border border-hairline bg-white px-2 py-1 text-sm outline-none focus:border-[#FF4308]"
                      value={m.role}
                      disabled={m.role === "Owner"}
                      onChange={(e) =>
                        setMembers((prev) =>
                          prev.map((x) => (x.id === m.id ? { ...x, role: e.target.value } : x)),
                        )
                      }
                    >
                      {ROLES.map((r) => (
                        <option key={r}>{r}</option>
                      ))}
                    </select>
                  </td>
                  <td className="py-3 pr-4">
                    <span
                      className={`rounded-full px-2.5 py-1 text-xs font-semibold ${m.status === "Active" ? "bg-emerald-50 text-emerald-700" : "bg-slate-100 text-slate-700"}`}
                    >
                      {m.status}
                    </span>
                  </td>
                  <td className="py-3">
                    {m.role !== "Owner" && (
                      <button
                        type="button"
                        onClick={() => {
                          setMembers((prev) => prev.filter((x) => x.id !== m.id));
                          toast.success(`${m.name} removed.`);
                        }}
                        className="text-sm font-semibold text-rose-600"
                      >
                        Remove
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </SectionCard>

      {inviteOpen && (
        <div
          className="fixed inset-0 z-[60] flex items-center justify-center bg-black/40 p-4"
          onClick={() => setInviteOpen(false)}
        >
          <div
            className="w-full max-w-md rounded-2xl border border-hairline bg-white p-6"
            onClick={(e) => e.stopPropagation()}
          >
            <h2 className="text-base font-bold text-ink">Invite Team Member</h2>
            <div className="mt-4 space-y-4">
              <Field label="Email address">
                <input
                  className={inputClass}
                  value={invite.email}
                  onChange={(e) => setInvite((i) => ({ ...i, email: e.target.value }))}
                />
              </Field>
              <Field label="Role">
                <select
                  className={inputClass}
                  value={invite.role}
                  onChange={(e) => setInvite((i) => ({ ...i, role: e.target.value }))}
                >
                  {ROLES.map((r) => (
                    <option key={r}>{r}</option>
                  ))}
                </select>
              </Field>
              <Field label="Message">
                <textarea
                  rows={3}
                  className={inputClass}
                  value={invite.message}
                  onChange={(e) => setInvite((i) => ({ ...i, message: e.target.value }))}
                />
              </Field>
            </div>
            <div className="mt-6 flex justify-end gap-2">
              <button
                type="button"
                onClick={() => setInviteOpen(false)}
                className="btn-ghost text-sm"
              >
                Cancel
              </button>
              <button type="button" onClick={send} className="btn-brand text-sm">
                Send Invitation
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
