'use client';

import { useState } from 'react';
import { routes } from '@/config/routes';
import { usePathname, useRouter } from 'next/navigation';
import TableLayout from '../../../table-layout';
import { PiCalendarBlank, PiCheckCircle, PiEye, PiKanban, PiList, PiPencilSimpleLine, PiPencilSimpleLineBold, PiPlus, PiTag, PiTrashBold, PiUsers, PiXCircle } from 'react-icons/pi';
import PrimaryButton from '../../../../components/common/primary-button';
import { PiPlusBold } from 'react-icons/pi';
import ConfirmModal from '@/components/common/confirm-modal';
import user from "../../../../../public/auh/user_1.png";
import user1 from "../../../../../public/auh/user_4.png";
import user3 from "../../../../../public/auh/user_5.png";
import user2 from "../../../../../public/auh/user_2.png";
import ScheduleFollowup from "../../../../components/modals/manage_lead/ScheduleFollowup";
import Image, { StaticImageData } from 'next/image';
import AssignLeadModal from '@/components/modals/manage_lead/AssignLeadModal';
import { useDrawer } from '@/components/common/Drawer';
import LeadDrawer from '@/components/drawer/manage_lead/LeadDrawer';
import ViewToggle from '@/components/common/ViewToggle';

type Column<T> = {
  header: string;
  accessor: keyof T;
  render?: (value: any, row: T) => React.ReactNode;
};

type LeadStatus =
  | 'New'
  | 'Contacted'
  | 'Interested'
  | 'Not Interested'
  | 'Dropped'
  | 'Followup'
  | 'Converted'
  | 'Lost';

const KANBAN_COLUMNS: LeadStatus[] = [
  'New',
  'Contacted',
  'Interested',
  'Not Interested',
  'Dropped',
  'Followup',
  'Converted',
  'Lost',
];

type Lead = {
  id: number;
  name: string;
  image: string | StaticImageData;
  mobile: string;
  source: string;
  assignedTo: string;
  tags: string[];
  nextFollowup: string;
  status: LeadStatus;
};

const pageHeader = {
  title: 'Manage Lead',
  breadcrumb: [
    { href: routes.dashboard, name: 'Home' },
    { name: 'Lead Management' },
  ],
};

