'use client';

import { useEffect, useState } from 'react';

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

interface WebhookEvent {
  app_id: string;
  app_user_id: string;
  country_code: string;
  currency: string;
  entitlement_ids: string[];
  environment: string;
  event_timestamp_ms: number;
  expiration_at_ms: number;
  is_family_share: boolean;
  offer_code: string | null;
  period_type: string;
  presented_offering_context: any;
  presented_offering_id: string | null;
  price: number;
  price_in_purchased_currency: number;
  product_display_name: string | null;
  product_id: string;
  purchased_at_ms: number;
  renewal_number: number;
  store: string;
  takehome_percentage: number;
  transaction_id: string;
}

interface WebhookResponse {
  status: string;
  error?: string;
}

// UUID validation function
const isValidUUID = (str: string): boolean => {
  const uuidRegex =
    /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
  return uuidRegex.test(str);
};

export default function RevcatClient() {
  const [jsonInput, setJsonInput] = useState('');
  const [eventId, setEventId] = useState('');
  const [eventType, setEventType] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [response, setResponse] = useState<WebhookResponse | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [parsedEvent, setParsedEvent] = useState<WebhookEvent | null>(null);
  const [jsonError, setJsonError] = useState<string | null>(null);
  const [instructionsOpen, setInstructionsOpen] = useState(true);

  const apiClient = useApiClient();

  // Auto-parse JSON when input changes
  useEffect(() => {
    if (!jsonInput.trim()) {
      setParsedEvent(null);
      setJsonError(null);
      return;
    }

    try {
      const parsed = JSON.parse(jsonInput);

      // Validate that app_user_id is not RCAnonymousID
      if (parsed.app_user_id && parsed.app_user_id.includes('$RCAnonymousID')) {
        setJsonError(
          'App User ID cannot be an RCAnonymousID. Please use a real user ID.'
        );
        setParsedEvent(null);
        return;
      }

      // Validate that app_user_id is a valid UUID
      if (parsed.app_user_id && !isValidUUID(parsed.app_user_id)) {
        setJsonError('App User ID must be a valid UUID format.');
        setParsedEvent(null);
        return;
      }

      setParsedEvent(parsed);
      setJsonError(null);
    } catch (err) {
      const errorMessage =
        err instanceof Error ? err.message : 'Invalid JSON format';
      setJsonError(errorMessage);
      setParsedEvent(null);
    }
  }, [jsonInput]);

  // Validate event ID when it changes
  useEffect(() => {
    if (eventId && !isValidUUID(eventId)) {
      setError('Event ID must be a valid UUID format.');
    } else {
      setError(null);
    }
  }, [eventId]);

  const sendWebhook = async () => {
    if (!parsedEvent) {
      setError('Please provide valid JSON data');
      return;
    }

    // Validate required fields
    if (!eventId) {
      setError('Event ID is required');
      return;
    }

    if (!eventType.trim()) {
      setError('Event Type is required');
      return;
    }

    if (!isValidUUID(eventId)) {
      setError('Event ID must be a valid UUID format');
      return;
    }

    if (!isValidUUID(parsedEvent.app_user_id)) {
      setError('App User ID must be a valid UUID format');
      return;
    }

    setIsLoading(true);
    setResponse(null);
    setError(null);

    try {
      // Create the webhook payload structure that matches what the API expects
      const webhookPayload = {
        api_version: '1.0',
        event: {
          aliases: [parsedEvent.app_user_id],
          app_id: parsedEvent.app_id,
          app_user_id: parsedEvent.app_user_id,
          commission_percentage: 0.3,
          country_code: parsedEvent.country_code,
          currency: parsedEvent.currency,
          entitlement_id: null,
          entitlement_ids: parsedEvent.entitlement_ids,
          environment: parsedEvent.environment,
          event_timestamp_ms: parsedEvent.event_timestamp_ms,
          expiration_at_ms: parsedEvent.expiration_at_ms,
          id: eventId,
          is_family_share: parsedEvent.is_family_share,
          offer_code: parsedEvent.offer_code,
          original_app_user_id: parsedEvent.app_user_id,
          original_transaction_id: parsedEvent.transaction_id,
          period_type: parsedEvent.period_type,
          presented_offering_id: parsedEvent.presented_offering_id,
          price: parsedEvent.price,
          price_in_purchased_currency: parsedEvent.price_in_purchased_currency,
          product_id: parsedEvent.product_id,
          purchased_at_ms: parsedEvent.purchased_at_ms,
          store: parsedEvent.store,
          subscriber_attributes: {
            $attConsentStatus: {
              updated_at_ms: parsedEvent.purchased_at_ms,
              value: 'notDetermined',
            },
          },
          takehome_percentage: parsedEvent.takehome_percentage,
          tax_percentage: 0,
          transaction_id: parsedEvent.transaction_id,
          type: eventType,
        },
      };

      // Use the apiClient to send the webhook with proper authentication
      const responseData = await (apiClient.POST as any)(
        '/api/billing/revcat-webhook-replay',
        {
          body: webhookPayload,
        }
      );

      setResponse({
        status: responseData.data?.status || 'success',
        ...responseData.data,
      });
    } catch (err: any) {
      // Handle different types of errors
      if (err.status) {
        // HTTP error with status
        setError(`HTTP ${err.status}: ${err.message || 'Request failed'}`);
      } else if (err.message) {
        // General error with message
        setError(err.message);
      } else {
        // Unknown error
        setError('Failed to send webhook');
      }
    } finally {
      setIsLoading(false);
    }
  };

  const clearAll = () => {
    setJsonInput('');
    setEventId('');
    setEventType('');
    setResponse(null);
    setError(null);
    setParsedEvent(null);
    setJsonError(null);
  };

  const formatTimestamp = (timestamp: number) => {
    return new Date(timestamp).toISOString();
  };

  return (
    <div className='min-h-screen w-full overflow-y-auto bg-black text-white'>
      <div className='w-full px-6 py-6 pb-32'>
        <div className='w-full rounded-lg border border-white bg-black p-6 shadow-lg'>
          <h1 className='mb-4 text-2xl font-bold text-white'>
            RevenueCat Webhook Replay Tool
          </h1>
          <p className='mb-6 text-white'>
            Paste a RevenueCat webhook event JSON below to replay it to the
            billing webhook endpoint.
          </p>

          {/* Collapsible Instructions */}
          <div className='mb-6 w-full rounded-lg border border-white bg-black'>
            <button
              onClick={() => setInstructionsOpen(!instructionsOpen)}
              className='flex w-full items-center justify-between p-4 text-left'
            >
              <h2 className='text-lg font-semibold text-white'>Instructions</h2>
              <span className='text-white'>
                {instructionsOpen ? '▼' : '▶'}
              </span>
            </button>
            {instructionsOpen && (
              <div className='p-4'>
                <ol className='w-full list-inside list-decimal space-y-2 text-sm text-white'>
                  <li>
                    Copy a RevenueCat webhook event JSON from your logs or
                    dashboard
                  </li>
                  <li>
                    Paste it into the text area below (JSON will be validated
                    automatically)
                  </li>
                  <li>
                    Enter a custom Event ID (required - must be a valid UUID)
                  </li>
                  <li>
                    Select the appropriate Event Type from the dropdown
                    (required)
                  </li>
                  <li>
                    Review the event details to ensure everything looks correct
                  </li>
                  <li>
                    Click "Send Webhook" to replay the event to the billing
                    webhook endpoint
                  </li>
                  <li>
                    Check the response to see if the webhook was processed
                    successfully
                  </li>
                </ol>
              </div>
            )}
          </div>

          {/* Event Configuration - At the top */}
          <div className='mb-4 grid w-full grid-cols-1 gap-4 md:grid-cols-2'>
            <div className='w-full'>
              <label
                htmlFor='event-id'
                className='mb-2 block text-sm font-medium text-white'
              >
                Event ID <span className='text-red-400'>*</span>
              </label>
              <input
                id='event-id'
                type='text'
                value={eventId}
                onChange={(e) => setEventId(e.target.value.replace(/\s/g, ''))}
                className='w-full rounded-md border border-white bg-black p-3 text-sm text-white placeholder-gray-400 focus:border-white focus:ring-1 focus:ring-white'
                placeholder='Enter the Event ID (required - must be UUID)'
                disabled={isLoading}
                required
              />
            </div>
            <div className='w-full'>
              <label
                htmlFor='event-type'
                className='mb-2 block text-sm font-medium text-white'
              >
                Event Type <span className='text-red-400'>*</span>
              </label>
              <select
                id='event-type'
                value={eventType}
                onChange={(e) => setEventType(e.target.value)}
                className='w-full rounded-md border border-white bg-black p-3 text-sm text-white focus:border-white focus:ring-1 focus:ring-white'
                disabled={isLoading}
                required
              >
                <option value=''>Select Event Type...</option>
                <option value='INITIAL_PURCHASE'>INITIAL_PURCHASE</option>
                <option value='NON_RENEWING_PURCHASE'>
                  NON_RENEWING_PURCHASE
                </option>
                <option value='RENEWAL'>RENEWAL</option>
                <option value='PRODUCT_CHANGE'>PRODUCT_CHANGE</option>
                <option value='CANCELLATION'>CANCELLATION</option>
                <option value='UNCANCELLATION'>UNCANCELLATION</option>
                <option value='NON_SUBSCRIPTION_PURCHASE'>
                  NON_SUBSCRIPTION_PURCHASE
                </option>
                <option value='SUBSCRIPTION_PAUSED'>SUBSCRIPTION_PAUSED</option>
                <option value='TRANSFER'>TRANSFER</option>
                <option value='EXPIRATION'>EXPIRATION</option>
                <option value='BILLING_ISSUE'>BILLING_ISSUE</option>
                <option value='SUBSCRIBER_ALIAS'>SUBSCRIBER_ALIAS</option>
              </select>
            </div>
          </div>

          {/* Main Content - Side by Side Layout */}
          <div className='grid w-full grid-cols-1 gap-6 lg:grid-cols-2'>
            {/* Left Side - JSON Input */}
            <div className='w-full space-y-4'>
              <div className='flex w-full items-center justify-between'>
                <label
                  htmlFor='json-input'
                  className='block text-sm font-medium text-white'
                >
                  Webhook Event JSON
                </label>
              </div>

              <textarea
                id='json-input'
                value={jsonInput}
                onChange={(e) => setJsonInput(e.target.value)}
                className='h-64 w-full resize-none rounded-md border border-white bg-black p-3 font-mono text-sm text-white placeholder-gray-400 focus:border-white focus:ring-1 focus:ring-white'
                placeholder='Paste your RevenueCat webhook event JSON here...'
                disabled={isLoading}
              />

              {/* JSON Validation Warning */}
              {jsonError && (
                <div className='bg-opacity-20 w-full rounded-md border border-yellow-500 bg-yellow-900 p-3'>
                  <h4 className='mb-1 text-sm font-medium text-yellow-400'>
                    JSON Validation Warning:
                  </h4>
                  <p className='text-sm text-yellow-300'>{jsonError}</p>
                </div>
              )}

              {/* Action Buttons */}
              <div className='flex w-full space-x-4'>
                <Button
                  variant={ButtonVariant.Primary}
                  onClick={sendWebhook}
                  disabled={
                    !parsedEvent ||
                    !eventId ||
                    !eventType.trim() ||
                    isLoading ||
                    !!jsonError
                  }
                >
                  {isLoading ? 'Sending...' : 'Send Webhook'}
                </Button>
                <Button
                  variant={ButtonVariant.Secondary}
                  onClick={clearAll}
                  disabled={isLoading}
                >
                  Clear All
                </Button>
              </div>
            </div>

            {/* Right Side - Event Details */}
            <div className='w-full'>
              {parsedEvent && !jsonError && (
                <div className='w-full rounded-md border border-white bg-black p-4'>
                  <div className='w-full'>
                    <h3 className='mb-3 text-sm font-medium text-white'>
                      Event Details:
                    </h3>
                    <div className='w-full space-y-1 text-sm text-white'>
                      <div>
                        <strong>App User ID:</strong> {parsedEvent.app_user_id}
                      </div>
                      <div>
                        <strong>Product ID:</strong> {parsedEvent.product_id}
                      </div>
                      <div>
                        <strong>Store:</strong> {parsedEvent.store}
                      </div>
                      <div>
                        <strong>Environment:</strong> {parsedEvent.environment}
                      </div>
                      <div>
                        <strong>Price:</strong>{' '}
                        {parsedEvent.price_in_purchased_currency}{' '}
                        {parsedEvent.currency}
                      </div>
                      <div>
                        <strong>Transaction ID:</strong>{' '}
                        {parsedEvent.transaction_id}
                      </div>
                      <div>
                        <strong>Country:</strong> {parsedEvent.country_code}
                      </div>
                      <div>
                        <strong>Entitlements:</strong>{' '}
                        {parsedEvent.entitlement_ids.join(', ')}
                      </div>
                      <div>
                        <strong>Purchased At:</strong>{' '}
                        {formatTimestamp(parsedEvent.purchased_at_ms)}
                      </div>
                      <div>
                        <strong>Expiration At:</strong>{' '}
                        {formatTimestamp(parsedEvent.expiration_at_ms)}
                      </div>
                      <div>
                        <strong>Event Type:</strong>{' '}
                        {eventType || 'Not selected'}
                      </div>
                      <div>
                        <strong>Event ID:</strong> {eventId || 'Not entered'}
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Error Display */}
          {error && (
            <div className='mt-4 w-full rounded-md border border-red-500 bg-black p-4'>
              <h3 className='mb-2 text-sm font-medium text-white'>Error:</h3>
              <p className='text-sm text-white'>{error}</p>
            </div>
          )}

          {/* Response Display */}
          {response && (
            <div className='mt-4 w-full rounded-md border border-white bg-black p-4'>
              <h3 className='mb-2 text-sm font-medium text-white'>
                Webhook Response:
              </h3>
              <pre className='w-full overflow-x-auto rounded border border-white bg-black p-3 text-sm whitespace-pre-wrap text-white'>
                {JSON.stringify(response, null, 2)}
              </pre>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
