"use client";

import React, { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { FiX, FiSend } from "react-icons/fi";
import {
  inviteClient,
  getCompaniesForDropdown,
} from "../client-portal.api";

interface Props {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  /** Pre-select company when inviting from a company context */
  preselectedCompanyId?: number;
}

export default function InviteClientModal({
  isOpen,
  onClose,
  onSuccess,
  preselectedCompanyId,
}: Props) {
  const [companies, setCompanies] = useState<{ id: number; name: string }[]>(
    [],
  );
  const [companyId, setCompanyId] = useState<number | "">(
    preselectedCompanyId ?? "",
  );
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    if (!isOpen) return;
    getCompaniesForDropdown()
      .then(setCompanies)
      .catch(() => setCompanies([]));
  }, [isOpen]);

  useEffect(() => {
    if (preselectedCompanyId) setCompanyId(preselectedCompanyId);
  }, [preselectedCompanyId]);

  if (!isOpen) return null;

  const handleSubmit = async () => {
    if (!companyId) {
      toast.error("Select a company");
      return;
    }
    if (!email.trim()) {
      toast.error("Email is required");
      return;
    }
    if (!phone.trim()) {
      toast.error("Phone is required");
      return;
    }

    setSubmitting(true);
    try {
      await inviteClient({
        company_id: Number(companyId),
        client_email: email.trim(),
        client_phone: phone.trim(),
      });
      toast.success("✅ Invitation sent successfully!");
      setEmail("");
      setPhone("");
      setCompanyId(preselectedCompanyId ?? "");
      onSuccess();
      onClose();
    } catch (err: any) {
      toast.error(err?.message || "Failed to send invitation");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <>
      {/* Overlay */}
      <div
        onClick={onClose}
        style={{
          position: "fixed",
          inset: 0,
          background: "rgba(0,0,0,0.5)",
          zIndex: 9998,
        }}
      />

      {/* Modal */}
      <div
        style={{
          position: "fixed",
          top: "50%",
          left: "50%",
          transform: "translate(-50%, -50%)",
          zIndex: 9999,
          background: "#fff",
          borderRadius: 16,
          boxShadow: "0 20px 60px rgba(0,0,0,0.2)",
          width: "min(480px, 92vw)",
          maxHeight: "90vh",
          overflowY: "auto",
        }}
      >
        {/* Header */}
        <div
          style={{
            padding: "20px 24px",
            borderBottom: "1px solid #e5e7eb",
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            background: "linear-gradient(135deg, #6d28d9, #8b5cf6)",
            borderRadius: "16px 16px 0 0",
          }}
        >
          <div>
            <h2
              style={{
                margin: 0,
                fontSize: 18,
                fontWeight: 800,
                color: "#fff",
              }}
            >
              ＋ Invite Client
            </h2>
            <p
              style={{
                margin: "4px 0 0",
                fontSize: 12,
                color: "rgba(255,255,255,0.8)",
              }}
            >
              Send portal access invitation via email
            </p>
          </div>
          <button
            onClick={onClose}
            style={{
              background: "rgba(255,255,255,0.2)",
              border: "none",
              borderRadius: 8,
              padding: 8,
              cursor: "pointer",
              color: "#fff",
            }}
          >
            <FiX size={18} />
          </button>
        </div>

        {/* Body */}
        <div style={{ padding: "24px" }}>
          {/* Company */}
          <div style={{ marginBottom: 16 }}>
            <label
              style={{
                display: "block",
                fontSize: 13,
                fontWeight: 700,
                color: "#374151",
                marginBottom: 6,
              }}
            >
              Company *
            </label>
            <select
              value={companyId}
              onChange={(e) =>
                setCompanyId(
                  e.target.value ? Number(e.target.value) : "",
                )
              }
              style={{
                width: "100%",
                padding: "10px 14px",
                borderRadius: 10,
                border: "1.5px solid #d1d5db",
                fontSize: 14,
                outline: "none",
              }}
            >
              <option value="">Select company...</option>
              {companies.map((c) => (
                <option key={c.id} value={c.id}>
                  {c.name}
                </option>
              ))}
            </select>
          </div>

          {/* Email */}
          <div style={{ marginBottom: 16 }}>
            <label
              style={{
                display: "block",
                fontSize: 13,
                fontWeight: 700,
                color: "#374151",
                marginBottom: 6,
              }}
            >
              Client Email *
            </label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="client@company.com"
              style={{
                width: "100%",
                padding: "10px 14px",
                borderRadius: 10,
                border: "1.5px solid #d1d5db",
                fontSize: 14,
                outline: "none",
              }}
            />
          </div>

          {/* Phone */}
          <div style={{ marginBottom: 24 }}>
            <label
              style={{
                display: "block",
                fontSize: 13,
                fontWeight: 700,
                color: "#374151",
                marginBottom: 6,
              }}
            >
              Client Phone *
            </label>
            <input
              type="tel"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              placeholder="+971501234567"
              style={{
                width: "100%",
                padding: "10px 14px",
                borderRadius: 10,
                border: "1.5px solid #d1d5db",
                fontSize: 14,
                outline: "none",
              }}
            />
            <div
              style={{ fontSize: 11, color: "#9ca3af", marginTop: 4 }}
            >
              E.164 format recommended (e.g. +971501234567)
            </div>
          </div>

          {/* Info box */}
          <div
            style={{
              padding: "12px 14px",
              background: "#eff6ff",
              border: "1px solid #bfdbfe",
              borderRadius: 10,
              marginBottom: 20,
              fontSize: 12,
              color: "#1e40af",
            }}
          >
            💡 An invitation email with a 7-day access link will be sent.
            The client logs in via OTP verification.
          </div>

          {/* Actions */}
          <div
            style={{
              display: "flex",
              justifyContent: "flex-end",
              gap: 10,
            }}
          >
            <button
              onClick={onClose}
              disabled={submitting}
              style={{
                padding: "10px 20px",
                borderRadius: 10,
                border: "1px solid #d1d5db",
                background: "#fff",
                color: "#374151",
                fontSize: 14,
                fontWeight: 600,
                cursor: "pointer",
              }}
            >
              Cancel
            </button>
            <button
              onClick={handleSubmit}
              disabled={submitting}
              style={{
                padding: "10px 24px",
                borderRadius: 10,
                border: "none",
                background: submitting
                  ? "#9ca3af"
                  : "linear-gradient(135deg, #6d28d9, #8b5cf6)",
                color: "#fff",
                fontSize: 14,
                fontWeight: 700,
                cursor: submitting ? "not-allowed" : "pointer",
                display: "inline-flex",
                alignItems: "center",
                gap: 6,
              }}
            >
              <FiSend size={14} />
              {submitting ? "Sending..." : "Send Invitation"}
            </button>
          </div>
        </div>
      </div>
    </>
  );
}
