'use client';

import { useState } from 'react';
import { routes } from '@/config/routes';
import TableLayout from '../../table-layout';
import DataTable from '@/components/common/DataTable';
import { useRouter } from 'next/navigation';
import user from "../../../../public/auh/user_1.png";
import user1 from "../../../../public/auh/user_4.png";
import user2 from "../../../../public/auh/user_7.png";
import user3 from "../../../../public/auh/user_11.png";
import Image, { StaticImageData } from 'next/image';

import {
  PiDotsThreeOutlineVertical,
  PiEnvelopeSimple,
  PiPhone,
  PiScales,
  PiLockKey,
  PiEye,
  PiPencilSimpleLineBold,
  PiTrashBold,
  PiUsers,
  PiPlus,
  PiCheckCircle,
  PiXCircle,
} from 'react-icons/pi';

import { Popover } from 'rizzui';

type Column<T> = {
  header: string;
  accessor: keyof T;
  render?: (value: any, row: T) => React.ReactNode;
};

type CustomerStatus = 'Active' | 'Churned';

type BookingStatus =
  | 'Booked'
  | 'Booking Initiated'
  | 'Not Ready';

type LoanEligibility =
  | 'Eligible'
  | 'Not Checked';

type Customer = {
  id: number;
  name: string;
  company: string;
  email: string;
  mobile: string;
  manager: string;
  status: CustomerStatus;
  legalStage: string;
  docsVerified: string;
  bookingStatus: BookingStatus;
  loanEligibility: LoanEligibility;
   image: string | StaticImageData;
};

const pageHeader = {
  title: 'Customer Management',
  breadcrumb: [
    { href: routes.dashboard, name: 'Home' },
    { name: 'Customer & Booking Management' },
  ],
};

