import { useQuery } from '@tanstack/react-query';
import React, { useState } from 'react';

import { ButtonVariant } from '@/components/button/Button';
import SpinnerSVG from '@/components/svg/SpinnerSVG';
import { useApiClient } from '@/lib/apiClient';

import { ModalButton } from '../../shared/ModalButton';

interface Props {
  onReasonSelected: (reason: string) => void;
  onBack: () => void;
  isSubmitting?: boolean;
}

// Fallback options in case API fails
const FALLBACK_CHURN_REASONS = [
  { value: 'not_used_enough', label: "I'm not using Suno enough" },
  {
    value: 'expectations_not_met',
    label: "The results don't match my expectations",
  },
  { value: 'missing_features', label: 'Missing features I need' },
  { value: 'better_alternative', label: 'Found better alternative' },
  { value: 'price_too_high', label: 'Price is too high' },
  { value: 'technical_issues', label: 'Technical issues / bugs' },
  { value: 'billing_issues', label: 'Billing / payment issues' },
  { value: 'other', label: 'Other' },
];

const CancelSurveyStep: React.FC<Props> = ({
  onReasonSelected,
  onBack,
  isSubmitting = false,
}) => {
  const [selectedReason, setSelectedReason] = useState<string>('');
  const apiClient = useApiClient();

  // Fetch churn survey options from API
  const { data: surveyOptionsData, isLoading: isLoadingOptions } = useQuery({
    queryKey: ['churnSurveyOptions'],
    queryFn: async () => {
      const response = await apiClient.GET(
        '/api/billing/get-churn-survey-options'
      );
      return response.data;
    },
    staleTime: 5 * 60 * 1000, // Cache for 5 minutes
  });

  // Use API data if available, otherwise fallback to hardcoded options
  const churnReasons = surveyOptionsData?.options || FALLBACK_CHURN_REASONS;

  const handleSubmit = () => {
    if (selectedReason) {
      onReasonSelected(selectedReason);
    }
  };

  return (
    <div>
      <p className='mb-4 text-white/80'>
        We&rsquo;re sad to see you go, but we&rsquo;d love to learn how we can
        improve. Why are you heading out?
      </p>

      <div className='mb-6 rounded-3xl bg-white/10 p-4'>
        {isLoadingOptions ? (
          <div className='flex items-center justify-center py-8'>
            <SpinnerSVG className='h-6 w-6 fill-white/60' />
          </div>
        ) : (
          <div className='space-y-3'>
            {churnReasons.map((reason) => (
              <label
                key={reason.value}
                className='group flex cursor-pointer items-start space-x-3'
              >
                <div className='relative'>
                  <input
                    type='radio'
                    name='churn_reason'
                    value={reason.value}
                    checked={selectedReason === reason.value}
                    onChange={(e) => setSelectedReason(e.target.value)}
                    className='sr-only'
                  />
                  <div
                    className={`flex h-5 w-5 items-center justify-center rounded-full border-2 transition-all duration-200 ${
                      selectedReason === reason.value
                        ? 'border-white bg-white'
                        : 'border-white/30 bg-transparent group-hover:border-white/50'
                    }`}
                  >
                    {selectedReason === reason.value && (
                      <div className='h-2 w-2 rounded-full bg-[#8B5A2B]' />
                    )}
                  </div>
                </div>
                <span className='text-left text-white/90 transition-colors group-hover:text-white'>
                  {reason.label}
                </span>
              </label>
            ))}
          </div>
        )}
      </div>

      <div className='flex justify-center gap-3'>
        <ModalButton
          variant={ButtonVariant.LightGlass}
          onClick={onBack}
          disabled={isSubmitting}
        >
          Back
        </ModalButton>
        <ModalButton
          variant={ButtonVariant.Primary}
          onClick={handleSubmit}
          disabled={!selectedReason || isSubmitting || isLoadingOptions}
          icon={isSubmitting ? <SpinnerSVG className='fill-black' /> : null}
        >
          {isSubmitting ? 'Submitting...' : 'Submit'}
        </ModalButton>
      </div>
    </div>
  );
};

export default CancelSurveyStep;
