import React from "react";
import { Link, useParams } from "react-router-dom";
import { useState, useEffect } from "react";
import user from "../../../assets/images/auth/user.png";
import IconCaretLeft from "../../../components/Icon/IconCaretLeft";
import Tooltip from "../../../components/Tooltip";
import IconAcademicCap from "../../../components/Icon/IconAcademicCap";
import ConvertStudent from "../../../modals/lead_marketing/ConvertStudent";
import Button from "../../../components/Buttons";
import IconMail from "../../../components/Icon/IconMail";
import IconPhone from "../../../components/Icon/IconPhone";
import IconUser from "../../../components/Icon/IconUser";
import IconTag from "../../../components/Icon/IconTag";
import IconClipboardText from "../../../components/Icon/IconClipboardText";
import Tabs from "../../../components/Tabs";
import IconClock from "../../../components/Icon/IconClock";
import IconCalendar from "../../../components/Icon/IconCalendar";
import IconInfoCircle from "../../../components/Icon/IconInfoCircle";
import IconLoader from "../../../components/Icon/IconLoader";
import api from "../../../api/axios";
import { toast } from "react-toastify";
import { decodeId } from '../../../utils/hashId';

interface LeadDetail {
    id: number;
    lead_name: string;
    lead_email: string;
    lead_mobile: string;
    lead_value: number;
    lead_priority: 'low' | 'medium' | 'high';
    status: number;
    branch_name: string;
    lead_source_name: string;
    assigned_staff_name: string;
    created_at: string;
    updated_at: string;
    remarks?: string;
    timeline?: TimelineItem[];
    comments?: CommentItem[];
    reminders?: ReminderItem[];
}

interface TimelineItem {
    id: number;
    action: string;
    field_name?: string;
    old_value?: string;
    new_value?: string;
    description: string;
    performed_by: string;
    created_at: string;
    performer?: {
        staff_name:string;

    };
}

interface CommentItem {
    id: number;
    comment: string;
    created_by: string;
    created_at: string;
}

interface ReminderItem {
    id: number;
    type: string;
    notes: string;
    follow_up_date: string;
    follow_up_time: string;
    assigned_staff?: {
        staff_name:string;
    };
    status: string;
}

interface FollowUp {
    id: number;
    title: string;
    description: string;
    type: string;
    reminder_date: string;
    reminder_time: string;
    status: string;
    assigned_staff?: {
        staff_name:string;
    };
    created_at: string;
}

const statusMap: Record<number, { label: string; color: string }> = {
    0: { label: 'New', color: 'bg-primary/20 text-primary' },
    1: { label: 'Inactive', color: 'bg-danger/20 text-danger' },
    3: { label: 'Contacted', color: 'bg-info/20 text-info' },
    4: { label: 'Interested', color: 'bg-success/20 text-success' },
    5: { label: 'Converted', color: 'bg-success/20 text-success' },
    6: { label: 'Follow-up', color: 'bg-warning/20 text-warning' },
    7: { label: 'Lost', color: 'bg-danger/20 text-danger' },
};

const priorityColors = {
    low: 'bg-warning/20 text-warning',
    medium: 'bg-info/20 text-info',
    high: 'bg-danger/20 text-danger'
};