export default function Page() {

  const router = useRouter();
  const [imgError, setImgError] = useState(false);
  const [customers] = useState<Customer[]>([
    {
      id: 1,
      name: 'Arun Kumar',
      company: 'Green Valley Developers',
      email: 'arun.kumar@gmail.com',
      mobile: '+91 98765 43210',
      manager: 'Ravi Shankar',
      status: 'Active',
      legalStage: 'Agreement Drafting',
      docsVerified: '3/5 Docs Verified',
      bookingStatus: 'Booked',
      loanEligibility: 'Eligible',
      image: user,
    },
    {
      id: 2,
      name: 'Meera Iyer',
      company: 'Sunrise Properties',
      email: 'meera.iyer@gmail.com',
      mobile: '+91 91234 56789',
      manager: 'Karthik Raj',
      status: 'Active',
      legalStage: 'Site Visit Completed',
      docsVerified: '2/5 Docs Verified',
      bookingStatus: 'Booking Initiated',
      loanEligibility: 'Eligible',
      image: user2,
    },
    {
      id: 3,
      name: 'Suresh Babu',
      company: 'Lakeview Residency',
      email: 'suresh.babu@gmail.com',
      mobile: '+91 99887 66554',
      manager: 'Divya Nair',
      status: 'Active',
      legalStage: 'Token Paid',
      docsVerified: '4/5 Docs Verified',
      bookingStatus: 'Booked',
      loanEligibility: 'Eligible',
      image:  user1,
    },
    {
      id: 4,
      name: 'Priya Menon',
      company: 'Skyline Builders',
      email: 'priya.menon@gmail.com',
      mobile: '+91 90909 80808',
      manager: 'Anil Kumar',
      status: 'Churned',
      legalStage: 'Loan Rejected',
      docsVerified: '1/5 Docs Verified',
      bookingStatus: 'Not Ready',
      loanEligibility: 'Not Checked',
      image: user3,
    },
    {
      id: 5,
      name: 'Vikram Singh',
      company: 'Royal Estates',
      email: 'vikram.singh@gmail.com',
      mobile: '+91 97654 32109',
      manager: 'Sneha Reddy',
      status: 'Active',
      legalStage: 'Registration Pending',
      docsVerified: '5/5 Docs Verified',
      bookingStatus: 'Booked',
      loanEligibility: 'Eligible',
      image: user,
    },
  ]);

  const getInitial = (name: string) => {
    return name.charAt(0).toUpperCase();
  };

  const getStatusStyles = (status: CustomerStatus) => {
    switch (status) {
      case 'Active':
        return 'bg-green-50 text-green-600 border border-green-200';

      case 'Churned':
        return 'bg-red-50 text-red-500 border border-red-200';
    }
  };

  const getBookingStyles = (status: BookingStatus) => {
    switch (status) {
      case 'Booked':
        return 'bg-violet-100 text-violet-600 border border-violet-200';

      case 'Booking Initiated':
        return 'bg-blue-100 text-blue-600 border border-blue-200';

      case 'Not Ready':
        return 'bg-gray-100 text-gray-500 border border-gray-200';
    }
  };

  const getLoanStyles = (status: LoanEligibility) => {
    switch (status) {
      case 'Eligible':
        return 'bg-emerald-100 text-emerald-600 border border-emerald-200';

      case 'Not Checked':
        return 'bg-gray-100 text-gray-500 border border-gray-200';
    }
  };

  const columns: Column<Customer>[] = [
    {
      header: 'Customer',
      accessor: 'name',
      render: (_, row) => {
        const handleError = (e: any) => {
          e.currentTarget.style.display = 'none';
        };

        return (
          <div className="flex items-center gap-3">
            <div className="flex h-11 w-11 items-center justify-center rounded-full bg-indigo-100 font-semibold text-indigo-700 overflow-hidden">
              {row.image ? (
              <Image
                src={typeof row.image === 'string' ? row.image : row.image.src}
                alt={row.name}
                width={40}
                height={40}
                className="rounded-full border"
                onError={handleError}
              />
              ) : (
                getInitial(row.name)
              )}
            </div>

            <div className="flex flex-col">
              <span className="font-semibold text-black">{row.name}</span>
              <span className="text-sm text-gray-500">{row.company}</span>
            </div>
          </div>
        );
      },
    },
    {
      header: 'Legal & Docs',
      accessor: 'legalStage',
      render: (_, row) => (
        <div>
          <div className="flex items-center gap-2 font-medium text-sm ">
            <PiScales className="text-violet-500" />
            {row.legalStage}
          </div>
          <div className="mt-1 text-sm text-orange-500">
            {row.docsVerified}
          </div>
        </div>
      ),
    },
    {
      header: 'Booking Status',
      accessor: 'bookingStatus',
      render: (value: BookingStatus) => (
        <span
          className={`inline-flex items-center gap-2 rounded-full px-4 py-1 text-xs font-medium ${getBookingStyles(
            value
          )}`}
        >
          <PiLockKey />
          {value}
        </span>
      ),
    },
    {
      header: 'Loan Eligibility',
      accessor: 'loanEligibility',
      render: (value: LoanEligibility) => (
        <span
          className={`rounded-full px-4 py-1 text-xs font-medium ${getLoanStyles(
            value
          )}`}
        >
          {value}
        </span>
      ),
    },
    {
      header: 'Contact',
      accessor: 'email',
      render: (_, row) => (
        <div className="space-y-1">
          <div className="flex items-center gap-2 text-sm text-gray-700">
            <PiEnvelopeSimple className="text-gray-400" />
            {row.email}
          </div>
          <div className="flex items-center gap-2 text-sm text-gray-700">
            <PiPhone className="text-gray-400" />
            {row.mobile}
          </div>
        </div>
      ),
    },
    {
      header: 'Manager',
      accessor: 'manager',
      render: (_, row) => (
        <div className="flex items-center justify-between">
          <span className="text-gray-700">
            {row.manager}
          </span>
        </div>
      ),
    },
    {
      header: 'Status',
      accessor: 'status',
      render: (value: CustomerStatus) => (
        <span
          className={`rounded-full px-4 py-1 text-xs font-medium ${getStatusStyles(
            value
          )}`}
        >
          {value}
        </span>
      ),
    },
    {
      header: 'Action',
      accessor: 'id',
      render: (_, row) => (
        <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_customer/view_customer/${row.id}`)}
              >
                <PiEye className='text-lg'/>
                View
              </button>
              <button
                className='flex items-center gap-2'
                // onClick={() => {
                //   setEditingLead(row);
                //   setOpenModal(true);
                // }}
              >
                <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>
      ),
    }
  ];

  return (
    <TableLayout
      title={pageHeader.title}
      breadcrumb={pageHeader.breadcrumb}
      data={[]}
      fileName="customer-management"
      header="Customer Management"
      showExport={false}
      showImport={false}
    >
      <div className="grid grid-cols-1 md:grid-cols-6 mb-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 Customers</span>
            <span className="text-2xl font-semibold text-black">05</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">Active</span>
            <span className="text-2xl font-semibold text-black">04</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">Churned</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="rounded-lg border border-gray-200 bg-white shadow-sm">
        <DataTable
          data={customers}
          columns={columns}
          searchAble
          pagination
        />
      </div>
    </TableLayout>
  );
}