'use client';

import { useState } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { routes } from '@/config/routes';
import TableLayout from '../../table-layout';
import {
  PiCalendarBlank,
  PiCalendarDot,
  PiChat,
  PiChatCircleDots,
  PiDotsThreeOutlineVertical,
  PiEye,
  PiKanban,
  PiList,
  PiSealCheck,
  PiUser,
  PiUsers,
} from 'react-icons/pi';
import ScheduleFollowup from '../../../components/modals/manage_lead/ScheduleFollowup';
import user from '../../../../public/auh/user_2.png';
import user1 from '../../../../public/auh/user_4.png';
import user2 from '../../../../public/auh/user_5.png';
import Image, { StaticImageData } from 'next/image';
import ConfirmModal from '@/components/common/confirm-modal';
import ViewToggle from '@/components/common/ViewToggle';

type LeadStatus = 'Scheduled' | 'Completed' | 'Overdue';

type Lead = {
  id: number;
  name: string;
  image: string | StaticImageData;
  mobile: string;
  source: string;
  assignedTo: string;
  followupDate: string;
  followupTime: string;
  comments: string;
  status: LeadStatus;
};

    const tabs = [
    { name: 'All', path: '/followup_lead', icon: PiDotsThreeOutlineVertical },
    { name: 'Scheduled', path: '/followup_lead/scheduled', icon: PiCalendarBlank },
    { name: 'Completed', path: '/followup_lead/completed', icon: PiSealCheck },
    { name: 'Overdue', path: '/followup_lead/overdue', icon: PiCalendarDot },
    ];