const LeadView = () => {
    const { id: encryptedId } = useParams();
    const leadId = decodeId(encryptedId || '');

    const [lead, setLead] = useState<LeadDetail | null>(null);
    const [loading, setLoading] = useState(true);
    const [activeTab, setActiveTab] = useState("activity");
    const [convertStud, setConvertStud] = useState(false);
    const [followUps, setFollowUps] = useState<FollowUp[]>([]);

    // Fetch lead details
    const fetchLeadDetails = async () => {
        if (!leadId) return;

        setLoading(true);
        try {
            const response = await api.get(`/lead/view/${leadId}`);
            if (response.data.status === true) {
                setLead(response.data.data);
                // Fetch follow-ups separately if needed
                await fetchFollowUps();
            } else {
                toast.error('Failed to load lead details');
            }
        } catch (error: any) {
            console.error('Error fetching lead details:', error);
            toast.error(error.response?.data?.message || 'Failed to load lead details');
        } finally {
            setLoading(false);
        }
    };

    // Fetch reminders
    const fetchFollowUps = async () => {
        try {
            const response = await api.get(`/lead/reminders/${leadId}`);
            if (response.data.status === true) {
                setFollowUps(response.data.data);
            }
        } catch (error) {
            console.error('Error fetching reminders:', error);
        }
    };

    useEffect(() => {
        fetchLeadDetails();
    }, [leadId]);

    // Format date for display
    const formatDate = (date: string) => {
        if (!date) return 'N/A';
        return new Date(date).toLocaleDateString('en-US', {
            day: '2-digit',
            month: 'short',
            year: 'numeric'
        });
    };

    const formatDateTime = (date: string) => {
        if (!date) return 'N/A';
        return new Date(date).toLocaleString('en-US', {
            day: '2-digit',
            month: 'short',
            year: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    };

    // Get status display
    const getStatusDisplay = (status: number) => {
        return statusMap[status] || statusMap[0];
    };

    // Get priority display
    const getPriorityDisplay = (priority: string) => {
        return priorityColors[priority as keyof typeof priorityColors] || priorityColors.medium;
    };

    // Format timeline items for Timeline component
    const formatTimelineItems = (timeline: TimelineItem[] | undefined) => {
        if (!timeline) return [];

        return timeline.map(item => ({
            id: item.id,
            date: formatDateTime(item.created_at),
            title: item.description || `${item.action} performed`,
            subtitle: `By: ${item.performed_by}`,
            ...(item.field_name && {
                additionalInfo: `${item.field_name}: ${item.old_value || 'N/A'} → ${item.new_value || 'N/A'}`
            })
        }));
    };

    const tabData = [
        { id: 'activity', label: 'Activity Log', icon: <IconClock /> },
        // { id: 'notes', label: 'Notes', icon: <IconClipboardText /> },
        { id: 'reminder', label: 'Reminders', icon: <IconCalendar /> },
    ];

    if (loading) {
        return (
            <div className="flex justify-center items-center h-96">
                <div className="text-center">
                    <IconLoader className="w-12 h-12 animate-spin text-primary mx-auto mb-4" />
                    <p className="text-gray-500">Loading lead details...</p>
                </div>
            </div>
        );
    }

    if (!lead) {
        return (
            <div className="p-4 text-center">
                <div className="text-gray-400">
                    <IconUser className="w-16 h-16 mx-auto mb-3 opacity-50" />
                    <p className="text-lg">Lead not found</p>
                    <Link to="/manage_leads" className="text-primary mt-2 inline-block">
                        Back to Leads
                    </Link>
                </div>
            </div>
        );
    }

    const statusDisplay = getStatusDisplay(lead.status);
    const priorityDisplay = getPriorityDisplay(lead.lead_priority);

    return (
        <>
            <div className="space-y-4">
                {/* Header */}
                <div className="flex justify-between items-start gap-5 flex-wrap">
                    <Link to="/manage_leads" className="flex items-center gap-2 group">
                        <IconCaretLeft className="text-primary group-hover:-translate-x-1 transition-transform" />
                        <div>
                            <div className="flex items-center gap-2 flex-wrap">
                                <h2 className="text-2xl font-semibold">{lead.lead_name}</h2>
                                <Tooltip content="Lead Status" placement="bottom">
                                    <span className={`text-sm rounded-full px-2 py-0.5 ${statusDisplay.color}`}>
                                        {statusDisplay.label}
                                    </span>
                                </Tooltip>
                            </div>
                            <div className="flex items-center gap-2 mt-1">
                                <Tooltip content="Branch" placement="bottom">
                                    <span className="text-sm text-dark rounded-full bg-slate-200 px-2 py-0.5">
                                        {lead.branch_name || 'N/A'}
                                    </span>
                                </Tooltip>
                            </div>
                        </div>
                    </Link>

                    {lead.status !== 5 && (
                        <Button
                            variant="primary"
                            onClick={() => {
                                setConvertStud(true);
                            }}
                            icon={<IconAcademicCap />}
                        >
                            Convert to Student
                        </Button>
                    )}
                </div>

                {/* Main Content */}
                <div className="bg-white rounded-xl shadow p-4">
                    {/* Lead Information Cards */}
                    <div className="flex justify-between flex-wrap gap-4 mb-4">
                        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 flex-1">
                            <div className="flex flex-col gap-2">
                                <span className="text-base text-dark font-semibold border-b pb-1">Contact Details</span>
                                <div className="flex justify-start gap-2 items-center">
                                    <IconMail className="w-5 h-5 text-gray-900" />
                                    <span className="text-sm">{lead.lead_email || 'N/A'}</span>
                                </div>
                                <div className="flex justify-start gap-2 items-center">
                                    <IconPhone className="w-5 h-5 text-gray-900" />
                                    <span className="text-sm">{lead.lead_mobile || 'N/A'}</span>
                                </div>
                            </div>
                            <div className="flex flex-col gap-2">
                                <span className="text-base text-dark font-semibold border-b pb-1">Source</span>
                                <div className="flex justify-start gap-2 items-center">
                                    <IconUser className="w-5 h-5 text-gray-900" />
                                    <span className="text-sm">{lead.assigned_staff_name || 'Unassigned'}</span>
                                </div>
                                <div className="flex justify-start gap-2 items-center">
                                    <IconTag className="w-5 h-5 text-gray-900" />
                                    <span className="text-sm">{lead.lead_source_name || 'N/A'}</span>
                                </div>
                            </div>
                            <div className="flex flex-col gap-2">
                                <span className="text-base text-dark font-semibold border-b pb-1">Dates</span>
                                <div className="flex justify-start gap-2 items-center">
                                    <IconCalendar className="w-5 h-5 text-gray-900" />
                                    <span className="text-sm">Created: {formatDate(lead.created_at)}</span>
                                </div>
                                <div className="flex justify-start gap-2 items-center">
                                    <IconClock className="w-5 h-5 text-gray-900" />
                                    <span className="text-sm">Updated: {formatDate(lead.updated_at)}</span>
                                </div>
                            </div>
                        </div>
                        <div className="bg-pink-50 p-4 rounded-md border border-rose-200 min-w-[180px]">
                            <div className="flex flex-col">
                                <span className="text-base text-dark">Potential Value</span>
                                <span className="text-2xl font-semibold text-primary">
                                    ₹ {lead.lead_value?.toLocaleString() || 0}
                                </span>
                            </div>
                        </div>
                    </div>

                    {/* Tabs */}
                    <Tabs
                        tabs={tabData}
                        defaultTab="activity"
                        onChange={(tabId) => {
                            setActiveTab(tabId);
                        }}
                    />

                    <div className="p-4">
                        {/* Activity Tab */}
                        {activeTab === "activity" && (
                            <div className="mt-2">
                                {lead.timeline && lead.timeline.length > 0 ? (
                                    <div className="flow-root">
                                        <ul className="-mb-8">
                                            {lead.timeline.map((item, index) => (
                                                <li key={item.id}>
                                                    <div className="relative pb-8">
                                                        {index !== lead.timeline!.length - 1 && (
                                                            <span
                                                                className="absolute top-4 left-4 -ml-px h-full w-0.5 bg-gray-200"
                                                                aria-hidden="true"
                                                            />
                                                        )}
                                                        <div className="relative flex space-x-3">
                                                            <div>
                                                                <span className="h-8 w-8 rounded-full bg-gray-100 flex items-center justify-center ring-8 ring-white">
                                                                    {item.action === 'created' && <IconUser className="w-4 h-4 text-green-600" />}
                                                                    {item.action === 'updated' && <IconClipboardText className="w-4 h-4 text-blue-600" />}
                                                                    {item.action === 'status_changed' && <IconClock className="w-4 h-4 text-yellow-600" />}
                                                                    {item.action === 'assigned' && <IconUser className="w-4 h-4 text-purple-600" />}
                                                                    {!['created', 'updated', 'status_changed', 'assigned'].includes(item.action) && <IconInfoCircle className="w-4 h-4 text-gray-600" />}
                                                                </span>
                                                            </div>
                                                            <div className="flex-1 min-w-0">
                                                                <div className="text-sm text-gray-500 mb-1">
                                                                    {formatDateTime(item.created_at)}
                                                                </div>
                                                                <div className="text-sm font-semibold text-gray-900">
                                                                    {item.description}
                                                                </div>
                                                                {item.field_name && item.old_value && item.new_value && (
                                                                    <div className="mt-1 text-xs text-gray-500 bg-gray-50 p-2 rounded">
                                                                        <span className="font-medium">Change details:</span>{' '}
                                                                        {item.field_name}: "{item.old_value}" → "{item.new_value}"
                                                                    </div>
                                                                )}
                                                                <div className="mt-1 text-xs text-gray-400">
                                                                    By: {item.performer?.staff_name || 'System'}
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </li>
                                            ))}
                                        </ul>
                                    </div>
                                ) : (
                                    <div className="text-center py-8">
                                        <IconClock className="w-12 h-12 mx-auto mb-3 text-gray-300" />
                                        <p className="text-gray-500">No activity recorded yet</p>
                                    </div>
                                )}
                            </div>
                        )}

                        {/* Notes Tab */}
                        {/* {activeTab === "notes" && (
                            <div className="mt-2">
                                {lead.comments && lead.comments.length > 0 ? (
                                    <div className="space-y-4">
                                        {lead.comments.map((comment) => (
                                            <div key={comment.id} className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
                                                <div className="bg-white rounded-full p-2 shadow-sm">
                                                    <IconClipboardText className="text-primary w-4 h-4" />
                                                </div>
                                                <div className="flex-1">
                                                    <p className="text-gray-800">{comment.comment}</p>
                                                    <div className="flex items-center gap-3 mt-2 text-xs text-gray-500">
                                                        <span className="flex items-center gap-1">
                                                            <IconUser className="w-3 h-3" />
                                                            {comment.created_by}
                                                        </span>
                                                        <span className="flex items-center gap-1">
                                                            <IconCalendar className="w-3 h-3" />
                                                            {formatDateTime(comment.created_at)}
                                                        </span>
                                                    </div>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                ) : (
                                    <div className="text-center py-8">
                                        <IconClipboardText className="w-12 h-12 mx-auto mb-3 text-gray-300" />
                                        <p className="text-gray-500">No notes added yet</p>
                                    </div>
                                )}
                            </div>
                        )} */}

                        {/* Reminders Tab */}
                        {activeTab === "reminder" && (
                            <div className="mt-2">
                                {followUps.length > 0 ? (
                                    <div className="space-y-4">
                                        {followUps.map((reminder) => (
                                            <div key={reminder.id} className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
                                                <div className="bg-white rounded-full p-2 shadow-sm">
                                                    <IconCalendar className="text-primary w-5 h-5" />
                                                </div>
                                                <div className="flex-1">
                                                    <div className="flex items-center gap-2 flex-wrap mb-1">
                                                        <span className="font-semibold text-gray-900">{reminder.title}</span>
                                                        <span className={`text-xs px-2 py-0.5 rounded-full ${
                                                            reminder.status === 'completed' ? 'bg-success/20 text-success' :
                                                            reminder.status === 'pending' ? 'bg-warning/20 text-warning' :
                                                            'bg-info/20 text-info'
                                                        }`}>
                                                            {reminder.status || 'Upcoming'}
                                                        </span>
                                                        <span className="text-xs bg-gray-200 px-2 py-0.5 rounded-full">
                                                            {reminder.type}
                                                        </span>
                                                    </div>
                                                    <p className="text-sm text-gray-600 mb-2">{reminder.description}</p>
                                                    <div className="flex items-center gap-3 text-xs text-gray-500 flex-wrap">
                                                        <span className="flex items-center gap-1">
                                                            <IconCalendar className="w-5 h-5" />
                                                            {formatDate(reminder.reminder_date)}
                                                        </span>
                                                        <span className="flex items-center gap-1">
                                                            <IconClock className="w-5 h-5" />
                                                            {reminder.reminder_time}
                                                        </span>
                                                        <span className="flex items-center gap-1">
                                                            <IconUser className="w-5 h-5" />
                                                            {reminder.assigned_staff?.staff_name}
                                                        </span>
                                                    </div>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                ) : (
                                    <div className="text-center py-8">
                                        <IconCalendar className="w-12 h-12 mx-auto mb-3 text-gray-300" />
                                        <p className="text-gray-500">No reminders set</p>
                                    </div>
                                )}
                            </div>
                        )}
                    </div>
                </div>
            </div>

            {/* Convert to Student Modal */}
            <ConvertStudent
                open={convertStud}
                onClose={() => {
                    setConvertStud(false);
                }}
                onSave={async (data) => {
                    try {
                        const response = await api.post(`/lead/convert-to-student/${lead.id}`, data);
                        if (response.data.status === true) {
                            toast.success('Lead converted to student successfully');
                            setConvertStud(false);
                            fetchLeadDetails(); // Refresh data
                            return true;
                        }
                        return false;
                    } catch (error: any) {
                        toast.error(error.response?.data?.message || 'Failed to convert lead');
                         return false;
                    }
                }}
                data={lead}
            />
        </>
    );
};

export default LeadView;
