'use client';

import React from 'react';
import { useSubscription } from './subscription-context';

const SubscriptionPanel: React.FC = () => {
  const { state, isTrialActive, daysLeftInTrial, isEntitled, startTrial, endTrial, purchase, cancel, reset } = useSubscription();

  return (
    <div className="mt-6 bg-white rounded-xl border shadow-sm p-6">
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-semibold">Subscription</h3>
          <p className="text-sm text-gray-600">Manage your Data4Autos subscription & free trial.</p>
        </div>
        <div className="text-right">
          <div className="text-sm">
            Status:{' '}
            {state.active ? (
              <span className="inline-block px-2 py-0.5 rounded bg-emerald-50 text-emerald-700 border border-emerald-200">
                Active
              </span>
            ) : (
              <span className="inline-block px-2 py-0.5 rounded bg-gray-100 text-gray-700 border">
                Inactive
              </span>
            )}
          </div>
          {isTrialActive && (
            <div className="text-xs text-emerald-700">
              Trial: {daysLeftInTrial} day(s) left
            </div>
          )}
        </div>
      </div>

      <div className="mt-5 flex flex-wrap gap-3">
        {!state.active && !isTrialActive && (
          <button
            onClick={() => startTrial(7)}
            className="px-4 py-2 rounded-lg bg-slate-900 text-white hover:bg-black transition"
          >
            Start 7-day Free Trial
          </button>
        )}

        {isTrialActive && (
          <button
            onClick={endTrial}
            className="px-4 py-2 rounded-lg border hover:bg-gray-50 transition"
          >
            End Trial
          </button>
        )}

        {!state.active && (
          <button
            onClick={purchase}
            className="px-4 py-2 rounded-lg bg-gradient-to-r from-blue-600 to-purple-600 text-white hover:from-blue-700 hover:to-purple-700 transition"
          >
            Purchase Subscription
          </button>
        )}

        {state.active && (
          <button
            onClick={cancel}
            className="px-4 py-2 rounded-lg border hover:bg-gray-50 transition"
          >
            Cancel Subscription
          </button>
        )}

        {/* Dev helper (remove in production) */}
        <button
          onClick={reset}
          className="px-4 py-2 rounded-lg border border-red-300 text-red-700 hover:bg-red-50 transition"
        >
          Reset (Dev)
        </button>
      </div>

      {!isEntitled && (
        <p className="text-xs text-gray-500 mt-3">
          Subscription is required to access premium pages. You can still start a 7-day free trial.
        </p>
      )}
    </div>
  );
};

export default SubscriptionPanel;
