"use client";

import React, { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { FiUsers, FiMail, FiPlus, FiClock, FiRefreshCw, FiUserPlus, FiCopy, FiCheck } from "react-icons/fi";
import { clientPortalApi } from "@/lib/api/clientPortalApi";
import styles from "../../../(dashboard)/modules/commonstyle/dattabale.module.css";

interface Member {
  id: number;
  firstName?: string;
  lastName?: string;
  email: string;
  joined_at?: string;
}

interface Pending {
  email: string;
  expires_at?: string;
  link?: string;
}

function initials(m: Member): string {
  const f = m.firstName?.[0] || m.email[0];
  const l = m.lastName?.[0] || "";
  return (f + l).toUpperCase();
}

function fullName(m: Member): string {
  const n = [m.firstName, m.lastName].filter(Boolean).join(" ");
  return n || m.email;
}

async function copyToClipboard(text: string): Promise<boolean> {
  try {
    await navigator.clipboard.writeText(text);
    return true;
  } catch {
    return false;
  }
}

const PREMIUM_CSS = `
@keyframes cpFadeUp { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }
.cp-rise { opacity: 0; animation: cpFadeUp 0.55s cubic-bezier(0.22,1,0.36,1) forwards; }
.cp-row { transition: background 0.15s ease; }
.cp-row:hover { background: #f8fafc; }
`;

function CopyButton({ text }: { text: string }) {
  const [copied, setCopied] = useState(false);
  return (
    <button
      onClick={async () => {
        const ok = await copyToClipboard(text);
        if (ok) {
          setCopied(true);
          toast.success("Invite link copied");
          setTimeout(() => setCopied(false), 2000);
        } else {
          toast.error("Couldn't copy - copy it manually instead");
        }
      }}
      style={{
        display: "flex", alignItems: "center", gap: 6, padding: "7px 12px",
        background: copied ? "#f0fdf4" : "#f8fafc", color: copied ? "#166534" : "#475569",
        border: "1px solid " + (copied ? "#bbf7d0" : "#e2e8f0"), borderRadius: 8,
        fontSize: 12, fontWeight: 600, cursor: "pointer", whiteSpace: "nowrap", flexShrink: 0,
      }}
    >
      {copied ? <FiCheck size={13} /> : <FiCopy size={13} />}
      {copied ? "Copied" : "Copy link"}
    </button>
  );
}

export default function TeamPage() {
  const [members, setMembers] = useState<Member[]>([]);
  const [pending, setPending] = useState<Pending[]>([]);
  const [loading, setLoading] = useState(true);
  const [showInvite, setShowInvite] = useState(false);
  const [inviteEmail, setInviteEmail] = useState("");
  const [inviting, setInviting] = useState(false);
  const [justInvitedLink, setJustInvitedLink] = useState<string | null>(null);

  useEffect(() => {
    fetchTeam();
  }, []);

  const fetchTeam = async () => {
    try {
      setLoading(true);
      const response = await clientPortalApi.getTeam();
      const data = response.data || response;
      setMembers(data?.members || []);
      setPending(data?.pending || []);
    } catch (error) {
      toast.error("Failed to load team");
    } finally {
      setLoading(false);
    }
  };

  const handleInvite = async () => {
    if (!inviteEmail.trim()) {
      toast.error("Enter an email address");
      return;
    }
    try {
      setInviting(true);
      const response = await clientPortalApi.inviteTeamMember(inviteEmail.trim());
      const data = response.data || response;
      toast.success("Invite created for " + inviteEmail);
      if (data?.link) {
        setJustInvitedLink(data.link);
      }
      setInviteEmail("");
      fetchTeam();
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Failed to send invite");
    } finally {
      setInviting(false);
    }
  };

  if (loading) {
    return (
      <div className={styles.errorContainer}>
        <p className={styles.errorMessage}>Loading team...</p>
      </div>
    );
  }

  return (
    <div className={styles.container}>
      <style>{PREMIUM_CSS}</style>

      <div className={styles.header}>
        <div className={styles.headerLeft}>
          <h1 className={styles.title}>Team access</h1>
          <p className={styles.subtitle}>
            Everyone who can sign in to this company's portal
            {members.length > 0 ? " \u00b7 " + members.length + " member" + (members.length === 1 ? "" : "s") : ""}
          </p>
        </div>
        <div className={styles.headerRight}>
          <button className={styles.btnSecondary} onClick={fetchTeam}>
            <FiRefreshCw className={styles.icon} /> Refresh
          </button>
          <button
            onClick={() => {
              setShowInvite(!showInvite);
              setJustInvitedLink(null);
            }}
            style={{
              display: "flex", alignItems: "center", gap: 6, padding: "8px 16px",
              background: "linear-gradient(135deg, #6a0dad 0%, #4a0080 100%)", color: "#fff",
              border: "none", borderRadius: 8, fontSize: "0.875rem", fontWeight: 600, cursor: "pointer",
              boxShadow: "0 2px 8px rgba(74,0,128,0.3)", whiteSpace: "nowrap",
            }}
          >
            <FiUserPlus size={16} /> Invite colleague
          </button>
        </div>
      </div>

      {showInvite && (
        <div className="cp-rise" style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: 16, padding: 20, marginBottom: 20 }}>
          <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
            <input
              type="email"
              placeholder="colleague@yourcompany.com"
              value={inviteEmail}
              onChange={(e) => setInviteEmail(e.target.value)}
              style={{ flex: 1, padding: "10px 14px", border: "1px solid #e2e8f0", borderRadius: 8, fontSize: 14 }}
            />
            <button
              onClick={handleInvite}
              disabled={inviting}
              style={{
                display: "flex", alignItems: "center", gap: 6, padding: "10px 18px",
                background: "#6a0dad", color: "#fff", border: "none", borderRadius: 8,
                fontSize: 14, fontWeight: 600, cursor: inviting ? "not-allowed" : "pointer",
                opacity: inviting ? 0.7 : 1,
              }}
            >
              <FiPlus size={15} /> {inviting ? "Sending..." : "Send invite"}
            </button>
          </div>

          {justInvitedLink && (
            <div style={{ marginTop: 14, padding: "12px 14px", background: "#fffbeb", border: "1px solid #fde68a", borderRadius: 10 }}>
              <p style={{ fontSize: 12, fontWeight: 700, color: "#92400e", marginBottom: 6 }}>
                Automated email delivery isn't confirmed yet - share this link directly for now:
              </p>
              <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                <div style={{ flex: 1, fontSize: 12, fontFamily: "'JetBrains Mono', monospace", color: "#78350f", wordBreak: "break-all", background: "#fff", padding: "8px 10px", borderRadius: 6, border: "1px solid #fde68a" }}>
                  {justInvitedLink}
                </div>
                <CopyButton text={justInvitedLink} />
              </div>
            </div>
          )}
        </div>
      )}

      <div
        className="cp-rise"
        style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: 16, padding: 8, marginBottom: 20, boxShadow: "0 1px 2px rgba(15,23,42,0.03), 0 10px 28px -16px rgba(15,23,42,0.16)" }}
      >
        <div style={{ padding: "10px 14px", fontSize: 12, fontWeight: 700, color: "#94a3b8", textTransform: "uppercase", letterSpacing: 0.5 }}>
          Members
        </div>
        {members.length === 0 ? (
          <div style={{ padding: "24px 14px", textAlign: "center", color: "#94a3b8", fontSize: 13 }}>
            No members found
          </div>
        ) : (
          members.map((m, idx) => (
            <div
              key={m.id}
              className="cp-row"
              style={{ display: "flex", alignItems: "center", gap: 14, padding: "14px", borderTop: idx > 0 ? "1px solid #f1f5f9" : "none" }}
            >
              <div style={{ width: 38, height: 38, borderRadius: "50%", background: "#eef2ff", color: "#4338ca", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 13, fontWeight: 700, flexShrink: 0 }}>
                {initials(m)}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: "#1e293b" }}>{fullName(m)}</div>
                <div style={{ fontSize: 12, color: "#94a3b8", marginTop: 2 }}>{m.email}</div>
              </div>
              <span style={{ background: "#f0fdf4", color: "#166534", fontSize: 11, fontWeight: 700, padding: "3px 10px", borderRadius: 99 }}>
                Active
              </span>
            </div>
          ))
        )}
      </div>

      {pending.length > 0 && (
        <div
          className="cp-rise"
          style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: 16, padding: 8, boxShadow: "0 1px 2px rgba(15,23,42,0.03), 0 10px 28px -16px rgba(15,23,42,0.16)" }}
        >
          <div style={{ padding: "10px 14px", fontSize: 12, fontWeight: 700, color: "#94a3b8", textTransform: "uppercase", letterSpacing: 0.5 }}>
            Pending invites
          </div>
          {pending.map((p, idx) => (
            <div
              key={p.email}
              className="cp-row"
              style={{ display: "flex", alignItems: "center", gap: 14, padding: "14px", borderTop: idx > 0 ? "1px solid #f1f5f9" : "none" }}
            >
              <div style={{ width: 38, height: 38, borderRadius: "50%", background: "#f8fafc", border: "1px dashed #cbd5e1", display: "flex", alignItems: "center", justifyContent: "center", color: "#94a3b8", flexShrink: 0 }}>
                <FiMail size={16} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: "#1e293b" }}>{p.email}</div>
                <div style={{ fontSize: 12, color: "#94a3b8", marginTop: 2, display: "flex", alignItems: "center", gap: 5 }}>
                  <FiClock size={11} /> Awaiting acceptance
                </div>
              </div>
              {p.link && <CopyButton text={p.link} />}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}