"use client";

import React, { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { FiX, FiUserPlus, FiMail, FiPhone, FiAlertTriangle } from "react-icons/fi";
import { fetchApi } from "@/lib/api/http";
import type { CompanyRow } from "@/lib/api/types/company.types";
const normalizePhone = (raw: string) => raw.replace(/[^\d+]/g, "");
const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_URL || "http://localhost:3007/api";

interface InviteClientModalProps {
  isOpen: boolean;
  company: CompanyRow | null;
  onClose: () => void;
}

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const PHONE_RE = /^\+[1-9]\d{1,14}$/; // matches backend's E.164 validation exactly

export default function InviteClientModal({
  isOpen,
  company,
  onClose,
}: InviteClientModalProps) {
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [loading, setLoading] = useState(false);
  const [checking, setChecking] = useState(true);
  const [linkedEmails, setLinkedEmails] = useState<string[]>([]);

  useEffect(() => {
    if (!isOpen || !company) return;

    // Reset fields for the new company each time the modal opens
    setEmail(company.email || "");
    setPhone(normalizePhone(company.mobile || "+971"));
    setLinkedEmails([]);
    setChecking(true);

    fetchApi<any>(`${API_BASE_URL}/client-portal/status/${company.id}`)
      .then((res) => {
        const data = res?.data || res;
        if (data?.linkedEmails?.length) setLinkedEmails(data.linkedEmails);
      })
      .catch(() => {
        // Status check failing shouldn't block sending an invite
      })
      .finally(() => setChecking(false));
  }, [isOpen, company]);

  if (!isOpen || !company) return null;

  const emailValid = EMAIL_RE.test(email);
  // Phone is optional — valid if empty/just-prefix OR matches E.164
  const phoneClean = phone.trim() === "+971" ? "" : phone.trim();
  const phoneValid = phoneClean === "" || PHONE_RE.test(phoneClean);

  const handleInvite = async () => {
    if (!emailValid || !phoneValid) return;
    setLoading(true);
    try {
      const body: Record<string, any> = {
        company_id: company.id,
        client_email: email,
      };
      // Only send phone if provided (not just the +971 prefix)
      if (phoneClean) {
        body.client_phone = phoneClean;
      }
      await fetchApi(`${API_BASE_URL}/client-portal/invite`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      toast.success(`Invite sent to ${email}`);
      onClose();
    } catch (err: any) {
      toast.error(err?.message || "Failed to send invite");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div
      style={{
        position: "fixed",
        inset: 0,
        background: "rgba(15, 23, 42, 0.45)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        zIndex: 1000,
      }}
      onClick={onClose}
    >
      <div
        style={{
          background: "#fff",
          borderRadius: 12,
          padding: 24,
          width: "100%",
          maxWidth: 400,
          boxShadow: "0 20px 40px rgba(0,0,0,0.15)",
        }}
        onClick={(e) => e.stopPropagation()}
      >
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 4 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <FiUserPlus size={18} color="#0f766e" />
            <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>Invite to portal</h3>
          </div>
          <button
            onClick={onClose}
            style={{ background: "none", border: "none", cursor: "pointer", color: "#64748b" }}
          >
            <FiX size={18} />
          </button>
        </div>
        <p style={{ fontSize: 13, color: "#64748b", margin: "0 0 16px" }}>{company.name}</p>

        {!checking && linkedEmails.length > 0 && (
          <div
            style={{
              display: "flex",
              gap: 8,
              background: "#fef3c7",
              color: "#92400e",
              padding: "10px 12px",
              borderRadius: 8,
              fontSize: 13,
              marginBottom: 14,
            }}
          >
            <FiAlertTriangle size={16} style={{ flexShrink: 0, marginTop: 1 }} />
            <span>
              Already has portal access: <strong>{linkedEmails.join(", ")}</strong>.
              Sending another invite adds this as an additional login.
            </span>
          </div>
        )}

        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          <label style={{ fontSize: 12, fontWeight: 600, color: "#475569" }}>
            <FiMail size={12} style={{ verticalAlign: -1, marginRight: 4 }} />
            Client email
          </label>
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="client@company.com"
            style={{ padding: "10px 12px", border: "1px solid #e2e8f0", borderRadius: 8, fontSize: 14 }}
          />

          <label style={{ fontSize: 12, fontWeight: 600, color: "#475569", marginTop: 4 }}>
            <FiPhone size={12} style={{ verticalAlign: -1, marginRight: 4 }} />
            Client phone / WhatsApp <span style={{ fontWeight: 400, color: "#94a3b8" }}>(optional)</span>
          </label>
          <input
            type="tel"
            value={phone}
            onChange={(e) => setPhone(normalizePhone(e.target.value))}
            placeholder="+9715XXXXXXXX"
            style={{ padding: "10px 12px", border: "1px solid #e2e8f0", borderRadius: 8, fontSize: 14 }}
          />
          {phoneClean && !PHONE_RE.test(phoneClean) && (
            <span style={{ fontSize: 11, color: "#dc2626" }}>
              Must be E.164 format, e.g. +971501234567
            </span>
          )}
        </div>

        <div style={{ display: "flex", gap: 8, marginTop: 20, justifyContent: "flex-end" }}>
          <button
            onClick={onClose}
            style={{ padding: "9px 16px", border: "1px solid #e2e8f0", borderRadius: 8, background: "#fff", cursor: "pointer", fontSize: 14 }}
          >
            Cancel
          </button>
          <button
            onClick={handleInvite}
            disabled={loading || !emailValid || !phoneValid}
            style={{
              padding: "9px 16px",
              border: "none",
              borderRadius: 8,
              background: loading || !emailValid || !phoneValid ? "#99d6c9" : "#0f766e",
              color: "#fff",
              cursor: loading || !emailValid || !phoneValid ? "not-allowed" : "pointer",
              fontSize: 14,
              fontWeight: 500,
            }}
          >
            {loading ? "Sending..." : "Send invite"}
          </button>
        </div>
      </div>
    </div>
  );
}