export default function Page() {
    const router = useRouter();
    const pathname = usePathname();

    const [openFollowupModal, setOpenFollowupModal] = useState(false);
    const [selectedLead, setSelectedLead] = useState<Lead | null>(null);
    const [completed, setCompleted] = useState<any>(null);

    const [leads, setLeads] = useState<Lead[]>([
        {
        id: 1,
        name: 'Prathap',
        image: user,
        mobile: '9876543210',
        source: 'Website',
        assignedTo: 'Arun',
        followupDate: '2026-05-20',
        followupTime: '10:30 AM',
        comments: 'Client interested, needs call back',
        status: 'Scheduled',
        },
        {
        id: 2,
        name: 'Ravi Kumar',
        image: user1,
        mobile: '9012345678',
        source: 'Facebook',
        assignedTo: 'Karthik',
        followupDate: '2026-05-22',
        followupTime: '02:00 PM',
        comments: 'Not reachable yet',
        status: 'Completed',
        },
        {
        id: 3,
        name: 'Suresh Babu',
        image: user2,
        mobile: '9988776655',
        source: 'Instagram',
        assignedTo: 'Vijay',
        followupDate: '2026-05-25',
        followupTime: '11:00 AM',
        comments: 'Follow-up required urgently',
        status: 'Overdue',
        },
    ]);

    const filteredLeads =
        pathname.includes('scheduled')
        ? leads.filter((l) => l.status === 'Scheduled')
        : pathname.includes('completed')
        ? leads.filter((l) => l.status === 'Completed')
        : pathname.includes('overdue')
        ? leads.filter((l) => l.status === 'Overdue')
        : leads;

    const getStatusColor = (status: LeadStatus) => {
        switch (status) {
        case 'Scheduled':
            return 'bg-blue-100 text-blue-600';
        case 'Completed':
            return 'bg-emerald-100 text-emerald-600';
        case 'Overdue':
            return 'bg-red-100 text-red-600';
        }
    };

    
    const handleConvert = () => {
        setLeads((prev) =>
        prev.map((l) =>
            l.id === completed.id ? { ...l, status: 'Completed' } : l
        )
        );

        setCompleted(null);
    };

    return (    
        <>
            <TableLayout
                title="Followup Lead"
                breadcrumb={[
                { href: routes.dashboard, name: 'Home' },
                { name: 'Lead & Call Management' },
                ]}
                data={[]}
                fileName="followup_lead"
                header="Module,Add,Edit,Delete,View"
                showExport={false}
                showImport={false}
                actions={
                    <ViewToggle
                    views={[
                        { label: 'Manage Lead', path: '/manage_lead', icon: PiUsers },
                        { label: 'Followup Lead', path: '/followup_lead', icon: PiCalendarBlank },
                    ]}
                    />
                }
            >
                <div className="flex gap-3 mb-3 justify-between items-center">
                    <div className="flex gap-3 border-b pb-2">
                        {tabs.map((tab) => {
                            const Icon = tab.icon;
                            const isActive =
                            pathname === tab.path ||
                            (tab.path === '/followup_lead' && pathname === '/followup_lead');
                            return (
                            <button
                                key={tab.name}
                                onClick={() => router.push(tab.path)}
                                className={`flex items-center gap-2 text-sm px-3 py-1 rounded transition ${
                                isActive ? 'bg-secondary text-white' : 'bg-gray-100'
                                }`}
                            >
                                <Icon className="text-lg" />
                                {tab.name}
                            </button>
                            );
                        })}
                    </div>
                    <ViewToggle
                    views={[
                        { label: 'List', path: '/followup_lead', icon: PiList },
                        { label: 'Kanban', path: '/followup_lead/kanban_board', icon: PiKanban },
                    ]}
                    />
                </div>
                <div className="space-y-3">
                    {filteredLeads.map((lead) => (
                        <div
                        key={lead.id}
                        className="bg-white border rounded-xl shadow-sm p-5 flex justify-between"
                        >
                        <div className="flex gap-4">
                            <Image
                                src={typeof lead.image === 'string' ? lead.image : lead.image.src}
                                alt={lead.name}
                                width={40}
                                height={40}
                                className="rounded-full border"
                            />
                            <div>
                                <h5 className="font-semibold">{lead.name}</h5>
                                <p className="text-xs text-gray-500">{lead.mobile}</p>
                                <div className="flex items-center gap-4 text-xs text-gray-500 mt-2">
                                    <span className="flex items-center gap-1">
                                        <PiCalendarBlank className='text-lg'/>
                                        {lead.followupDate} • {lead.followupTime}
                                    </span>
                                    <span className="flex items-center gap-1">
                                        <PiUser className='text-lg'/>
                                        {lead.assignedTo}
                                    </span>
                                </div>
                            </div>
                        </div>
                        <div className="flex flex-col gap-2 justify-between items-end">
                            <span
                                className={`px-3 py-1 text-xs rounded ${getStatusColor(
                                    lead.status
                                )}`}
                            >
                                {lead.status}
                            </span>
                            <span className="text-xs text-gray-600  flex items-center gap-1">
                                <PiChatCircleDots className='text-lg'/> <i>{lead.comments}</i>
                            </span>
                            <div className="flex gap-2 flex-wrap justify-end">
                                <button
                                    className="text-lg"
                                    onClick={() => router.push(`/manage_lead/view_lead/${lead.id}`)}
                                >
                                    <PiEye />
                                </button>
                                <button
                                    onClick={() => {
                                    setSelectedLead(lead);
                                    setOpenFollowupModal(true);
                                    }}
                                    className="text-lg"
                                >
                                    <PiCalendarDot/>
                                </button>
                                <button className="text-lg" onClick={() => setCompleted(lead)}>
                                    <PiSealCheck/>
                                </button>
                            </div>
                        </div>
                    </div>
                ))}
                </div>
            </TableLayout>
            
            <ScheduleFollowup
                open={openFollowupModal}
                onClose={() => setOpenFollowupModal(false)}
                leadData={selectedLead}
                onSubmit={(data : any) => {
                console.log(data);
                }}
            />
            
            <ConfirmModal
                open={!!completed}
                onClose={() => setCompleted(null)}
                onConfirm={handleConvert}
                title="Followup Completed"
                description={`Are you sure you want to change status of "${completed?.name}" to Completed?`}
                confirmText="Yes, Completed"
                confirmColor="bg-emerald-500 hover:bg-emerald-600"
            />
        </>
    );
}