import { Fragment, useState, useEffect } from 'react';
import { Dialog, Transition, Tab } from '@headlessui/react';
import axios from 'axios';
import Swal from 'sweetalert2';

interface AutoCallerModalProps {
    isOpen: boolean;
    onClose: () => void;
    bookingId?: string | null;
    customerId?: string | null;
    customerName?: string;
    customerPhone?: string;
    bookingDate?: string;
    bookingTime?: string;
    packageName?: string;
}

interface Conversation {
    _id: string;
    customer_name: string;
    customer_phone: string;
    call_status: string;
    call_duration: number;
    conversation: Array<{
        role: string;
        message: string;
        timestamp: string;
    }>;
    booking_confirmed: boolean;
    recording_url?: string;
    scheduled_datetime?: string;
    status: string;
    created_at: string;
}

const AutoCallerModal = ({
    isOpen,
    onClose,
    bookingId,
    customerId,
    customerName = '',
    customerPhone = '',
    bookingDate,
    bookingTime,
    packageName
}: AutoCallerModalProps) => {
    const [loading, setLoading] = useState(false);
    const [conversations, setConversations] = useState<Conversation[]>([]);
    const [loadingConversations, setLoadingConversations] = useState(false);
    const [selectedConversation, setSelectedConversation] = useState<Conversation | null>(null);

    // Form state for manual call
    const [formData, setFormData] = useState({
        customer_name: customerName,
        customer_phone: customerPhone,
    });

    useEffect(() => {
        if (isOpen) {
            setFormData({
                customer_name: customerName,
                customer_phone: customerPhone,
            });
            loadConversations();
        }
    }, [isOpen, customerName, customerPhone, bookingId, customerId]);

    const loadConversations = async () => {
        if (!bookingId && !customerId) return;

        setLoadingConversations(true);
        try {
            const endpoint = bookingId
                ? `/api/auto-caller/booking-conversations/${bookingId}`
                : `/api/auto-caller/customer-conversations/${customerId}`;

            const response = await axios.get(endpoint);
            if (response.data.success) {
                setConversations(response.data.data || []);
            }
        } catch (error: any) {
            console.error('Error loading conversations:', error);
        } finally {
            setLoadingConversations(false);
        }
    };

    const handleInitiateCall = async () => {
        if (!formData.customer_phone) {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Customer phone number is required',
            });
            return;
        }

        setLoading(true);
        try {
            const companyId = localStorage.getItem('companyId') || '1';
            const response = await axios.post('/api/auto-caller/initiate', {
                booking_id: bookingId,
                customer_id: customerId,
                customer_name: formData.customer_name,
                customer_phone: formData.customer_phone,
                company_id: companyId,
            });

            if (response.data.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Success',
                    text: 'Call initiated successfully!',
                    timer: 2000,
                });
                loadConversations();
            } else {
                throw new Error(response.data.message || 'Failed to initiate call');
            }
        } catch (error: any) {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: error.response?.data?.message || error.message || 'Failed to initiate call',
            });
        } finally {
            setLoading(false);
        }
    };

    const handleRetryCall = async (agentChatId: string) => {
        try {
            const response = await axios.post(`/api/auto-caller/retry/${agentChatId}`);
            if (response.data.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Success',
                    text: 'Call retry initiated!',
                    timer: 2000,
                });
                loadConversations();
            }
        } catch (error: any) {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: error.response?.data?.message || 'Failed to retry call',
            });
        }
    };

    const handleDeleteConversation = async (agentChatId: string) => {
        const result = await Swal.fire({
            icon: 'warning',
            title: 'Are you sure?',
            text: 'This will delete the conversation permanently',
            showCancelButton: true,
            confirmButtonText: 'Yes, delete it',
            cancelButtonText: 'Cancel',
        });

        if (result.isConfirmed) {
            try {
                await axios.delete(`/api/auto-caller/conversation/${agentChatId}`);
                Swal.fire({
                    icon: 'success',
                    title: 'Deleted',
                    text: 'Conversation deleted successfully',
                    timer: 2000,
                });
                loadConversations();
                setSelectedConversation(null);
            } catch (error: any) {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Failed to delete conversation',
                });
            }
        }
    };

    const formatDate = (dateString: string) => {
        return new Date(dateString).toLocaleString('en-US', {
            month: 'short',
            day: 'numeric',
            year: 'numeric',
            hour: 'numeric',
            minute: '2-digit',
            hour12: true,
        });
    };

    const getStatusBadge = (status: string, callStatus?: string) => {
        if (status === 'executed' && callStatus === 'completed') {
            return <span className="badge bg-success">Completed</span>;
        } else if (status === 'in-progress' || status === 'initiating') {
            return <span className="badge bg-info">In Progress</span>;
        } else if (status === 'failed') {
            return <span className="badge bg-danger">Failed</span>;
        } else if (status === 'scheduled') {
            return <span className="badge bg-warning">Scheduled</span>;
        }
        return <span className="badge bg-secondary">{status}</span>;
    };

    return (
        <Transition appear show={isOpen} as={Fragment}>
            <Dialog as="div" open={isOpen} onClose={onClose} className="relative z-50">
                <Transition.Child
                    as={Fragment}
                    enter="ease-out duration-300"
                    enterFrom="opacity-0"
                    enterTo="opacity-100"
                    leave="ease-in duration-200"
                    leaveFrom="opacity-100"
                    leaveTo="opacity-0"
                >
                    <div className="fixed inset-0 bg-[black]/60" />
                </Transition.Child>
                <div className="fixed inset-0 overflow-y-auto">
                    <div className="flex min-h-full items-center justify-center px-4 py-8">
                        <Transition.Child
                            as={Fragment}
                            enter="ease-out duration-300"
                            enterFrom="opacity-0 scale-95"
                            enterTo="opacity-100 scale-100"
                            leave="ease-in duration-200"
                            leaveFrom="opacity-100 scale-100"
                            leaveTo="opacity-0 scale-95"
                        >
                            <Dialog.Panel className="panel w-full max-w-4xl overflow-hidden rounded-lg border-0 p-0 text-black dark:text-white-dark">
                                <div className="flex items-center justify-between bg-[#fbfbfb] px-5 py-3 dark:bg-[#121c2c]">
                                    <h5 className="text-lg font-bold">AI Calling Agent</h5>
                                    <button type="button" onClick={onClose} className="text-white-dark hover:text-dark">
                                        <svg
                                            xmlns="http://www.w3.org/2000/svg"
                                            width="20"
                                            height="20"
                                            viewBox="0 0 24 24"
                                            fill="none"
                                            stroke="currentColor"
                                            strokeWidth="1.5"
                                            strokeLinecap="round"
                                            strokeLinejoin="round"
                                        >
                                            <line x1="18" y1="6" x2="6" y2="18"></line>
                                            <line x1="6" y1="6" x2="18" y2="18"></line>
                                        </svg>
                                    </button>
                                </div>
                                <div className="p-5">
                                    <Tab.Group>
                                        <Tab.List className="mt-3 flex flex-wrap border-b border-white-light dark:border-[#191e3a]">
                                            <Tab as={Fragment}>
                                                {({ selected }) => (
                                                    <button
                                                        className={`${
                                                            selected ? 'text-primary !outline-none before:!w-full' : ''
                                                        } relative -mb-[1px] flex items-center p-5 py-3 before:absolute before:bottom-0 before:left-0 before:right-0 before:m-auto before:inline-block before:h-[1px] before:w-0 before:bg-primary before:transition-all before:duration-700 hover:text-primary hover:before:w-full`}
                                                    >
                                                        <svg className="h-5 w-5 ltr:mr-2 rtl:ml-2" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                            <circle cx="12" cy="6" r="4" stroke="currentColor" strokeWidth="1.5" />
                                                            <path
                                                                opacity="0.5"
                                                                d="M20 17.5C20 19.9853 20 22 12 22C4 22 4 19.9853 4 17.5C4 15.0147 7.58172 13 12 13C16.4183 13 20 15.0147 20 17.5Z"
                                                                stroke="currentColor"
                                                                strokeWidth="1.5"
                                                            />
                                                        </svg>
                                                        Initiate Call
                                                    </button>
                                                )}
                                            </Tab>
                                            <Tab as={Fragment}>
                                                {({ selected }) => (
                                                    <button
                                                        className={`${
                                                            selected ? 'text-primary !outline-none before:!w-full' : ''
                                                        } relative -mb-[1px] flex items-center p-5 py-3 before:absolute before:bottom-0 before:left-0 before:right-0 before:m-auto before:inline-block before:h-[1px] before:w-0 before:bg-primary before:transition-all before:duration-700 hover:text-primary hover:before:w-full`}
                                                    >
                                                        <svg className="h-5 w-5 ltr:mr-2 rtl:ml-2" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                            <path
                                                                d="M2 12C2 8.22876 2 6.34315 3.17157 5.17157C4.34315 4 6.22876 4 10 4H14C17.7712 4 19.6569 4 20.8284 5.17157C22 6.34315 22 8.22876 22 12C22 15.7712 22 17.6569 20.8284 18.8284C19.6569 20 17.7712 20 14 20H10C6.22876 20 4.34315 20 3.17157 18.8284C2 17.6569 2 15.7712 2 12Z"
                                                                stroke="currentColor"
                                                                strokeWidth="1.5"
                                                            />
                                                            <path opacity="0.5" d="M7 4V2.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                                            <path opacity="0.5" d="M17 4V2.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                                            <path opacity="0.5" d="M2 9H22" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                                        </svg>
                                                        Call History
                                                    </button>
                                                )}
                                            </Tab>
                                        </Tab.List>
                                        <Tab.Panels>
                                            <Tab.Panel>
                                                <div className="pt-5">
                                                    {bookingId && (
                                                        <div className="mb-4 rounded-md bg-primary-light p-4 text-primary">
                                                            <h6 className="mb-2 font-semibold">Booking Details:</h6>
                                                            <div className="space-y-1 text-sm">
                                                                {packageName && <p><strong>Package:</strong> {packageName}</p>}
                                                                {bookingDate && <p><strong>Date:</strong> {bookingDate}</p>}
                                                                {bookingTime && <p><strong>Time:</strong> {bookingTime}</p>}
                                                            </div>
                                                        </div>
                                                    )}
                                                    <div className="grid grid-cols-1 gap-5 md:grid-cols-2">
                                                        <div>
                                                            <label htmlFor="customer_name">Customer Name</label>
                                                            <input
                                                                id="customer_name"
                                                                type="text"
                                                                placeholder="Enter Customer Name"
                                                                className="form-input"
                                                                value={formData.customer_name}
                                                                onChange={(e) =>
                                                                    setFormData({
                                                                        ...formData,
                                                                        customer_name: e.target.value,
                                                                    })
                                                                }
                                                            />
                                                        </div>
                                                        <div>
                                                            <label htmlFor="customer_phone">Customer Phone *</label>
                                                            <input
                                                                id="customer_phone"
                                                                type="text"
                                                                placeholder="Enter Customer Phone"
                                                                className="form-input"
                                                                value={formData.customer_phone}
                                                                onChange={(e) =>
                                                                    setFormData({
                                                                        ...formData,
                                                                        customer_phone: e.target.value,
                                                                    })
                                                                }
                                                            />
                                                        </div>
                                                    </div>
                                                    <div className="mt-8 flex items-center justify-end">
                                                        <button type="button" onClick={onClose} className="btn btn-outline-danger">
                                                            Cancel
                                                        </button>
                                                        <button
                                                            type="button"
                                                            onClick={handleInitiateCall}
                                                            className="btn btn-primary ltr:ml-4 rtl:mr-4"
                                                            disabled={loading}
                                                        >
                                                            {loading ? (
                                                                <span className="inline-flex items-center">
                                                                    <svg className="h-4 w-4 animate-spin ltr:mr-2 rtl:ml-2" viewBox="0 0 24 24" fill="none">
                                                                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                                                        <path
                                                                            className="opacity-75"
                                                                            fill="currentColor"
                                                                            d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                                                                        ></path>
                                                                    </svg>
                                                                    Initiating...
                                                                </span>
                                                            ) : (
                                                                'Initiate Call'
                                                            )}
                                                        </button>
                                                    </div>
                                                </div>
                                            </Tab.Panel>
                                            <Tab.Panel>
                                                <div className="pt-5">
                                                    {loadingConversations ? (
                                                        <div className="flex items-center justify-center py-8">
                                                            <svg className="h-8 w-8 animate-spin text-primary" viewBox="0 0 24 24" fill="none">
                                                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                                                <path
                                                                    className="opacity-75"
                                                                    fill="currentColor"
                                                                    d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                                                                ></path>
                                                            </svg>
                                                        </div>
                                                    ) : conversations.length === 0 ? (
                                                        <div className="py-8 text-center text-gray-500">No call history found</div>
                                                    ) : (
                                                        <div className="grid grid-cols-1 gap-4">
                                                            {conversations.map((conv) => (
                                                                <div
                                                                    key={conv._id}
                                                                    className="cursor-pointer rounded-lg border border-gray-200 p-4 hover:border-primary dark:border-gray-700"
                                                                    onClick={() => setSelectedConversation(conv)}
                                                                >
                                                                    <div className="mb-2 flex items-center justify-between">
                                                                        <div>
                                                                            <h6 className="font-semibold">{conv.customer_name}</h6>
                                                                            <p className="text-xs text-gray-500">{conv.customer_phone}</p>
                                                                        </div>
                                                                        {getStatusBadge(conv.status, conv.call_status)}
                                                                    </div>
                                                                    <div className="flex items-center justify-between text-xs text-gray-500">
                                                                        <span>{formatDate(conv.created_at)}</span>
                                                                        {conv.call_duration > 0 && <span>{conv.call_duration}s</span>}
                                                                    </div>
                                                                    {conv.booking_confirmed && (
                                                                        <div className="mt-2">
                                                                            <span className="badge bg-success">Booking Confirmed</span>
                                                                        </div>
                                                                    )}
                                                                </div>
                                                            ))}
                                                        </div>
                                                    )}

                                                    {selectedConversation && (
                                                        <Transition appear show={selectedConversation !== null} as={Fragment}>
                                                            <Dialog
                                                                as="div"
                                                                open={selectedConversation !== null}
                                                                onClose={() => setSelectedConversation(null)}
                                                                className="relative z-50"
                                                            >
                                                                <Transition.Child
                                                                    as={Fragment}
                                                                    enter="ease-out duration-300"
                                                                    enterFrom="opacity-0"
                                                                    enterTo="opacity-100"
                                                                    leave="ease-in duration-200"
                                                                    leaveFrom="opacity-100"
                                                                    leaveTo="opacity-0"
                                                                >
                                                                    <div className="fixed inset-0 bg-[black]/60" />
                                                                </Transition.Child>
                                                                <div className="fixed inset-0 overflow-y-auto">
                                                                    <div className="flex min-h-full items-center justify-center px-4 py-8">
                                                                        <Transition.Child
                                                                            as={Fragment}
                                                                            enter="ease-out duration-300"
                                                                            enterFrom="opacity-0 scale-95"
                                                                            enterTo="opacity-100 scale-100"
                                                                            leave="ease-in duration-200"
                                                                            leaveFrom="opacity-100 scale-100"
                                                                            leaveTo="opacity-0 scale-95"
                                                                        >
                                                                            <Dialog.Panel className="panel w-full max-w-2xl overflow-hidden rounded-lg border-0 p-0">
                                                                                <div className="flex items-center justify-between bg-[#fbfbfb] px-5 py-3 dark:bg-[#121c2c]">
                                                                                    <h5 className="text-lg font-bold">Conversation Details</h5>
                                                                                    <button
                                                                                        type="button"
                                                                                        onClick={() => setSelectedConversation(null)}
                                                                                        className="text-white-dark hover:text-dark"
                                                                                    >
                                                                                        <svg
                                                                                            xmlns="http://www.w3.org/2000/svg"
                                                                                            width="20"
                                                                                            height="20"
                                                                                            viewBox="0 0 24 24"
                                                                                            fill="none"
                                                                                            stroke="currentColor"
                                                                                            strokeWidth="1.5"
                                                                                            strokeLinecap="round"
                                                                                            strokeLinejoin="round"
                                                                                        >
                                                                                            <line x1="18" y1="6" x2="6" y2="18"></line>
                                                                                            <line x1="6" y1="6" x2="18" y2="18"></line>
                                                                                        </svg>
                                                                                    </button>
                                                                                </div>
                                                                                <div className="p-5">
                                                                                    <div className="mb-4 space-y-2">
                                                                                        <div className="flex items-center justify-between">
                                                                                            <div>
                                                                                                <p className="font-semibold">{selectedConversation.customer_name}</p>
                                                                                                <p className="text-xs text-gray-500">{selectedConversation.customer_phone}</p>
                                                                                            </div>
                                                                                            {getStatusBadge(selectedConversation.status, selectedConversation.call_status)}
                                                                                        </div>
                                                                                        <p className="text-xs text-gray-500">{formatDate(selectedConversation.created_at)}</p>
                                                                                    </div>

                                                                                    {selectedConversation.recording_url && (
                                                                                        <div className="mb-4">
                                                                                            <audio controls className="w-full">
                                                                                                <source src={selectedConversation.recording_url} type="audio/mpeg" />
                                                                                            </audio>
                                                                                        </div>
                                                                                    )}

                                                                                    {selectedConversation.conversation && selectedConversation.conversation.length > 0 ? (
                                                                                        <div className="space-y-3">
                                                                                            <h6 className="font-semibold">Conversation:</h6>
                                                                                            <div className="max-h-96 space-y-2 overflow-y-auto">
                                                                                                {selectedConversation.conversation.map((msg, idx) => (
                                                                                                    <div
                                                                                                        key={idx}
                                                                                                        className={`rounded-lg p-3 ${
                                                                                                            msg.role === 'assistant'
                                                                                                                ? 'bg-primary-light text-primary'
                                                                                                                : 'bg-gray-100 dark:bg-gray-700'
                                                                                                        }`}
                                                                                                    >
                                                                                                        <p className="mb-1 text-xs font-semibold uppercase">
                                                                                                            {msg.role === 'assistant' ? 'AI Agent' : 'Customer'}
                                                                                                        </p>
                                                                                                        <p className="text-sm">{msg.message}</p>
                                                                                                        {msg.timestamp && (
                                                                                                            <p className="mt-1 text-xs opacity-70">
                                                                                                                {new Date(msg.timestamp).toLocaleTimeString()}
                                                                                                            </p>
                                                                                                        )}
                                                                                                    </div>
                                                                                                ))}
                                                                                            </div>
                                                                                        </div>
                                                                                    ) : (
                                                                                        <div className="py-4 text-center text-gray-500">No conversation data available</div>
                                                                                    )}

                                                                                    <div className="mt-5 flex items-center justify-end space-x-3">
                                                                                        {selectedConversation.status === 'failed' && (
                                                                                            <button
                                                                                                type="button"
                                                                                                onClick={() => handleRetryCall(selectedConversation._id)}
                                                                                                className="btn btn-warning"
                                                                                            >
                                                                                                Retry Call
                                                                                            </button>
                                                                                        )}
                                                                                        <button
                                                                                            type="button"
                                                                                            onClick={() => handleDeleteConversation(selectedConversation._id)}
                                                                                            className="btn btn-danger"
                                                                                        >
                                                                                            Delete
                                                                                        </button>
                                                                                        <button
                                                                                            type="button"
                                                                                            onClick={() => setSelectedConversation(null)}
                                                                                            className="btn btn-outline-dark"
                                                                                        >
                                                                                            Close
                                                                                        </button>
                                                                                    </div>
                                                                                </div>
                                                                            </Dialog.Panel>
                                                                        </Transition.Child>
                                                                    </div>
                                                                </div>
                                                            </Dialog>
                                                        </Transition>
                                                    )}
                                                </div>
                                            </Tab.Panel>
                                        </Tab.Panels>
                                    </Tab.Group>
                                </div>
                            </Dialog.Panel>
                        </Transition.Child>
                    </div>
                </div>
            </Dialog>
        </Transition>
    );
};

export default AutoCallerModal;
