'use client';

import { useEffect, useState } from 'react';
import { TransactionDetail, TransactionType } from '../types/transactionDetail.type';
import { TransactionDetailService } from '../services/transactionDetailService';
import TopupDetailCard from './details/TopupDetailCard';
import WithdrawalDetailCard from './details/WithdrawalDetailCard';
import ChargeDetailCard from './details/ChargeDetailCard';
import { Typography } from '@/components/atoms/typogrpahy';

// Simple Loading Component
const LoadingSpinner = () => (
  <div className="flex items-center justify-center">
    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
  </div>
);

interface TransactionDetailComponentProps {
  transactionId: string;
  expectedType?: TransactionType;
}

const TransactionDetailComponent: React.FC<TransactionDetailComponentProps> = ({ 
  transactionId, 
  expectedType 
}) => {
  const [transaction, setTransaction] = useState<TransactionDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchTransaction = async () => {
      try {
        setLoading(true);
        const transactionService = new TransactionDetailService();
        
        // Use updated service method that handles token internally
        const transactionData = await transactionService.getTransactionDetail(transactionId);

        ;
        
        // Validate expected type if provided
        if (expectedType && transactionData.transaction_type !== expectedType) {
          setError(`Expected ${expectedType} transaction, but got ${transactionData.transaction_type}`);
          return;
        }
        
        setTransaction(transactionData);
      } catch (err) {
        console.error('Error fetching transaction:', err);
        setError('Failed to load transaction details');
      } finally {
        setLoading(false);
      }
    };

    fetchTransaction();
  }, [transactionId, expectedType]);

  const renderTransactionDetail = () => {
    if (!transaction) return null;

    // Normalize transaction_type to uppercase for case-insensitive matching
    const transactionType = transaction.transaction_type 
      ? String(transaction.transaction_type).toUpperCase() 
      : null;
    
    if (!transactionType) {
      return (
        <div className="bg-white dark:bg-gray-800 rounded-2xl p-6 shadow-sm border border-gray-100 dark:border-gray-700">
          <Typography variant="h4" className="mb-4">Transaction Type Not Available</Typography>
          <Typography variant="b2">Transaction type is missing from the response.</Typography>
          <Typography variant="b2" className="mt-2 text-gray-500">
            Transaction ID: {transaction.id}
          </Typography>
        </div>
      );
    }

    switch (transactionType) {
      case 'TOPUP':
        return <TopupDetailCard transaction={transaction} />;
      
      case 'WITHDRAWAL':
        return <WithdrawalDetailCard transaction={transaction} />;
      
      case 'INVOICE':
        return (
          <div className="bg-white dark:bg-gray-800 rounded-2xl p-6 shadow-sm border border-gray-100 dark:border-gray-700">
            <Typography variant="h4" className="mb-4">Invoice Transaction</Typography>
            <Typography variant="b2">Invoice details component coming soon...</Typography>
          </div>
        );
      
      case 'CHARGE':
        return <ChargeDetailCard transaction={transaction} />;
      
      case 'RESERVATION':
        return (
          <div className="bg-white dark:bg-gray-800 rounded-2xl p-6 shadow-sm border border-gray-100 dark:border-gray-700">
            <Typography variant="h4" className="mb-4">Reservation Transaction</Typography>
            <Typography variant="b2">Reservation details component coming soon...</Typography>
          </div>
        );
      
      default:
        return (
          <div className="bg-white dark:bg-gray-800 rounded-2xl p-6 shadow-sm border border-gray-100 dark:border-gray-700">
            <Typography variant="h4" className="mb-4">Unknown Transaction Type</Typography>
            <Typography variant="b2">Type: {transactionType}</Typography>
            <Typography variant="b2" className="mt-2 text-gray-500">
              Transaction ID: {transaction.id}
            </Typography>
          </div>
        );
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center">
        <LoadingSpinner />
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center">
        <div className="bg-white dark:bg-gray-800 rounded-2xl p-8 shadow-sm border border-gray-100 dark:border-gray-700 max-w-md w-full mx-4">
          <div className="text-center">
            <div className="w-16 h-16 bg-red-100 dark:bg-red-900/20 rounded-full flex items-center justify-center mx-auto mb-4">
              <svg className="w-8 h-8 text-red-600 dark:text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
              </svg>
            </div>
            <Typography variant="h4" className="mb-2 text-gray-800 dark:text-gray-200">
              Error Loading Transaction
            </Typography>
            <Typography variant="b2" className="text-gray-600 dark:text-gray-400 mb-4">
              {error}
            </Typography>
            <button
              onClick={() => window.history.back()}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
            >
              Go Back
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 py-6">
      <div className="max-w-2xl mx-auto px-4">
        {/* Header */}
        <div className="mb-6">
          <button
            onClick={() => window.history.back()}
            className="flex items-center gap-2 text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 transition-colors mb-4"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 19l-7-7 7-7" />
            </svg>
            Back
          </button>
          
          <Typography variant="h2" className="font-bold text-gray-900 dark:text-gray-100">
            Transaction Detail
          </Typography>
          <Typography variant="b2" className="text-gray-600 dark:text-gray-400">
            {transaction ? `${transaction.transaction_type} Transaction` : 'Loading...'}
          </Typography>
        </div>

        {/* Transaction Detail Card */}
        {renderTransactionDetail()}
      </div>
    </div>
  );
};

export default TransactionDetailComponent;