export default function Page() {
  const [deleteLead, setDeleteLead] = useState<Lead | null>(null);
  const [convertLead, setConvertLead] = useState<any>(null);
  const [assignLead, setAssignLead] = useState<any>(null);
  const [openFollowupModal, setOpenFollowupModal] = useState(false);
  const [selectedLead, setSelectedLead] = useState<any>(null);

  const handleAssign = (data: any) => {
    setLeads((prev) =>
      prev.map((lead) =>
        lead.id === data.id
          ? { ...lead, assignedTo: data.assignedTo }
          : lead
      )
    );
  };

  const handleEdit = (updatedLead: Lead) => {
    setLeads((prev) =>
      prev.map((l) => (l.id === updatedLead.id ? updatedLead : l))
    );
  };

  const handleDelete = () => {
    if (!deleteLead) return;

    setLeads((prev) =>
      prev.filter((l) => l.id !== deleteLead.id)
    );
    setDeleteLead(null);
  };

  const handleConvert = () => {
    setLeads((prev) =>
      prev.map((l) =>
        l.id === convertLead.id ? { ...l, status: 'Converted' } : l
      )
    );

    setConvertLead(null);
  };
  
  const getStatusColor = (status: LeadStatus) => {
  switch (status) {
    case 'New':
      return 'bg-blue-100 text-blue-600';
    case 'Contacted':
      return 'bg-yellow-100 text-yellow-600';
    case 'Interested':
      return 'bg-cyan-100 text-cyan-600';
    case 'Not Interested':
      return 'bg-gray-200 text-gray-700';
    case 'Dropped':
      return 'bg-orange-100 text-orange-600';
    case 'Followup':
      return 'bg-purple-100 text-purple-600';
    case 'Converted':
      return 'bg-emerald-100 text-emerald-600';
    case 'Lost':
      return 'bg-red-100 text-red-600';
    default:
      return 'bg-gray-100 text-gray-600';
  }
};  



  const { openDrawer } = useDrawer();
  const router = useRouter();

  const [leads, setLeads] = useState<Lead[]>([
    {
      id: 1,
      name: 'Prathap',
      image: user,
      mobile: '9876543210',
      source: 'Website',
      assignedTo: 'Arun',
      tags: ['Hot', 'Budget', 'Premium'],
      nextFollowup: '2026-05-20',
      status: 'New',
    },
    {
      id: 2,
      name: 'Ravi Kumar',
      image: user1,
      mobile: '9012345678',
      source: 'Facebook',
      assignedTo: 'Karthik',
      tags: ['Cold'],
      nextFollowup: '2026-05-22',
      status: 'Contacted',
    },
    {
      id: 3,
      name: 'Suresh Babu',
      image: user2,
      mobile: '9988776655',
      source: 'Instagram',
      assignedTo: 'Vijay',
      tags: ['Followup', 'Cold', 'Budget', 'Premium'],
      nextFollowup: '2026-05-25',
      status: 'Followup',
    },
    {
      id: 4,
      name: 'Mani Raj',
      image: user3,
      mobile: '9871234560',
      source: 'Referral',
      assignedTo: 'Arun',
      tags: ['Hot'],
      nextFollowup: '2026-05-18',
      status: 'Interested',
    },
    {
      id: 5,
      name: 'Karthik',
      image: user1,
      mobile: '9090909090',
      source: 'Website',
      assignedTo: 'Karthik',
      tags: ['Cold'],
      nextFollowup: '2026-05-30',
      status: 'Lost',
    },
    {
      id: 6,
      name: 'Vijay',
      image: user3,
      mobile: '9191919191',
      source: 'Facebook',
      assignedTo: 'Vijay',
      tags: ['Premium'],
      nextFollowup: '2026-05-28',
      status: 'Converted',
    },
    {
      id: 7,
      name: 'Ajith',
      image: user2,
      mobile: '9292929292',
      source: 'Instagram',
      assignedTo: 'Arun',
      tags: ['Budget'],
      nextFollowup: '2026-06-01',
      status: 'New',
    },
    {
      id: 8,
      name: 'Surya',
      image: user1,
      mobile: '9393939393',
      source: 'Website',
      assignedTo: 'Karthik',
      tags: ['Hot'],
      nextFollowup: '2026-05-19',
      status: 'Interested',
    },
    {
      id: 9,
      name: 'Prakash',
      image: user3,
      mobile: '9494949494',
      source: 'Referral',
      assignedTo: 'Vijay',
      tags: ['Cold'],
      nextFollowup: '2026-05-26',
      status: 'Followup',
    },
    {
      id: 10,
      name: 'Dinesh',
      image: user2,
      mobile: '9595959595',
      source: 'Facebook',
      assignedTo: 'Arun',
      tags: ['Budget'],
      nextFollowup: '2026-05-21',
      status: 'Contacted',
    },
  ]);

  
  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 [search, setSearch] = useState('');

  return (
    <>
      <TableLayout
        title={pageHeader.title}
        breadcrumb={pageHeader.breadcrumb}
        data={[]}
        fileName="manaeg_lead"
        header="Module,Add,Edit,Delete,View"
        showExport={false}
        showImport={true}
         actions={
          <ViewToggle
            views={[
                { label: 'Manage Lead', path: '/manage_lead/kanban_board', icon: PiUsers },
                { label: 'Followup Lead', path: '/followup_lead', icon: PiCalendarBlank },
            ]}
          />
        }
      >
        <div className="space-y-6">
          <div className="flex items-start justify-between gap-5">
            <div className="grid grid-cols-1 lg:grid-cols-4 md:grid-cols-4 gap-3">
              <div className="rounded-lg p-4 border bg-white flex items-center justify-between w-[200px]">
                <div className="flex flex-col">
                  <span className="text-gray-500 text-sm">Total Leads</span>
                  <span className="text-2xl font-semibold text-black">10</span>
                </div>
                <div className="bg-amber-100 text-amber-600 rounded-full p-2">
                  <PiUsers />
                </div>
              </div>
              <div className="rounded-lg p-4 border bg-white flex items-center justify-between w-[200px]">
                <div className="flex flex-col">
                  <span className="text-gray-500 text-sm">New</span>
                  <span className="text-2xl font-semibold text-black">02</span>
                </div>
                <div className="bg-blue-100 text-blue-600 rounded-full p-2">
                  <PiPlus />
                </div>
              </div>
              <div className="rounded-lg p-4 border bg-white flex items-center justify-between w-[200px]">
                <div className="flex flex-col">
                  <span className="text-gray-500 text-sm">Converted</span>
                  <span className="text-2xl font-semibold text-black">01</span>
                </div>
                <div className="bg-green-100 text-green-600 rounded-full p-2">
                  <PiCheckCircle />
                </div>
              </div>
              <div className="rounded-lg p-4 border bg-white flex items-center justify-between w-[200px]">
                <div className="flex flex-col">
                  <span className="text-gray-500 text-sm">Lost</span>
                  <span className="text-2xl font-semibold text-black">01</span>
                </div>
                <div className="bg-red-100 text-red-600 rounded-full p-2">
                  <PiXCircle />
                </div>
              </div>
            </div>
            <div className="flex items-center jutify-end gap-2">
              <PrimaryButton
                onClick={() =>
                  openDrawer({
                    placement: 'right',
                    view: (
                      <LeadDrawer
                        onSubmit={(data: Lead) => {
                          setLeads((prev) => [...prev, { ...data, id: Date.now() }]);
                        }}
                      />
                    ),
                  })
                }
              >
                <PiPlusBold />
                Create Lead
              </PrimaryButton>
              <ViewToggle
                views={[
                  { label: 'List', icon: PiList, path: '/manage_lead' },
                  { label: 'Kanban', icon: PiKanban, path: '/manage_lead/kanban_board' },
                ]}
              />
            </div>
          </div>
          <div >
            <input
              type="text"
              placeholder="Search..."
              value={search}
              onChange={(e) => {
                setSearch(e.target.value);
              }}
              className="w-full rounded-lg border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
            />
          </div>
          <div className="rounded-lg bg-white shadow-sm">
            <div className="flex gap-4 overflow-x-auto pb-4">
              {KANBAN_COLUMNS.map((status) => (
                <div
                  key={status}
                  className={`min-w-[280px] rounded-xl p-3 border-t-4 ${getStatusColor(
                    status
                  )}`}
                >
                  {/* Column Header */}
                  <div className="flex justify-between items-center mb-3">
                      <h3
                      className={`font-semibold text-xs 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 gap-2 border-b py-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 flex-row gap-2 text-sm">
                            <button
                                onClick={() => router.push(`/manage_lead/view_lead/${lead.id}`)}
                            >
                              <PiEye className='text-lg text-gray-600'/>
                            </button>
                            <button
                              onClick={() =>
                                openDrawer({
                                  placement: 'right',
                                  view: (
                                    <LeadDrawer
                                      initialData={lead}
                                      onSubmit={handleEdit}
                                    />
                                  ),
                                })
                              }
                            >
                              <PiPencilSimpleLine className='text-lg text-gray-600' />
                            </button>
                            <button onClick={() => setDeleteLead(lead)} className='text-red-600'>
                              <PiTrashBold className="text-lg text-red-600" />
                            </button>
                          </div>
                        </div>
                        <div className="flex flex-wrap gap-1 mt-2">
                          {lead.tags.slice(0, 2).map((tag, i) => (
                            <span
                              key={i}
                              className="text-xs bg-gray-100 px-2 py-0.5 rounded flex items-center gap-2"
                            >
                              <PiTag className='text-md'/>
                              {tag}
                            </span>
                          ))}
                        </div>
                        <div className="text-xs text-red-500 mt-2 flex items-center gap-2">
                          <PiCalendarBlank className='text-md'/>
                          {formatDate(lead.nextFollowup)}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </TableLayout>


      <ConfirmModal
        open={!!deleteLead}
        onClose={() => setDeleteLead(null)}
        onConfirm={handleDelete}
        title="Delete Lead"
        description={`Are you sure you want to delete "${deleteLead?.name}"?`}
        confirmText="Delete"
        confirmColor="bg-red-500 hover:bg-red-600"
      />

      <AssignLeadModal
        open={!!assignLead}
        onClose={() => setAssignLead(null)}
        onSubmit={handleAssign}
        leadData={assignLead}
      />

      <ConfirmModal
        open={!!convertLead}
        onClose={() => setConvertLead(null)}
        onConfirm={handleConvert}
        title="Convert to Customer"
        description={`Are you sure you want to convert "${convertLead?.name}" to customer?`}
        confirmText="Yes, Convert"
        confirmColor="bg-emerald-500 hover:bg-emerald-600"
      />

      <ScheduleFollowup
        open={openFollowupModal}
        onClose={() => {
          setOpenFollowupModal(false);
          setSelectedLead(null);
        }}
        leadData={selectedLead}
        onSubmit={(data: any) => {
          console.log('Followup Data:', data);
        }}
      />
    </>
  );
}