import React, { useEffect, useMemo, useState } from 'react';
import { usePage } from '@inertiajs/react';
import axios from 'axios';
import { notify } from '@/lib/notify';
import moment from 'moment';

interface EmailRecord {
    id: number;
    uuid: string;
    subject: string;
    to: string;
    body: string;
    submitted_by?: string;
    created_at: string;
}

export default function SentEmails() {
    const { auth } = usePage<{ auth: { user: { api_token: string } } }>().props;
    const [results, setResults] = useState<any>({ data: [], total: 0 });
    const [activeEmail, setActiveEmail] = useState<EmailRecord | null>(null);
    const [currentPage, setCurrentPage] = useState<number>(1);

    const authHeaders = {
        headers: {
            Authorization: `Bearer ${auth?.user?.api_token}`,
        },
    };

    const fetchData = async (page: number = 1) => {
        try {
            const response = await axios.get(`/api/logs/emails/actual?page=${page}`, authHeaders);
            const res = response.data.result;
            setResults(res);
            setCurrentPage(res?.current_page ?? page);
        } catch {
            notify.toastErrorMessage('Something went wrong!');
        }
    };

    useEffect(() => {
        fetchData(1);
    }, []);

    const resultsText = useMemo(() => {
        if (!results?.data) return 'please wait...';
        return `showing ${results.data.length} of ${results.total?.toLocaleString()} result${results.total > 1 ? 's' : ''} found`;
    }, [results]);

    const timeAgo = (date: string) => moment(date).fromNow();
    const formatDate = (date: string) => moment(date).format('ddd, DD/MMM/YYYY');

    const extractTextSnippet = (htmlString?: string) => {
        if (!htmlString) return 'No content';
        htmlString = htmlString.replace(/<style[^>]*>[\s\S]*?<\/style>|<script[^>]*>[\s\S]*?<\/script>/gi, '');
        let text = htmlString.replace(/<[^>]*>/g, '').trim().substring(0, 60);
        return text.replace(/UNICEF South Sudan UNICEF South Sudan/gi, '').split('.')[0] + '.'.trim() + '...';
    };

    const copyMail = () => {
        if (!activeEmail) return;
        const url = `${window.location.host}/logs/email/shared/${activeEmail.id}/${activeEmail.uuid}`;
        navigator.clipboard
            .writeText(url)
            .then(() => notify.toastSuccessMessage('URL copied to clipboard'))
            .catch(() => notify.toastErrorMessage('Failed to copy URL to clipboard.'));
    };

    const [actionLoading, setActionLoading] = useState(false);

    const resendEmail = async () => {
        if (!activeEmail) return;
        if (actionLoading) return;
        setActionLoading(true);
        try {
            await axios.post(`/api/logs/emails/resend/${activeEmail.id}`, {}, authHeaders);
            notify.toastSuccessMessage('Email resend queued');
            // optionally refresh list
            fetchData();
        } catch (err: any) {
            notify.toastErrorMessage(err?.response?.data?.message || 'Failed to resend email');
        } finally {
            setActionLoading(false);
        }
    };

    const deleteEmail = async () => {
        if (!activeEmail) return;
        if (!window.confirm('Are you sure you want to delete this email?')) return;
        if (actionLoading) return;
        setActionLoading(true);
        try {
            await axios.delete(`/api/logs/emails/delete/${activeEmail.id}`, authHeaders);
            notify.toastSuccessMessage('Email deleted');
            // remove from list and clear active email
            fetchData();
            setActiveEmail(null);
        } catch (err: any) {
            notify.toastErrorMessage(err?.response?.data?.message || 'Failed to delete email');
        } finally {
            setActionLoading(false);
        }
    };

    return (
        <div className="bg-white rounded-lg shadow">
            <div className="p-6">
                <div className="grid grid-cols-12 gap-4">
                    {/* Email List */}
                    <div className="col-span-12 md:col-span-4">
                        <ul className="divide-y divide-gray-200 border rounded-lg h-screen overflow-auto">
                            {results?.data?.map((result: EmailRecord, index: number) => (
                                <li
                                    key={`${result.uuid}_${index}`}
                                    className={`p-3 cursor-pointer transition-colors hover:bg-cyan-50 ${
                                        activeEmail?.id === result.id ? 'bg-cyan-50' : ''
                                    }`}
                                    onClick={() => setActiveEmail(result)}
                                >
                                    <div className="flex justify-between items-start">
                                        <h6 className="text-sm font-semibold truncate flex-1">{result.subject}</h6>
                                        <span className="text-[10px] text-gray-500 ml-2 whitespace-nowrap">
                                            {timeAgo(result.created_at)}
                                        </span>
                                    </div>
                                    <p className="text-xs mt-1">
                                        <b>To:</b> {result.to}
                                    </p>
                                    <p className="text-xs text-gray-500 mt-1">
                                        {extractTextSnippet(result.body)}
                                    </p>
                                </li>
                            ))}
                        </ul>
                        {/* Pagination */}
                        {results?.last_page > 1 && (
                            <div className="flex items-center justify-between mt-2 px-2">
                                <div className="text-xs text-gray-500">{resultsText}</div>
                                <div className="flex items-center gap-2">
                                    <button
                                        onClick={() => fetchData((results?.current_page ?? 1) - 1)}
                                        disabled={(results?.current_page ?? 1) <= 1}
                                        className="px-2 py-1 text-xs bg-white border rounded disabled:opacity-50"
                                    >
                                        ‹ Prev
                                    </button>
                                    <button
                                        onClick={() => fetchData((results?.current_page ?? 1) + 1)}
                                        disabled={(results?.current_page ?? 1) >= (results?.last_page ?? 1)}
                                        className="px-2 py-1 text-xs bg-white border rounded disabled:opacity-50"
                                    >
                                        Next ›
                                    </button>
                                </div>
                            </div>
                        )}
                    </div>

                    {/* Email Detail */}
                    <div className="col-span-12 md:col-span-8">
                        {!activeEmail ? (
                            <div className="flex items-center justify-center h-screen text-gray-500">
                                Select an email to view
                            </div>
                        ) : (
                            <div>
                                <div className="mb-4">
                                    <div className="flex justify-between items-start">
                                        <div>
                                            <h6 className="text-sm font-semibold">{activeEmail.subject}</h6>
                                            <p className="text-xs mt-1">
                                                <b>From:</b> {activeEmail.submitted_by}
                                            </p>
                                            <p className="text-xs">
                                                <b>To:</b> {activeEmail.to}
                                            </p>
                                        </div>
                                        <div className="text-right">
                                            <span className="text-xs text-gray-500">
                                                {formatDate(activeEmail.created_at)}
                                            </span>
                                            <div className="mt-2">
                                                <div className="flex items-center gap-3">
                                                    <button
                                                        onClick={copyMail}
                                                        className="text-xs text-indigo-600 hover:text-indigo-800"
                                                    >
                                                        📋 Copy Email
                                                    </button>
                                                    <button
                                                        onClick={resendEmail}
                                                        disabled={actionLoading}
                                                        className="text-xs text-green-600 hover:text-green-800 disabled:opacity-50"
                                                    >
                                                        🔁 Resend
                                                    </button>
                                                    <button
                                                        onClick={deleteEmail}
                                                        disabled={actionLoading}
                                                        className="text-xs text-red-600 hover:text-red-800 disabled:opacity-50"
                                                    >
                                                        🗑️ Delete
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <iframe
                                    srcDoc={activeEmail.body}
                                    className="w-full border-0"
                                    style={{ minHeight: '80vh' }}
                                />
                            </div>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
}

