'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import { Check, ExternalLink, ShieldAlert, Coins } from 'lucide-react';
import { Profile } from '@/lib/constants';
import { claimMilestoneReward } from '@/lib/credits-actions';

interface EarnCreditsSectionProps {
  profile: Partial<Profile> & { id?: string; discord_id?: string | null; views?: number };
  claimedMilestones?: string[];
  onClaimSuccess?: (milestoneId: string, creditsEarned: number, newBalance: number) => void;
  title?: string;
  subtitle?: string;
}

export default function EarnCreditsSection({
  profile,
  claimedMilestones = [],
  onClaimSuccess,
  title = 'Earn Sinss Credits',
  subtitle = 'Complete milestones and participate in the community to receive credit drops.',
}: EarnCreditsSectionProps) {
  const [busyMilestone, setBusyMilestone] = useState<string | null>(null);
  const [localClaimed, setLocalClaimed] = useState<string[]>(claimedMilestones);
  const [message, setMessage] = useState<{ text: string; error?: boolean } | null>(null);

  const isClaimed = (id: string) => localClaimed.includes(id) || claimedMilestones.includes(id);
  const viewsCount = profile.views || 0;

  const handleClaim = async (milestoneId: string) => {
    if (isClaimed(milestoneId)) return;
    setBusyMilestone(milestoneId);
    setMessage(null);

    try {
      const res = await claimMilestoneReward(milestoneId);
      setBusyMilestone(null);

      if (!res.success) {
        setMessage({ text: res.error || 'Could not claim reward.', error: true });
        return;
      }

      setLocalClaimed((prev) => [...prev, milestoneId]);
      setMessage({ text: `Claimed +${res.creditsEarned} credits.` });

      if (onClaimSuccess && res.creditsEarned !== undefined && res.newBalance !== undefined) {
        onClaimSuccess(milestoneId, res.creditsEarned, res.newBalance);
      }
    } catch {
      setBusyMilestone(null);
      setMessage({ text: 'Network error claiming reward.', error: true });
    }
  };

  const handleBugReport = () => {
    if (typeof window !== 'undefined') {
      const bugBtn = document.getElementById('reportBugBtn') || document.querySelector('[data-trigger-bug-report]');
      if (bugBtn && 'click' in bugBtn) {
        (bugBtn as HTMLButtonElement).click();
      } else {
        window.open('https://discord.gg/sinss', '_blank');
      }
    }
  };

  return (
    <div className="earnSectionRoot">
      <div className="earnHeader">
        <div>
          <h2>{title}</h2>
          <p>{subtitle}</p>
        </div>
      </div>

      {message && (
        <div className={`earnNotice ${message.error ? 'earnNoticeError' : 'earnNoticeSuccess'}`}>
          {message.error ? <ShieldAlert size={15} /> : <Check size={15} />}
          <span>{message.text}</span>
        </div>
      )}

      <div className="earnLinkedNotice">
        <Coins size={14} className="noticeCoin" />
        <span>
          Free milestone rewards can only be claimed on one account across your linked profiles. You can transfer credits between your accounts at any time.
        </span>
      </div>

      <div className="earnGrid">
        {/* Discord Connect Milestone */}
        <div className={`earnCard ${isClaimed('welcome_discord') ? 'earnCardCompleted' : ''}`}>
          <div className="earnCardHeader">
            <span className="earnIcon">🎮</span>
            <div>
              <strong>Link Discord Account</strong>
              <p>Connect your verified Discord to your sinss.lol profile.</p>
            </div>
          </div>
          <div className="earnCardFooter">
            <span className="earnReward">+100 Credits</span>
            {isClaimed('welcome_discord') ? (
              <button type="button" className="earnBtn earnBtnClaimed" disabled>
                <Check size={14} />
                <span>Claimed</span>
              </button>
            ) : profile.discord_id ? (
              <button
                type="button"
                className="earnBtn"
                disabled={busyMilestone === 'welcome_discord'}
                onClick={() => handleClaim('welcome_discord')}
              >
                {busyMilestone === 'welcome_discord' ? 'Claiming…' : 'Claim Reward'}
              </button>
            ) : (
              <Link href="/dashboard/discord-presence" className="earnBtnGhost">
                Connect Discord
              </Link>
            )}
          </div>
        </div>

        {/* 100 Views Milestone */}
        <div className={`earnCard ${isClaimed('milestone_views_100') ? 'earnCardCompleted' : ''}`}>
          <div className="earnCardHeader">
            <span className="earnIcon">👁️</span>
            <div>
              <strong>100 Profile Views</strong>
              <p>Reach 100 unique visits on your public profile link.</p>
            </div>
          </div>
          <div className="earnProgressWrap">
            <div className="earnProgressBar">
              <div
                className="earnProgressFill"
                style={{ width: `${Math.min(100, (viewsCount / 100) * 100)}%` }}
              />
            </div>
            <small>{viewsCount} / 100 Views</small>
          </div>
          <div className="earnCardFooter">
            <span className="earnReward">+50 Credits</span>
            {isClaimed('milestone_views_100') ? (
              <button type="button" className="earnBtn earnBtnClaimed" disabled>
                <Check size={14} />
                <span>Claimed</span>
              </button>
            ) : (
              <button
                type="button"
                className={`earnBtn ${viewsCount < 100 ? 'earnBtnLocked' : ''}`}
                disabled={viewsCount < 100 || busyMilestone === 'milestone_views_100'}
                onClick={() => handleClaim('milestone_views_100')}
              >
                {viewsCount < 100 ? 'In Progress' : busyMilestone === 'milestone_views_100' ? 'Claiming…' : 'Claim'}
              </button>
            )}
          </div>
        </div>

        {/* 500 Views Milestone */}
        <div className={`earnCard ${isClaimed('milestone_views_500') ? 'earnCardCompleted' : ''}`}>
          <div className="earnCardHeader">
            <span className="earnIcon">🔥</span>
            <div>
              <strong>500 Profile Views</strong>
              <p>Accelerate your reach and unlock 500 profile views.</p>
            </div>
          </div>
          <div className="earnProgressWrap">
            <div className="earnProgressBar">
              <div
                className="earnProgressFill"
                style={{ width: `${Math.min(100, (viewsCount / 500) * 100)}%` }}
              />
            </div>
            <small>{viewsCount} / 500 Views</small>
          </div>
          <div className="earnCardFooter">
            <span className="earnReward">+150 Credits</span>
            {isClaimed('milestone_views_500') ? (
              <button type="button" className="earnBtn earnBtnClaimed" disabled>
                <Check size={14} />
                <span>Claimed</span>
              </button>
            ) : (
              <button
                type="button"
                className={`earnBtn ${viewsCount < 500 ? 'earnBtnLocked' : ''}`}
                disabled={viewsCount < 500 || busyMilestone === 'milestone_views_500'}
                onClick={() => handleClaim('milestone_views_500')}
              >
                {viewsCount < 500 ? 'In Progress' : busyMilestone === 'milestone_views_500' ? 'Claiming…' : 'Claim'}
              </button>
            )}
          </div>
        </div>

        {/* 1,000 Views Milestone */}
        <div className={`earnCard ${isClaimed('milestone_views_1000') ? 'earnCardCompleted' : ''}`}>
          <div className="earnCardHeader">
            <span className="earnIcon">👑</span>
            <div>
              <strong>1,000 Profile Views</strong>
              <p>Hit the four-figure milestone on your bio link.</p>
            </div>
          </div>
          <div className="earnProgressWrap">
            <div className="earnProgressBar">
              <div
                className="earnProgressFill"
                style={{ width: `${Math.min(100, (viewsCount / 1000) * 100)}%` }}
              />
            </div>
            <small>{viewsCount} / 1,000 Views</small>
          </div>
          <div className="earnCardFooter">
            <span className="earnReward">+300 Credits</span>
            {isClaimed('milestone_views_1000') ? (
              <button type="button" className="earnBtn earnBtnClaimed" disabled>
                <Check size={14} />
                <span>Claimed</span>
              </button>
            ) : (
              <button
                type="button"
                className={`earnBtn ${viewsCount < 1000 ? 'earnBtnLocked' : ''}`}
                disabled={viewsCount < 1000 || busyMilestone === 'milestone_views_1000'}
                onClick={() => handleClaim('milestone_views_1000')}
              >
                {viewsCount < 1000 ? 'In Progress' : busyMilestone === 'milestone_views_1000' ? 'Claiming…' : 'Claim'}
              </button>
            )}
          </div>
        </div>

        {/* Server Booster */}
        <div className="earnCard">
          <div className="earnCardHeader">
            <span className="earnIcon">💎</span>
            <div>
              <strong>Discord Server Booster</strong>
              <p>Active nitro boosters in our Discord receive monthly credit airdrops.</p>
            </div>
          </div>
          <div className="earnCardFooter">
            <span className="earnReward">+500 Credits / mo</span>
            <a
              href="https://discord.gg/sinss"
              target="_blank"
              rel="noopener noreferrer"
              className="earnBtnGhost"
            >
              <ExternalLink size={13} />
              <span>Boost Server</span>
            </a>
          </div>
        </div>

        {/* Bug Hunter Bounty */}
        <div className="earnCard">
          <div className="earnCardHeader">
            <span className="earnIcon">🛡️</span>
            <div>
              <strong>Bug Hunter Bounty</strong>
              <p>Report reproducible bugs, styling glitches, or security issues.</p>
            </div>
          </div>
          <div className="earnCardFooter">
            <span className="earnReward">+250 Credits</span>
            <button
              type="button"
              className="earnBtnGhost"
              onClick={handleBugReport}
            >
              <ExternalLink size={13} />
              <span>Submit Report</span>
            </button>
          </div>
        </div>
      </div>

      <style jsx>{`
        .earnSectionRoot {
          margin-top: 10px;
          font-family: inherit;
        }
        .earnHeader {
          margin-bottom: 16px;
        }
        .earnHeader h2 {
          font-family: Unbounded, sans-serif;
          font-size: 18px;
          font-weight: 500;
          color: #000;
          margin: 0 0 6px;
          letter-spacing: -0.4px;
        }
        .earnHeader p {
          color: #420d0d;
          font-size: 13px;
          margin: 0;
        }
        .earnNotice {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 10px 14px;
          border-radius: 10px;
          font-size: 13px;
          font-weight: 500;
          margin-bottom: 16px;
        }
        .earnNoticeSuccess {
          background: rgba(222, 131, 131, 0.12);
          border: 1px solid rgba(222, 131, 131, 0.3);
          color: #de8383;
        }
        .earnNoticeError {
          background: rgba(248, 214, 214, 0.12);
          border: 1px solid rgba(248, 214, 214, 0.3);
          color: #f8d6d6;
        }
        .earnLinkedNotice {
          display: flex;
          align-items: center;
          gap: 10px;
          padding: 10px 14px;
          background: rgba(0, 0, 0, 0.03);
          border: 1px solid rgba(0, 0, 0, 0.08);
          border-radius: 10px;
          font-size: 11.5px;
          color: #420d0d;
          margin-bottom: 16px;
        }
        :global(.noticeCoin) {
          color: #f5e1e1;
          flex-shrink: 0;
        }
        .earnGrid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
          gap: 16px;
        }
        .earnCard {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          background: linear-gradient(140deg, #101115, #0c0d10);
          border: 1px solid rgba(0, 0, 0, 0.08);
          border-radius: 14px;
          padding: 18px;
          transition: all 0.2s ease;
        }
        .earnCard:hover {
          border-color: rgba(255, 255, 255, 0.25);
          transform: translateY(-2px);
          box-shadow: 0 8px 24px -10px rgba(0, 0, 0, 0.6);
        }
        .earnCardCompleted {
          background: rgba(15, 22, 20, 0.65);
          border-color: rgba(222, 131, 131, 0.2);
        }
        .earnCardHeader {
          display: flex;
          align-items: flex-start;
          gap: 12px;
          margin-bottom: 12px;
        }
        .earnIcon {
          font-size: 24px;
          line-height: 1;
        }
        .earnCardHeader strong {
          display: block;
          font-size: 15px;
          font-weight: 700;
          color: #650101;
          margin-bottom: 4px;
        }
        .earnCardHeader p {
          color: #551212;
          font-size: 12px;
          line-height: 1.4;
          margin: 0;
        }
        .earnProgressWrap {
          margin-bottom: 14px;
        }
        .earnProgressBar {
          height: 6px;
          background: rgba(0, 0, 0, 0.08);
          border-radius: 999px;
          overflow: hidden;
          margin-bottom: 6px;
        }
        .earnProgressFill {
          height: 100%;
          background: #f6e6e6;
          border-radius: 999px;
          transition: width 0.3s ease;
        }
        .earnProgressWrap small {
          color: #551212;
          font-size: 11px;
          font-weight: 600;
        }
        .earnCardFooter {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding-top: 14px;
          border-top: 1px solid rgba(0, 0, 0, 0.06);
          margin-top: auto;
        }
        .earnReward {
          font-size: 13px;
          font-weight: 700;
          color: #f6e6e6;
        }
        .earnBtn {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          gap: 6px;
          padding: 8px 16px;
          border-radius: 8px;
          background: #f6e6e6;
          color: #000;
          font-size: 12px;
          font-weight: 700;
          border: none;
          cursor: pointer;
          transition: all 0.15s ease;
        }
        .earnBtn:hover:not(:disabled) {
          background: #faefef;
          transform: translateY(-1px);
        }
        .earnBtnLocked {
          background: rgba(0, 0, 0, 0.08);
          color: #3d1616;
          cursor: not-allowed;
        }
        .earnBtnClaimed {
          background: rgba(222, 131, 131, 0.12) !important;
          border: 1px solid rgba(222, 131, 131, 0.3) !important;
          color: #de8383 !important;
          cursor: default !important;
          pointer-events: none;
        }
        .earnBtnGhost {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          gap: 6px;
          padding: 7px 14px;
          border-radius: 8px;
          background: rgba(0, 0, 0, 0.05);
          border: 1px solid rgba(0, 0, 0, 0.12);
          color: #9b0707;
          font-size: 12px;
          font-weight: 600;
          text-decoration: none;
          cursor: pointer;
          transition: all 0.15s ease;
        }
        .earnBtnGhost:hover {
          background: rgba(0, 0, 0, 0.1);
          color: #000;
          border-color: rgba(0, 0, 0, 0.2);
        }
      `}</style>
    </div>
  );
}
