'use client';

import { useState } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { routes } from '@/config/routes';
import Select from 'react-select';
import TableLayout from '../../table-layout';
import {
  PiCalendarBlank,
  PiCalendarDot,
  PiCaretLeft,
  PiCaretRight,
  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';
import { DatePicker } from '@/components/ui/datepicker';
import { TimePicker } from '@/components/ui/timepicker';
import PrimaryButton from '@/components/common/primary-button';

type Status = 'Scheduled' | 'Completed' | 'Overdue';

type LeadStatus =
  | 'New'
  | 'Contacted'
  | 'Followup'
  | 'Interested'
  | 'Lost'
  | 'Converted';

type Lead = {
  id: number;
  name: string;
  image: string | StaticImageData;
  mobile: string;
  source: string;
  assignedTo: string;
  followupDate: string;
  followupTime: string;
  comments: string;
    status: Status;
    leadStatus: 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 [activeLeadId, setActiveLeadId] = useState<number | null>(null);
    const [actionType, setActionType] = useState<'complete' | 'reschedule' | null>(null);
    const [followupDate, setFollowupDate] = useState<Date | null>(null);
    const [followupTime, setFollowupTime] = useState<Date | null>(null);
    const [outcome, setOutcome] = useState<any>(null);
    const [activeFilter, setActiveFilter] = useState<'all' | Status | 'Upcoming'>('all');

    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',
            leadStatus: 'New',
        },
        {
            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',
            leadStatus: 'Interested',
        },
        {
            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',
            leadStatus: 'Lost',
        },
    ]);

    const filteredLeads = leads.filter((lead) => {
        if (activeFilter === 'all') return true;

        if (activeFilter === 'Upcoming') {
            const today = new Date().toISOString().split('T')[0];
            return lead.followupDate > today;
        }

        return lead.status === activeFilter;
    });
    
      
  const getLeadStatusColor = (status: LeadStatus) => {
    switch (status) {
      case 'New':
        return 'bg-blue-100 text-blue-600';
      case 'Contacted':
        return 'bg-yellow-100 text-yellow-600';
      case 'Followup':
        return 'bg-purple-100 text-purple-600';
      case 'Interested':
        return 'bg-cyan-100 text-cyan-600';
      case 'Lost':
        return 'bg-red-100 text-red-600';
      case 'Converted':
        return 'bg-emerald-100 text-emerald-600';
    }
  };

    const getStatusColor = (status: Status) => {
        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 getBorderColor = (status: string) => {
        switch (status) {
            case 'Scheduled':
            return 'border-l-blue-500';
            case 'Completed':
            return 'border-l-emerald-500';
            case 'Overdue':
            return 'border-l-red-500';
            default:
            return 'border-l-gray-300';
        }
    };

    const dashboardCards = [
        {
            label: 'All Tasks',
            value: 'all',
            count: leads.length,
            border: 'border-blue-500',
            bg: 'bg-blue-50',
            iconBg: 'bg-blue-100',
            text: 'text-blue-600',
        },
        {
            label: 'Pending / Delayed',
            value: 'Overdue',
            count: leads.filter(l => l.status === 'Overdue').length,
            border: 'border-red-500',
            bg: 'bg-red-50',
            iconBg: 'bg-red-100',
            text: 'text-red-600',
        },
        {
            label: 'Current (Today)',
            value: 'Scheduled',
            count: leads.filter(l => l.status === 'Scheduled').length,
            border: 'border-orange-500',
            bg: 'bg-orange-50',
            iconBg: 'bg-orange-100',
            text: 'text-orange-600',
        },
        {
            label: 'Upcoming',
            value: 'Upcoming',
            count: leads.filter(l => l.status === 'Scheduled').length,
            border: 'border-emerald-500',
            bg: 'bg-emerald-50',
            iconBg: 'bg-emerald-100',
            text: 'text-emerald-600',
        },
    ];
    
    const handleConvert = () => {
        setLeads((prev) =>
        prev.map((l) =>
            l.id === completed.id ? { ...l, status: 'Completed' } : l
        )
        );

        setCompleted(null);
    };

    const outcomeOptions = [
        { label: "Spoke - High Interest", value: "high_interest" },
        { label: "Not Interested", value: "not_interested" },
    ];

    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="grid grid-cols-4 gap-4 mb-4">
                        {dashboardCards.map((card) => {
                            const isActive = activeFilter === card.value;

                            return (
                            <div
                                key={card.label}
                                onClick={() => setActiveFilter(card.value as any)}
                                className={`
                                cursor-pointer rounded-xl border p-4 flex justify-between items-center 
                                transition-all duration-300

                                    ${isActive ? `${card.border} ${card.bg}` : 'border-gray-200'}
                                `}
                            >
                                <div>
                                <p className="text-sm text-gray-500">{card.label}</p>
                                <h3 className="text-xl font-semibold">{card.count}</h3>
                                </div>

                                <div className={`p-2 rounded-lg ${card.iconBg}`}>
                                <PiCalendarBlank className={`text-lg ${card.text}`} />
                                </div>
                            </div>
                            );
                        })}
                    </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
                                id={`lead-${lead.id}`} 
                                key={lead.id}
                                className={`bg-white border border-l-4 rounded-xl shadow-sm p-5 ${getBorderColor(lead.status)}`}
                            >
                                <div className='flex justify-between'>
                                    <div className="flex gap-4">
                                        <Image
                                            src={typeof lead.image === 'string' ? lead.image : lead.image.src}
                                            alt={lead.name}
                                            width={45}
                                            height={45}
                                            className="rounded-full border border-primary border-2"
                                        />
                                        <div>
                                            <div className="flex items-center justify-start gap-2">
                                                <h5 className="font-semibold">{lead.name}</h5>
                                                <span
                                                    className={`px-3 py-1 text-xs rounded-full ${getLeadStatusColor(
                                                        lead.leadStatus
                                                    )}`}
                                                >
                                                    {lead.leadStatus}
                                                </span>
                                            </div>
                                            <div className="flex items-center justify-start gap-2">
                                                <p className="text-xs text-gray-500">{lead.mobile} • {lead.id}</p>
                                            </div>
                                        </div>
                                    </div>
                                    <div className="flex flex-col gap-0 justify-between items-end">
                                        <span className="text-gray-400 font-semibold">Previous Interaction Notes</span>    
                                        <span className="text-gray-400 font-semibold">&quot;<i>{lead.comments}</i>&quot;</span>    
                                    </div>
                                    <div>
                                        <span className={`flex items-center gap-1 px-3 py-1 text-xs rounded-full ${getStatusColor(
                                            lead.status
                                        )}`}>
                                            <PiCalendarBlank className='text-lg'/>
                                            {lead.followupDate} • {lead.followupTime}
                                        </span>
                                    </div>
                                    <div className="flex flex-col gap-2 justify-between items-end">
                                        <div className="flex gap-2 flex-wrap justify-end">
                                            <button
                                                onClick={() => {
                                                    setActiveLeadId(lead.id);
                                                    setActionType('reschedule');

                                                    setTimeout(() => {
                                                        document
                                                        .getElementById(`lead-${lead.id}`)
                                                        ?.scrollIntoView({ behavior: 'smooth', block: 'center' });
                                                    }, 100);
                                                }}
                                                className='flex items-center gap-1 justify-center bg-blue-100 text-blue-600 rounded-xl px-2 py-1' 
                                            >
                                                <PiCalendarDot className="text-lg"/>
                                                <span className='text-xs font-medium'>Reschedule</span>
                                            </button>
                                            <button className='flex items-center gap-1 justify-center bg-emerald-100 text-emerald-600 rounded-xl px-2 py-1' onClick={() => {
                                                setActiveLeadId(lead.id);
                                                setActionType('complete');

                                                setTimeout(() => {
                                                    document
                                                    .getElementById(`lead-${lead.id}`)
                                                    ?.scrollIntoView({ behavior: 'smooth', block: 'center' });
                                                }, 100);
                                            }}>
                                                <PiSealCheck className="text-lg"/>
                                                <span className='text-xs font-medium'>Completed</span>
                                            </button>                                
                                            <button
                                                className="text-lg"
                                                onClick={() => router.push(`/manage_lead/view_lead/${lead.id}`)}
                                            >
                                                <PiCaretRight />
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                {activeLeadId === lead.id && (
                                    <div className="mt-4 border-t pt-4 bg-gray-50 rounded-xl p-4">
                                        {actionType === 'complete' && (
                                            <div className="space-y-3">
                                                <h4 className="text-sm font-semibold text-gray-700">
                                                    Mark Followup As Completed
                                                </h4>
                                                <div className="grid grid-cols-2 gap-2">
                                                    <div>
                                                        <label className="block text-sm font-medium mb-1 text-gray-700">
                                                            Outcome Category
                                                        </label>
                                                        <Select
                                                            options={outcomeOptions}
                                                            value={outcome}
                                                            onChange={(selected) => setOutcome(selected)}
                                                            placeholder="Select outcome"
                                                            className="text-sm"
                                                            classNamePrefix="react-select"
                                                        />
                                                    </div>
                                                    <div>
                                                        <label className="block text-sm font-medium mb-1 text-gray-700">
                                                            Internal summary / next actions
                                                        </label>
                                                        <textarea
                                                            placeholder="Internal summary / next actions..."
                                                            rows={1}
                                                            className="w-full border rounded-lg px-3 py-2 text-sm"
                                                        />
                                                    </div>
                                                </div>
                                                <div className="flex justify-end gap-2">
                                                    <button
                                                        onClick={() => setActiveLeadId(null)}
                                                        className="px-4 py-2 border rounded-lg"
                                                    >
                                                        Cancel
                                                    </button>
                                                    <button className="bg-emerald-700 text-white px-4 py-1 rounded-lg text-sm">
                                                        Log Completion
                                                    </button>
                                                </div>
                                            </div>
                                        )}

                                        {actionType === 'reschedule' && (
                                            <div className="space-y-3">
                                                <h4 className="text-sm font-semibold text-gray-700 flex items-center gap-2">
                                                    <PiCalendarBlank className='text-lg'/>
                                                    Reschedule Followup
                                                </h4>
                                                <div className="grid grid-cols-3 gap-0">
                                                    <div>
                                                        <label className="block text-sm font-medium mb-1 text-gray-700">
                                                            Follow-up Date
                                                        </label>
                                                        <DatePicker
                                                            selected={followupDate}
                                                            className='w-[400px]'
                                                            onChange={(date) => setFollowupDate(date)}
                                                            inputProps={{ placeholder: "Select date" }}
                                                        />
                                                    </div>
                                                    <div>
                                                        <label className="block text-sm font-medium mb-1 text-gray-700">
                                                            Follow-up Time
                                                        </label>
                                                        <TimePicker
                                                            selected={followupTime}
                                                            className='w-[800px]'
                                                            onChange={(time) => setFollowupTime(time)}
                                                            inputProps={{ placeholder: "Select time" }}
                                                        />
                                                    </div>
                                                    <div>
                                                        <label className="block text-sm font-medium mb-1 text-gray-700">
                                                            Reschedule Reason
                                                        </label>
                                                        <textarea
                                                            name="comments"
                                                            placeholder="Enter comments"
                                                            rows={1}
                                                            className="w-full rounded-lg border px-4 py-2"
                                                        />
                                                    </div>
                                                </div>
                                                <div className="flex justify-end gap-2">
                                                    <button
                                                        onClick={() => setActiveLeadId(null)}
                                                        className="px-4 py-2 border rounded-lg"
                                                    >
                                                        Cancel
                                                    </button>
                                                    <PrimaryButton type="submit">
                                                        Schedule
                                                    </PrimaryButton>
                                                </div>
                                            </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"
            />
        </>
    );
}