import React, { useState } from 'react';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '../ui/card';
import { Button } from '../ui/button';
import { useIsLoggedIn } from '../../lib/isLoggedIn';
import Loader from "../ui/loader";
import { Loader2 } from "lucide-react";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../ui/dialog";
const PRICE_CONFIG = [
    {purchaseType: 'loose', price: 2000, minute: 10000},
    {purchaseType: 'bulk', price: 1000, minute: 10000}
];
export default function STTStreaming(){
    const USER_API_URL = 'https://host-api.cs1.hz.siliconpin.com/v1/users/';
    const [purchaseType, setPurchaseType] = useState();
    const [amount, setAmount] = useState();
    const [dataError, setDataError] = useState();
    const [isProcessing, setIsProcessing] = useState(false);
    const handlePurchaseType = (type) => {
        const selected = PRICE_CONFIG.find(item => item.purchaseType === type);
        setAmount(type === 'bulk' ? selected.price : type === 'loose' ? selected.price : '')
        setPurchaseType(type);
    }

    const handlePurchase = async () => {
        // Validate inputs
        if (!purchaseType) {
            setDataError('Please select a Plan');
            return;
        }

        setIsProcessing(true);
        setDataError(null);
        
        try {
            const formData = new FormData();
            formData.append('service', 'STT Streaming API');
            formData.append('serviceId', 'sttstreamingapi');
            formData.append('cycle', 'monthly');
            formData.append('amount', amount.toString());
            formData.append('service_type', 'streaming_api');
            const response = await fetch(`${USER_API_URL}?query=initiate_payment`, {
                method: 'POST',
                body: formData,  // Using FormData instead of JSON
                credentials: 'include'
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            
            if (data.success) {
                // Redirect to payment success page with order ID
                window.location.href = `/success?service=streaming_api&orderId=${data.order_id}`;
            } else {
                throw new Error(data.message || 'Payment initialization failed');
            }
        } catch (error) {
            console.error('Purchase error:', error);
            setDataError(error.message || 'An error occurred during purchase. Please try again.');
        } finally {
            setIsProcessing(false);
        }
    };
    if(!purchaseType){
        <div>
            <p>{dataError}</p>
        </div>
    }
    return(
        <>
            <div className='container mx-auto'>
                <Card className='max-w-2xl mx-auto px-4 mt-8'>
                    <CardContent>
                        <CardHeader>
                            <CardTitle>STT Streaming API</CardTitle>
                            <CardDescription>Real-time Speech-to-Text (STT) streaming that converts spoken words into accurate, readable text</CardDescription>
                        </CardHeader>
                        <div className='flex flex-row justify-between items-center gap-x-6'>
                            <label htmlFor="purchase-type-loose" className={`border ${purchaseType === 'loose' ? 'bg-[#6d9e37]' : ''} border-[#6d9e37] text-white px-4 py-2 text-center rounded-md w-full cursor-pointer ${isProcessing ? 'opacity-50 cursor-not-allowed' : ''}`}>
                                <input onChange={() => handlePurchaseType('loose')} type="radio" name="purchase-type" id="purchase-type-loose" className='hidden' />
                                <div className='flex flex-col'>
                                    <span className='text-2xl font-bold'>Loose Plan</span>
                                    <span className=''>&#x1F550;10,000 Min &#8377;2000</span>
                                </div>
                            </label>
                            <label htmlFor="purchase-type-bulk" className={`border ${purchaseType === 'bulk' ? 'bg-[#6d9e37]' : ''} border-[#6d9e37] text-white px-4 py-2 text-center rounded-md w-full cursor-pointer ${isProcessing ? 'opacity-50 cursor-not-allowed' : ''}`}>
                                <input onChange={() => handlePurchaseType('bulk')} type="radio" name="purchase-type" id="purchase-type-bulk" className='hidden' />
                                <div className='flex flex-col'>
                                    <span className='text-2xl font-bold'>Bulk Plan</span>
                                    <span className=''>&#x1F550;10,000 Min &#8377;1000</span>
                                </div>
                            </label>
                        </div>
                        <ul className="grid grid-cols-2 justify-between mt-2 gap-x-2 text-xs">
                            {['Setup Charge 5000', '10000 Min INR 2000 in Loose Plan', '10000 Min INR 1000 in Bulk Plan', 'Real-time transcription with high accuracy', 'Supports multiple languages', 'Custom vocabulary for domain-specific terms', 'Integrates easily with video/audio streams', 'Secure and scalable API access', 'Live subtitle overlay options'].map((feature, index) => (
                                <li key={index} className="flex items-start">
                                    <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-2 text-[#6d9e37] shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                                    </svg>
                                    <span className='text-zinc-400'>{feature}</span>
                                </li>
                            ))}
                        </ul>
                        <div className='flex my-8 w-full'>
                            <Button onClick={handlePurchase} disabled={!purchaseType} className={`w-full ${!purchaseType ? 'cursor-not-allowed' : ''}`}>{isProcessing ? (<><Loader2 className="mr-2 h-4 w-4 animate-spin" />Processing...</>) : 'Proceed'}</Button>
                        </div>
                    </CardContent>
                </Card>
            </div>
        </>
    )
}