'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import axios from 'axios';
import InternalPageTemplate from '@/components/InternalPageTemplate';
import { useAuthStore } from '@/store/authStore';
import { useTranslations } from 'next-intl';

const PLAN_INFO: Record<string, { name: string; color: string; features: string[] }> = {
  free: {
    name: 'Free',
    color: 'bg-gray-100 text-gray-600',
    features: ['Unlimited listings checked', 'See IF a price gap exists'],
  },
  basic: {
    name: 'Basic',
    color: 'bg-blue-100 text-blue-700',
    features: ['5 searches / month', 'Country revealed', 'Cheapest price shown'],
  },
  premium: {
    name: 'Premium',
    color: 'bg-purple-100 text-brand-purple',
    features: ['20 searches / month', 'Country revealed', 'Manual country explorer', 'Price alerts (up to 5)', 'Historical price data'],
  },
  max: {
    name: 'Max',
    color: 'bg-indigo-100 text-indigo-700',
    features: ['100 searches / month', 'Country revealed', 'Manual country explorer', 'Unlimited price alerts', 'Historical price data', 'Priority feature access'],
  },
  business: {
    name: 'Business',
    color: 'bg-yellow-100 text-yellow-700',
    features: ['Custom queries', 'Team seats', 'White-label options', 'API integrations', 'Dedicated support'],
  },
  admin: {
    name: 'Admin',
    color: 'bg-yellow-100 text-yellow-700',
    features: ['Full platform access', 'All features unlocked'],
  },
};

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';

