'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { usePortalAuthStore } from '@/lib/portal-auth-store';
import portalApi from '@/lib/portal-api';
import { formatCurrency } from '@/lib/utils';

interface AccountData {
  accountNumber: string;
  firstName: string;
  lastName: string;
  email?: string;
  phone?: string;
  subscription?: {
    planName: string;
    downloadMbps: number;
    uploadMbps: number;
    monthlyRate: number;
    status: string;
  };
  balanceDue: number;
}

const statusColors: Record<string, { bg: string; text: string }> = {
  ACTIVE: { bg: '#DCFCE7', text: '#16A34A' },
  SUSPENDED: { bg: '#FEF9C3', text: '#CA8A04' },
  CANCELLED: { bg: '#FEE2E2', text: '#DC2626' },
  PENDING: { bg: '#F1F5F9', text: '#64748B' },
};

export default function PortalDashboardPage() {
  const router = useRouter();
  const { isAuthenticated, subscriber, logout } = usePortalAuthStore();
  const [mounted, setMounted] = useState(false);
  const [account, setAccount] = useState<AccountData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

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

  useEffect(() => {
    if (!mounted) return;
    if (!isAuthenticated) { router.replace('/portal/login'); return; }
    portalApi.get('/api/v1/portal/account')
      .then((res) => setAccount(res.data))
      .catch(() => setError('Failed to load account info.'))
      .finally(() => setLoading(false));
  }, [mounted, isAuthenticated, router]);

  if (!mounted || !isAuthenticated) return null;

  const handleLogout = () => { logout(); router.replace('/portal/login'); };

  return (
    <div style={{ maxWidth: 800, margin: '0 auto', padding: '32px 24px' }}>
      {/* Header row */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 28 }}>
        <div>
          <h1 style={{ fontSize: 22, fontWeight: 700, color: '#0F172A', marginBottom: 2 }}>
            Welcome, {subscriber?.firstName ?? 'Subscriber'}
          </h1>
          <p style={{ fontSize: 14, color: '#64748B' }}>Account #{subscriber?.accountNumber}</p>
        </div>
        <button
          onClick={handleLogout}
          style={{ fontSize: 13, color: '#64748B', background: 'none', border: '1px solid #E2E8F0', borderRadius: 8, padding: '7px 14px', cursor: 'pointer' }}
        >
          Sign Out
        </button>
      </div>

      {error && (
        <div style={{ backgroundColor: '#FEF2F2', border: '1px solid #FECACA', borderRadius: 8, padding: '12px 16px', color: '#DC2626', fontSize: 14, marginBottom: 20 }}>
          {error}
        </div>
      )}

      {loading ? (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {[1, 2, 3].map((i) => (
            <div key={i} style={{ backgroundColor: '#ffffff', borderRadius: 12, border: '1px solid #E2E8F0', padding: 24, height: 100, animation: 'pulse 1.5s infinite' }} />
          ))}
        </div>
      ) : account && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {/* Account Info */}
          <div style={cardStyle}>
            <h2 style={cardTitleStyle}>Account Information</h2>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px 24px', marginTop: 12 }}>
              {[
                { label: 'Full Name', value: `${account.firstName} ${account.lastName}` },
                { label: 'Account Number', value: account.accountNumber },
                { label: 'Email', value: account.email || '—' },
                { label: 'Phone', value: account.phone || '—' },
              ].map(({ label, value }) => (
                <div key={label}>
                  <p style={{ fontSize: 11, fontWeight: 600, color: '#94A3B8', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 2 }}>{label}</p>
                  <p style={{ fontSize: 14, color: '#0F172A' }}>{value}</p>
                </div>
              ))}
            </div>
          </div>

          {/* Subscription */}
          <div style={cardStyle}>
            <h2 style={cardTitleStyle}>Active Subscription</h2>
            {account.subscription ? (
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px 24px', marginTop: 12 }}>
                <div>
                  <p style={labelStyle}>Plan</p>
                  <p style={{ fontSize: 14, color: '#0F172A', fontWeight: 600 }}>{account.subscription.planName}</p>
                </div>
                <div>
                  <p style={labelStyle}>Speed</p>
                  <p style={{ fontSize: 14, color: '#0F172A', fontFamily: 'Fira Code, monospace' }}>
                    {account.subscription.downloadMbps}↓ / {account.subscription.uploadMbps}↑ Mbps
                  </p>
                </div>
                <div>
                  <p style={labelStyle}>Monthly Rate</p>
                  <p style={{ fontSize: 14, color: '#0F172A', fontWeight: 600 }}>{formatCurrency(account.subscription.monthlyRate)}</p>
                </div>
                <div>
                  <p style={labelStyle}>Status</p>
                  <span style={{
                    display: 'inline-block',
                    fontSize: 12,
                    fontWeight: 600,
                    padding: '3px 10px',
                    borderRadius: 20,
                    backgroundColor: (statusColors[account.subscription.status] ?? statusColors.PENDING).bg,
                    color: (statusColors[account.subscription.status] ?? statusColors.PENDING).text,
                  }}>
                    {account.subscription.status}
                  </span>
                </div>
              </div>
            ) : (
              <p style={{ fontSize: 14, color: '#94A3B8', marginTop: 12 }}>No active subscription.</p>
            )}
          </div>

          {/* Balance Due */}
          <div style={{ ...cardStyle, border: account.balanceDue > 0 ? '1px solid #FECACA' : '1px solid #E2E8F0' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <h2 style={cardTitleStyle}>Balance Due</h2>
              <span style={{
                fontSize: 24,
                fontWeight: 700,
                fontFamily: 'Fira Code, monospace',
                color: account.balanceDue > 0 ? '#DC2626' : '#16A34A',
              }}>
                {formatCurrency(account.balanceDue)}
              </span>
            </div>
            {account.balanceDue > 0 && (
              <p style={{ fontSize: 13, color: '#DC2626', marginTop: 8 }}>
                You have an outstanding balance. Please settle your invoices to avoid service interruption.
              </p>
            )}
          </div>

          {/* Quick Links */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <Link href="/portal/invoices" style={{ ...cardStyle, textDecoration: 'none', display: 'block', textAlign: 'center', padding: '20px 16px' }}>
              <div style={{ fontSize: 28, marginBottom: 8 }}>🧾</div>
              <p style={{ fontSize: 15, fontWeight: 600, color: '#0891B2' }}>View Invoices</p>
              <p style={{ fontSize: 13, color: '#64748B', marginTop: 2 }}>See your billing history</p>
            </Link>
            <Link href="/portal/tickets" style={{ ...cardStyle, textDecoration: 'none', display: 'block', textAlign: 'center', padding: '20px 16px' }}>
              <div style={{ fontSize: 28, marginBottom: 8 }}>🎫</div>
              <p style={{ fontSize: 15, fontWeight: 600, color: '#0891B2' }}>Support Tickets</p>
              <p style={{ fontSize: 13, color: '#64748B', marginTop: 2 }}>View or raise a ticket</p>
            </Link>
          </div>
        </div>
      )}
    </div>
  );
}

const cardStyle: React.CSSProperties = {
  backgroundColor: '#ffffff',
  borderRadius: 12,
  border: '1px solid #E2E8F0',
  padding: 24,
  boxShadow: '0 1px 3px rgba(0,0,0,0.04)',
};

const cardTitleStyle: React.CSSProperties = {
  fontSize: 15,
  fontWeight: 600,
  color: '#0F172A',
  margin: 0,
};

const labelStyle: React.CSSProperties = {
  fontSize: 11,
  fontWeight: 600,
  color: '#94A3B8',
  textTransform: 'uppercase',
  letterSpacing: '0.05em',
  marginBottom: 2,
};
