'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,
  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 KANBAN_COLUMNS: LeadStatus[] = [
  'Scheduled',
  'Completed',
  'Overdue',
];

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 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';
      default:
        return 'bg-gray-100 text-gray-600';
    }
  };

  const groupedLeads = KANBAN_COLUMNS.reduce((acc, status) => {
    acc[status] = leads.filter((lead) => lead.status === status);
    return acc;
  }, {} as Record<LeadStatus, Lead[]>);

  const formatDate = (date: string) => {
    return new Date(date)
      .toLocaleDateString('en-GB', {
        day: '2-digit',
        month: 'short',
        year: 'numeric',
      })
      .replace(/ /g, '-');
  };

  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-5 mb-3 justify-end items-center">
          <ViewToggle
            views={[
                { label: 'List', path: '/followup_lead', icon: PiList },
                { label: 'Kanban', path: '/followup_lead/kanban_board', icon: PiKanban },
            ]}
          />
        </div>
        <div className="rounded-lg bg-white">
          <div className="flex gap-4 overflow-x-auto pb-4">
            {KANBAN_COLUMNS.map((status) => (
              <div
                key={status}
                className={`min-w-[300px] rounded-xl p-3 border-t-4 ${getStatusColor(status)}`}
              >
                {/* Header */}
                <div className="flex justify-between items-center mb-3">
                  <h3 className={`text-xs font-semibold px-2 py-1 rounded ${getStatusColor(status)}`}>
                    {status}
                  </h3>
                  <span className="text-xs bg-gray-200 px-2 py-0.5 rounded">
                    {groupedLeads[status].length}
                  </span>
                </div>
                <div className="flex flex-col gap-3">
                  {groupedLeads[status].map((lead) => (
                    <div
                      key={lead.id}
                      className="bg-white p-3 rounded-lg border hover:shadow-md transition"
                    >
                      <div className="flex items-center justify-between border-b pb-2">
                        <div className="flex items-center gap-2">
                          <Image
                            src={typeof lead.image === 'string' ? lead.image : lead.image.src}
                            alt={lead.name}
                            width={40}
                            height={40}
                            className="rounded-full border"
                          />
                          <div>
                            <div className="text-sm font-medium">{lead.name}</div>
                            <div className="text-xs text-gray-500">{lead.mobile}</div>
                          </div>
                        </div>
                        <div className="flex items-center gap-2">
                          <button
                            onClick={() => router.push(`/manage_lead/view_lead/${lead.id}`)}
                          >
                            <PiEye className="text-gray-600 text-lg" />
                          </button>
                          <button
                            onClick={() => {
                            setSelectedLead(lead);
                            setOpenFollowupModal(true);
                            }}
                            className="text-lg text-gray-600"
                          >
                              <PiCalendarDot/>
                          </button>
                          <button className="text-lg text-gray-600" onClick={() => setCompleted(lead)}>
                              <PiSealCheck/>
                          </button>
                        </div>
                      </div>
                      <div className="text-xs text-gray-600 mt-2 flex items-center gap-2">
                        <PiCalendarBlank />
                        {formatDate(lead.followupDate)} • {lead.followupTime}
                      </div>

                      {/* Assigned */}
                      <div className="text-xs text-gray-600 mt-1 flex items-center gap-2">
                        <PiUser />
                        {lead.assignedTo}
                      </div>

                      {/* Comments */}
                      <div className="text-xs text-gray-500 mt-2 flex items-center gap-2">
                        <PiChatCircleDots />
                        <i>{lead.comments}</i>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ))}

          </div>
        </div>
      </TableLayout>

      {/* Modals */}
      <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"
      />
    </>
  );
}