'use client';

import { useState } from 'react';
import { routes } from '@/config/routes';
import { useRouter, useSearchParams } from 'next/navigation';
import TableLayout from '../../table-layout';
import { PiCalendar, PiCalendarBlank, PiCheckCircle, PiDotsThreeOutlineVertical, PiEye, PiKanban, PiList, PiPencilSimpleLineBold, PiPlus, PiRepeat, PiTag, PiTrashBold, PiUser, PiUserCheck, 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 DataTable from '@/components/common/DataTable';
import user from "../../../../public/auh/user_2.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 { Popover } from 'rizzui';
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'
  | 'Followup'
  | 'Interested'
  | 'Lost'
  | 'Converted';

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 views = [
    { label: 'List', icon: PiList, path: '/manage_lead' },
    { label: 'Kanban', icon: PiKanban, path: '/manage_lead/kanban_board' },
    { label: 'Calendar', icon: PiCalendar, path: '/manage_lead/calendar' }, 
  ];
  const router = useRouter();

  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 '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 STATUS_OPTIONS: LeadStatus[] = [
    'New',
    'Contacted',
    'Followup',
    'Interested',
    'Lost',
    'Converted',
  ];


  const { openDrawer } = useDrawer();

  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 columns: Column<Lead>[] = [
    {
      header: 'Lead',
      accessor: 'name',
      render: (_, row) => (
        <div className="flex items-center gap-3">
          <Image
            src={typeof row.image === 'string' ? row.image : row.image.src}
            alt={row.name}
            width={40}
            height={40}
            className="rounded-full border"
          />
          <div>
            <div className="font-semibold">{row.name}</div>
            <div className="text-xs text-gray-500">{row.mobile}</div>
          </div>
        </div>
      ),
    },
    {
      header: 'Source',
      accessor: 'source',
    },
    {
      header: 'Assigned To',
      accessor: 'assignedTo',
      render: (_, row) => (
        <span className="flex items-center gap-1">
          <PiUser/>
         {row.assignedTo} 
        </span>
       ),
    },
    {
      header: 'Tags',
      accessor: 'tags',
      render: (value: string[]) => {
        const visibleTags = value.slice(0, 2);
        const remainingTags = value.slice(2);

        return (
          <div className="flex flex-wrap items-center gap-1">

            {visibleTags.map((tag, i) => (
              <span
                key={i}
                className="px-2 py-0.5 text-xs bg-gray-200 rounded flex items-center gap-2"
              >
                <PiTag />
                {tag}
              </span>
            ))}

            {remainingTags.length > 0 && (
              <Popover placement="bottom-start">
                <Popover.Trigger>
                  <span className="px-2 py-0.5 text-xs bg-gray-200 rounded cursor-pointer cursor-pointer hover:bg-gray-600 hover:text-white">
                    +{remainingTags.length}
                  </span>
                </Popover.Trigger>

                <Popover.Content className="p-2 bg-white rounded-lg shadow-md border">
                  <div className="flex flex-wrap gap-2 max-w-[200px]">
                    {remainingTags.map((tag, i) => (
                      <span
                        key={i}
                        className="px-2 py-0.5 text-xs bg-gray-100 rounded flex items-center gap-1"
                      >
                        <PiTag />
                        {tag}
                      </span>
                    ))}
                  </div>
                </Popover.Content>
              </Popover>
            )}
          </div>
        );
      },
    },
    {
      header: 'Next Follow-up',
      accessor: 'nextFollowup',
      render: (_, row) => {
        const date = new Date(row.nextFollowup);
        const formattedDate = date.toLocaleDateString('en-GB', {
          day: '2-digit',
          month: 'short',
          year: 'numeric',
        }).replace(/ /g, '-'); ;

        return (
          <span className="text-red-500 text-sm flex items-center gap-1">
            <PiCalendarBlank/>
            {formattedDate}
          </span>
        );
      }
    },
    {
      header: 'Status',
      accessor: 'status',
      render: (value: LeadStatus) => (
        <Popover placement="bottom-start">
          <Popover.Trigger>
            <button
              className={`px-2 py-1 text-xs rounded cursor-pointer ${getStatusColor(
                value
              )}`}
            >
              {value}
            </button>
          </Popover.Trigger>

          <Popover.Content className="w-52 p-2 bg-white rounded-lg shadow-md border">
            <div className="flex flex-col gap-3 text-sm">
              {STATUS_OPTIONS
                .filter((status) => status !== value) // 👈 remove current status
                .map((status) => (
                  <button
                    key={status}
                    onClick={() => {
                      console.log('Selected Status:', status);
                    }}
                    className="text-left"
                  >
                    <span
                      className={`px-2 py-1 text-xs rounded ${getStatusColor(
                        status
                      )}`}
                    >
                      {status}
                    </span>
                  </button>
                ))}
            </div>
          </Popover.Content>
        </Popover>
      ),
    },
    {
      header: 'Actions',
      accessor: 'id',
      render: (_, row) => (
        <div className="flex gap-2">
          <button onClick={() => setAssignLead(row)}>
            <PiUserCheck className='text-lg'/>
          </button>
          <button
            onClick={() => setConvertLead(row)}
            className="bg-emerald-50 p-2 rounded-md"
          >
            <PiRepeat className="text-emerald-600 text-lg" />
          </button>
          <button
            onClick={() => {
              setSelectedLead(row);
              setOpenFollowupModal(true);
            }}
          >
            <PiCalendar className='text-lg' />
          </button>
          <Popover placement="bottom-end">
            <Popover.Trigger>
              <button className="p-1 rounded hover:bg-gray-100">
                <PiDotsThreeOutlineVertical />
              </button>
            </Popover.Trigger>
            <Popover.Content className="w-40 p-1 bg-white rounded-lg shadow-md border">
              <div className="flex flex-col gap-3 p-3 text-sm">
                <button
                    className='flex items-center gap-2'
                    onClick={() => router.push(`/manage_lead/view_lead/${row.id}`)}
                >
                  <PiEye className='text-lg'/>
                  View
                </button>
                <button
                  className='flex items-center gap-2'
                  onClick={() =>
                    openDrawer({
                      placement: 'right',
                      view: (
                        <LeadDrawer
                          initialData={row}
                          onSubmit={handleEdit}
                        />
                      ),
                    })
                  }
                >
                  <PiPencilSimpleLineBold className='text-lg' />
                  Edit
                </button>
                <button onClick={() => setDeleteLead(row)} className='flex items-center gap-2 text-red-600'>
                  <PiTrashBold className="text-lg text-red-600" />
                  Delete
                </button>
              </div>
            </Popover.Content>
          </Popover>
        </div>
      ),
    },
  ];


  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', 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 className="rounded-lg border bg-white shadow-sm">
            <DataTable
              data={leads}
              columns={columns}
              searchAble
              pagination
            />
          </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);
        }}
      />
    </>
  );
}