'use client';

import React, { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { Coins, Send, X, AlertCircle, Check } from 'lucide-react';
import { tipCreditsAction } from '@/lib/credits-actions';
import { useToast } from '@/components/Toast';

interface ProfileTipButtonProps {
  username: string;
  accent?: string;
}

export default function ProfileTipButton({ username, accent = '#f5caca' }: ProfileTipButtonProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [mounted, setMounted] = useState(false);
  const [amount, setAmount] = useState<number>(50);
  const [customAmount, setCustomAmount] = useState('');
  const [message, setMessage] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);
  const toast = useToast();

  useEffect(() => {
    setMounted(true);
  }, []);

  const handleOpen = () => {
    setIsOpen(true);
    setError(null);
    setSuccess(false);
    setMessage('');
  };

  const handleClose = () => {
    if (busy) return;
    setIsOpen(false);
  };

  const selectedAmount = customAmount ? parseInt(customAmount, 10) || 0 : amount;

  const handleSendTip = async () => {
    if (selectedAmount <= 0) {
      setError('Please select or enter a valid amount.');
      return;
    }

    setBusy(true);
    setError(null);

    try {
      const res = await tipCreditsAction(username, selectedAmount, message);
      setBusy(false);

      if (!res.success) {
        if (res.error?.includes('logged in')) {
          window.location.href = '/login';
          return;
        }
        setError(res.error || 'Failed to send tip.');
      } else {
        setSuccess(true);
        toast.show(`Successfully sent ${selectedAmount} credits to @${username}`);
        setTimeout(() => {
          setIsOpen(false);
        }, 1500);
      }
    } catch {
      setBusy(false);
      setError('Network error sending tip.');
    }
  };

  return (
    <>
      <button
        type="button"
        onClick={handleOpen}
        className="profileTipBtn"
        aria-label={`Tip credits to @${username}`}
        title={`Tip credits to @${username}`}
        style={{
          '--tip-accent': accent,
        } as React.CSSProperties}
      >
        <Coins size={14} />
        <span>Tip</span>
      </button>

      {isOpen && mounted && createPortal(
        <div className="tipModalOverlay" onClick={handleClose}>
          <div className="tipModalCard" onClick={(e) => e.stopPropagation()}>
            <button type="button" className="tipModalClose" onClick={handleClose} disabled={busy}>
              <X size={16} />
            </button>

            {!success ? (
              <>
                <div className="tipModalHead">
                  <div className="tipModalIcon">
                    <Coins size={24} style={{ color: accent }} />
                  </div>
                  <h3>Tip Sinss Credits</h3>
                  <p>Send credits directly to @{username}</p>
                </div>

                {error && (
                  <div className="tipErrorBanner">
                    <AlertCircle size={14} />
                    <span>{error}</span>
                  </div>
                )}

                <div className="tipPresetRow">
                  {[25, 50, 100, 250].map((val) => (
                    <button
                      key={val}
                      type="button"
                      className={`tipPresetBtn ${amount === val && !customAmount ? 'active' : ''}`}
                      onClick={() => {
                        setAmount(val);
                        setCustomAmount('');
                      }}
                    >
                      {val}
                    </button>
                  ))}
                </div>

                <div className="tipCustomInputWrap">
                  <label htmlFor="custom-tip">Custom Amount</label>
                  <input
                    id="custom-tip"
                    type="number"
                    min="1"
                    placeholder="Enter credits..."
                    value={customAmount}
                    onChange={(e) => setCustomAmount(e.target.value)}
                  />
                </div>

                <div className="tipMessageWrap">
                  <label htmlFor="tip-note">Note (Optional)</label>
                  <input
                    id="tip-note"
                    type="text"
                    maxLength={140}
                    placeholder="Add a friendly message..."
                    value={message}
                    onChange={(e) => setMessage(e.target.value)}
                  />
                </div>

                <div className="tipLinkedInfoNote">
                  <Coins size={12} className="tipInfoCoin" />
                  <span>
                    You can freely transfer credits to your own linked accounts or tip other users.
                  </span>
                </div>

                <button
                  type="button"
                  className="tipSubmitBtn"
                  style={{ background: accent, color: '#000' }}
                  onClick={handleSendTip}
                  disabled={busy || selectedAmount <= 0}
                >
                  <Send size={15} />
                  <span>{busy ? 'Sending...' : `Send ${selectedAmount} Credits`}</span>
                </button>
              </>
            ) : (
              <div className="tipSuccessState">
                <div className="tipSuccessIcon">
                  <Check size={28} />
                </div>
                <h3>Tip Sent!</h3>
                <p>
                  You transferred <strong>{selectedAmount} credits</strong> to @{username}.
                </p>
              </div>
            )}
          </div>
        </div>,
        document.body
      )}

      <style>{`
        .profileTipBtn {
          display: inline-flex;
          align-items: center;
          gap: 6px;
          background: rgba(0, 0, 0, 0.06);
          border: 1px solid rgba(0, 0, 0, 0.12);
          border-radius: 999px;
          padding: 6px 13px;
          font-size: 12px;
          font-weight: 700;
          color: #9b0707;
          cursor: pointer;
          transition: all 0.15s ease;
          backdrop-filter: blur(8px);
        }
        .profileTipBtn:hover {
          background: rgba(0, 0, 0, 0.12);
          border-color: var(--tip-accent, #f5caca);
          color: #000;
          transform: translateY(-1px);
        }
        .tipModalOverlay {
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          width: 100vw;
          height: 100vh;
          background: rgba(0, 0, 0, 0.75);
          backdrop-filter: blur(8px);
          -webkit-backdrop-filter: blur(8px);
          display: grid;
          place-items: center;
          z-index: 999999;
          padding: 20px;
        }
        .tipModalCard {
          position: relative;
          width: 100%;
          max-width: 380px;
          background: #0d121f;
          border: 1px solid rgba(0, 0, 0, 0.14);
          border-radius: 18px;
          padding: 24px;
          box-shadow: 0 20px 50px rgba(0, 0, 0, 0.7);
        }
        .tipModalClose {
          position: absolute;
          top: 14px;
          right: 14px;
          width: 28px;
          height: 28px;
          border-radius: 50%;
          border: 1px solid rgba(0, 0, 0, 0.1);
          background: rgba(0, 0, 0, 0.05);
          color: #551212;
          display: grid;
          place-items: center;
          cursor: pointer;
        }
        .tipModalHead {
          text-align: center;
          margin-bottom: 18px;
        }
        .tipModalIcon {
          width: 48px;
          height: 48px;
          border-radius: 14px;
          background: rgba(0, 0, 0, 0.04);
          border: 1px solid rgba(0, 0, 0, 0.1);
          display: grid;
          place-items: center;
          margin: 0 auto 10px;
        }
        .tipModalHead h3 {
          font-size: 18px;
          font-weight: 800;
          color: #ca0202;
          margin-bottom: 4px;
        }
        .tipModalHead p {
          font-size: 12px;
          color: #551212;
        }
        .tipErrorBanner {
          background: rgba(239, 191, 191, 0.15);
          border: 1px solid rgba(239, 191, 191, 0.35);
          color: #fce1e1;
          padding: 8px 12px;
          border-radius: 8px;
          font-size: 11px;
          display: flex;
          align-items: center;
          gap: 6px;
          margin-bottom: 14px;
        }
        .tipPresetRow {
          display: grid;
          grid-template-columns: repeat(4, 1fr);
          gap: 8px;
          margin-bottom: 14px;
        }
        .tipPresetBtn {
          height: 36px;
          border-radius: 9px;
          border: 1px solid rgba(0, 0, 0, 0.1);
          background: rgba(0, 0, 0, 0.03);
          color: #ca0202;
          font-size: 13px;
          font-weight: 750;
          cursor: pointer;
          transition: all 0.15s ease;
        }
        .tipPresetBtn.active {
          border-color: #f5caca;
          background: rgba(245, 202, 202, 0.15);
          color: #f5caca;
        }
        .tipCustomInputWrap, .tipMessageWrap {
          margin-bottom: 12px;
          text-align: left;
        }
        .tipCustomInputWrap label, .tipMessageWrap label {
          display: block;
          font-size: 11px;
          font-weight: 700;
          color: #551212;
          margin-bottom: 5px;
        }
        .tipCustomInputWrap input, .tipMessageWrap input {
          width: 100%;
          height: 38px;
          border-radius: 9px;
          border: 1px solid rgba(0, 0, 0, 0.1);
          background: #080c16;
          color: #ca0202;
          padding: 0 12px;
          font-size: 12px;
          outline: none;
        }
        .tipCustomInputWrap input:focus, .tipMessageWrap input:focus {
          border-color: #f5caca;
        }
        .tipLinkedInfoNote {
          display: flex;
          align-items: center;
          gap: 6px;
          padding: 8px 10px;
          border-radius: 8px;
          background: rgba(0, 0, 0, 0.03);
          border: 1px solid rgba(0, 0, 0, 0.08);
          font-size: 11px;
          color: #551212;
          text-align: left;
          line-height: 1.4;
          margin-top: 8px;
        }
        .tipInfoCoin {
          color: #f5e1e1;
          flex-shrink: 0;
        }
        .tipSubmitBtn {
          width: 100%;
          height: 42px;
          border-radius: 11px;
          border: none;
          font-size: 13px;
          font-weight: 800;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 8px;
          cursor: pointer;
          margin-top: 16px;
          transition: filter 0.15s ease;
        }
        .tipSubmitBtn:hover:not(:disabled) {
          filter: brightness(1.15);
        }
        .tipSubmitBtn:disabled {
          opacity: 0.55;
          cursor: not-allowed;
        }
        .tipSuccessState {
          text-align: center;
          padding: 20px 0;
        }
        .tipSuccessIcon {
          width: 52px;
          height: 52px;
          border-radius: 50%;
          background: rgba(222, 131, 131, 0.15);
          border: 1px solid rgba(222, 131, 131, 0.4);
          color: #de8383;
          display: grid;
          place-items: center;
          margin: 0 auto 14px;
        }
        .tipSuccessState h3 {
          font-size: 20px;
          font-weight: 800;
          color: #ca0202;
          margin-bottom: 6px;
        }
        .tipSuccessState p {
          font-size: 13px;
          color: #551212;
        }
      `}</style>
    </>
  );
}