export default function ProfilePage() {
  const router = useRouter();
  const { user, token, isAuthenticated } = useAuthStore();
  const t = useTranslations('profile');

  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [pwStatus, setPwStatus] = useState<{ type: 'success' | 'error'; message: string } | null>(null);
  const [pwLoading, setPwLoading] = useState(false);

  useEffect(() => {
    if (!isAuthenticated) router.push('/signin');
  }, [isAuthenticated, router]);

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

  const planKey = (user.plan || 'free').toLowerCase();
  const plan = PLAN_INFO[planKey] ?? PLAN_INFO['free'];
  const isPaid = planKey !== 'free' && planKey !== 'admin';
  const isAdmin = (user.role || '').toLowerCase() === 'admin';

  async function handleChangePassword(e: React.FormEvent) {
    e.preventDefault();
    setPwStatus(null);

    if (newPassword !== confirmPassword) {
      setPwStatus({ type: 'error', message: t('changePassword.errors.mismatch') });
      return;
    }
    if (newPassword.length < 8) {
      setPwStatus({ type: 'error', message: t('changePassword.errors.tooShort') });
      return;
    }

    setPwLoading(true);
    try {
      await axios.post(
        `${API_URL}/api/auth/change-password`,
        { currentPassword, newPassword },
        { headers: { Authorization: `Bearer ${token}` } }
      );
      setPwStatus({ type: 'success', message: t('changePassword.success') });
      setCurrentPassword('');
      setNewPassword('');
      setConfirmPassword('');
    } catch (err: unknown) {
      const message =
        axios.isAxiosError(err) && err.response?.data?.error
          ? err.response.data.error
          : t('changePassword.errors.generic');
      setPwStatus({ type: 'error', message });
    } finally {
      setPwLoading(false);
    }
  }

  return (
    <InternalPageTemplate>
      {/* Header */}
      <div className="mb-12">
        <h1 className="text-4xl font-bold text-gray-900 mb-4">{t('heading')}</h1>
        <p className="text-gray-500 text-lg max-w-2xl leading-relaxed">
          {t('subheading')}
        </p>
      </div>

      {/* Account info */}
      <div className="mb-10">
        <h2 className="text-lg font-semibold text-gray-900 mb-4">{t('accountInfo.sectionHeading')}</h2>
        <div className="bg-gray-50 border border-gray-100 rounded-2xl divide-y divide-gray-100">
          <div className="flex items-center justify-between px-6 py-4">
            <span className="text-sm text-gray-500">{t('accountInfo.emailLabel')}</span>
            <span className="text-sm font-medium text-gray-900">{user.email}</span>
          </div>
          <div className="flex items-center justify-between px-6 py-4">
            <span className="text-sm text-gray-500">{t('accountInfo.accountIdLabel')}</span>
            <span className="text-sm font-mono text-gray-400">{user.userId}</span>
          </div>
          {user.role && (
            <div className="flex items-center justify-between px-6 py-4">
              <span className="text-sm text-gray-500">{t('accountInfo.roleLabel')}</span>
              <span className="text-xs bg-purple-100 text-brand-purple font-medium px-2.5 py-0.5 rounded-full capitalize">
                {user.role}
              </span>
            </div>
          )}
        </div>
      </div>

      {/* Plan */}
      <div className="mb-10">
        <h2 className="text-lg font-semibold text-gray-900 mb-4">{t('plan.sectionHeading')}</h2>
        <div className="bg-gray-50 border border-gray-100 rounded-2xl p-6">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-3">
              <span className={`text-xs font-semibold px-2.5 py-0.5 rounded-full ${plan.color}`}>
                {plan.name}
              </span>
              {!isPaid && !isAdmin && (
                <span className="text-sm text-gray-400">{t('plan.freePlanLabel')}</span>
              )}
            </div>
            {!isAdmin && (
              <Link
                href={isPaid ? '/billing' : '/pricing'}
                className={`text-sm font-medium px-4 py-2 rounded-md transition-colors ${
                  isPaid
                    ? 'border border-gray-300 text-gray-700 hover:border-gray-400'
                    : 'bg-brand-purple hover:bg-purple-700 text-white'
                }`}
              >
                {isPaid ? t('plan.managePlan') : t('plan.upgrade')}
              </Link>
            )}
          </div>
          <ul className="flex flex-col gap-2">
            {plan.features.map(f => (
              <li key={f} className="flex items-center gap-2 text-sm text-gray-600">
                <svg className="w-4 h-4 text-brand-purple shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                </svg>
                {f}
              </li>
            ))}
          </ul>
          {!isPaid && !isAdmin && (
            <p className="text-xs text-gray-400 mt-4">
              {t('plan.upgradeHint')}
            </p>
          )}
        </div>
      </div>

      {/* Change password */}
      <div className="mb-10">
        <h2 className="text-lg font-semibold text-gray-900 mb-4">{t('changePassword.sectionHeading')}</h2>
        <form
          onSubmit={handleChangePassword}
          className="bg-gray-50 border border-gray-100 rounded-2xl px-6 py-6 flex flex-col gap-4 max-w-md"
        >
          <div className="flex flex-col gap-1.5">
            <label className="text-sm font-medium text-gray-700">{t('changePassword.currentLabel')}</label>
            <input
              type="password"
              value={currentPassword}
              onChange={e => setCurrentPassword(e.target.value)}
              required
              className="border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:border-brand-purple focus:ring-1 focus:ring-brand-purple transition"
            />
          </div>
          <div className="flex flex-col gap-1.5">
            <label className="text-sm font-medium text-gray-700">{t('changePassword.newLabel')}</label>
            <input
              type="password"
              value={newPassword}
              onChange={e => setNewPassword(e.target.value)}
              required
              minLength={8}
              className="border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:border-brand-purple focus:ring-1 focus:ring-brand-purple transition"
            />
          </div>
          <div className="flex flex-col gap-1.5">
            <label className="text-sm font-medium text-gray-700">{t('changePassword.confirmLabel')}</label>
            <input
              type="password"
              value={confirmPassword}
              onChange={e => setConfirmPassword(e.target.value)}
              required
              className="border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:border-brand-purple focus:ring-1 focus:ring-brand-purple transition"
            />
          </div>

          {pwStatus && (
            <p className={`text-sm ${pwStatus.type === 'success' ? 'text-emerald-600' : 'text-red-500'}`}>
              {pwStatus.type === 'success' ? '✓ ' : '✕ '}{pwStatus.message}
            </p>
          )}

          <button
            type="submit"
            disabled={pwLoading}
            className="bg-brand-purple hover:bg-purple-700 text-white text-sm font-medium px-5 py-2.5 rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed self-start"
          >
            {pwLoading ? t('changePassword.submitting') : t('changePassword.submit')}
          </button>
        </form>
      </div>
    </InternalPageTemplate>
  );
}
