"use client";
import { useState } from "react";
import { Copy, UserPlus } from "lucide-react";
import { Avatar, Badge, Button, Card, Field, Input, PageHeader, Select, Sheet, Toggle, api, useAction, useUI } from "@/components/ui";
import { ago, useApi } from "@/components/hooks";

export default function TeamPage() {
  const users = useApi<{ data: any[] }>("/users");
  const roles = useApi<{ data: any[] }>("/roles");
  const [invite, setInvite] = useState(false);
  const [edit, setEdit] = useState<any | null>(null);
  const { push } = useUI();
  return (
    <>
      <PageHeader title="Team" subtitle="Members of this workspace, their roles and lead-routing attributes" actions={<Button variant="primary" icon={<UserPlus className="h-3.5 w-3.5" />} onClick={() => setInvite(true)}>Invite</Button>} />
      <Card bodyClass="p-0">
        <table className="table-mac">
          <thead><tr><th>Member</th><th>Role</th><th>Territory</th><th>Projects</th><th>MFA</th><th>Last sign-in</th><th>Status</th><th /></tr></thead>
          <tbody>{users.data?.data.map((u) => (
            <tr key={u.id}>
              <td><div className="flex items-center gap-2.5"><Avatar name={u.name} size={28} /><div><div className="font-medium">{u.name}</div><div className="text-[11.5px] text-ink-3">{u.email}</div></div></div></td>
              <td><Badge tone="violet">{u.role.name}</Badge></td><td className="text-ink-2">{u.territory ?? "—"}</td><td className="max-w-[200px] truncate text-ink-2">{u.projects.join(", ") || "—"}</td>
              <td>{u.mfaEnabled ? <Badge tone="green">On</Badge> : <Badge>Off</Badge>}</td><td className="text-ink-3">{ago(u.lastLoginAt)}</td>
              <td>{!u.active ? <Badge>Deactivated</Badge> : u.status === "invited" ? <Badge tone="amber">Invited</Badge> : <Badge tone="green" dot>Active</Badge>}</td>
              <td className="whitespace-nowrap text-right">
                {u.status === "invited" && <button className="mr-3 text-[12px] text-brand hover:underline" onClick={async () => { const r = await api(`/users/${u.id}/invite-link`, { method: "POST" }); navigator.clipboard.writeText(r.data.inviteLink); push("ok", "Invite link copied"); }}>Copy invite</button>}
                <button className="text-[12px] text-brand hover:underline" onClick={() => setEdit(u)}>Edit</button>
              </td>
            </tr>
          ))}</tbody>
        </table>
      </Card>
      {invite && <InviteSheet roles={roles.data?.data ?? []} onClose={() => setInvite(false)} onDone={() => users.reload()} />}
      {edit && <EditSheet user={edit} roles={roles.data?.data ?? []} onClose={() => setEdit(null)} onDone={() => { setEdit(null); users.reload(); }} />}
    </>
  );
}

function InviteSheet({ roles, onClose, onDone }: { roles: any[]; onClose: () => void; onDone: () => void }) {
  const [f, setF] = useState({ email: "", name: "", role_id: roles.find((r) => r.key === "sales_rep")?.id ?? "", territory: "", projects: "" });
  const [link, setLink] = useState<string | null>(null);
  const { busy, run } = useAction();
  const { push } = useUI();
  return (
    <Sheet open onClose={onClose} width={480} title="Invite a member" footer={link ? <Button variant="primary" onClick={onClose}>Done</Button> : <><Button onClick={onClose}>Cancel</Button><Button variant="primary" loading={busy} onClick={() => run(async () => { const r = await api("/users", { body: { ...f, territory: f.territory || undefined, projects: f.projects.split(",").map((x) => x.trim()).filter(Boolean) } }); onDone(); if (r.data.inviteLink) setLink(r.data.inviteLink); else onClose(); push("ok", r.data.emailed ? "Invitation emailed" : r.data.inviteLink ? "Invite created — share the link" : "Member added"); })}>Invite</Button></>}>
      {link ? (
        <div className="space-y-2"><p className="text-[13px]">Share this link with {f.name} (valid 7 days):</p><div className="flex gap-2"><Input readOnly value={link} className="font-mono text-[11.5px]" /><Button icon={<Copy className="h-3.5 w-3.5" />} onClick={() => { navigator.clipboard.writeText(link); push("ok", "Copied"); }}>Copy</Button></div></div>
      ) : (
        <div className="space-y-3">
          <div className="grid grid-cols-2 gap-3"><Field label="Name"><Input value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} /></Field><Field label="Email"><Input type="email" value={f.email} onChange={(e) => setF({ ...f, email: e.target.value })} /></Field></div>
          <Field label="Role"><Select value={f.role_id} onChange={(e) => setF({ ...f, role_id: e.target.value })}>{roles.map((r) => <option key={r.id} value={r.id}>{r.name}{r.isSystem ? "" : " (custom)"}</option>)}</Select></Field>
          <div className="grid grid-cols-2 gap-3"><Field label="Territory" hint="For territory routing"><Input value={f.territory} onChange={(e) => setF({ ...f, territory: e.target.value })} placeholder="Gulshan" /></Field><Field label="Projects" hint="Comma separated"><Input value={f.projects} onChange={(e) => setF({ ...f, projects: e.target.value })} /></Field></div>
        </div>
      )}
    </Sheet>
  );
}

function EditSheet({ user, roles, onClose, onDone }: { user: any; roles: any[]; onClose: () => void; onDone: () => void }) {
  const [f, setF] = useState({ role_id: user.role.id, territory: user.territory ?? "", projects: user.projects.join(", "), active: user.active });
  const { busy, run } = useAction();
  return (
    <Sheet open onClose={onClose} width={460} title={user.name} footer={<><Button onClick={onClose}>Cancel</Button><Button variant="primary" loading={busy} onClick={() => run(async () => { await api(`/users/${user.id}`, { method: "PATCH", body: { role_id: f.role_id, territory: f.territory || null, projects: f.projects.split(",").map((x: string) => x.trim()).filter(Boolean), active: f.active } }); onDone(); }, "Member updated")}>Save</Button></>}>
      <div className="space-y-3">
        <Field label="Role"><Select value={f.role_id} onChange={(e) => setF({ ...f, role_id: e.target.value })}>{roles.map((r) => <option key={r.id} value={r.id}>{r.name}</option>)}</Select></Field>
        <Field label="Territory"><Input value={f.territory} onChange={(e) => setF({ ...f, territory: e.target.value })} /></Field>
        <Field label="Projects"><Input value={f.projects} onChange={(e) => setF({ ...f, projects: e.target.value })} /></Field>
        <Toggle checked={f.active} onChange={(v) => setF({ ...f, active: v })} label="Active member (turn off to revoke access and sign out)" />
      </div>
    </Sheet>
  );
}

