'use client';

import { useMemo, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Image from 'next/image';
import Select from "react-select";
import {
  PiEnvelopeSimple,
  PiPencilSimpleLineBold,
  PiUserCircle,
  PiHandshake,
  PiFileText,
  PiClockCounterClockwise,
  PiReceipt,
  PiCaretLeft,
  PiX,
  PiFloppyDisk,
  PiUserCheck,
  PiMapPin,
  PiFileBold,
  PiUserPlus,
  PiClipboardText,
  PiTarget,
  PiUser,
  PiPhone,
  PiCalendarBlank,
  PiHouse,
  PiCalculator,
  PiCheckCircle,
  PiWallet,
  PiTrendUp,
  PiSignatureLight,
  PiTrafficCone,
  PiBank,
  PiCheckBold,
  PiShare,
  PiCurrencyDollar,
} from 'react-icons/pi';
import PageTabs from '@/components/common/page-tabs';
import PrimaryButton from '@/components/common/primary-button';
import user from '../../../../../../public/auh/user_6.png';
import ProfileSection from '@/components/common/ProfileSectionCard';
import { Input } from 'rizzui/input';
import { Textarea } from 'rizzui/textarea';
import RecordPaymentModal from '@/components/modals/manage_customer/RecordPaymentModal';

type PlanType = "construction_linked" | "down_payment";
type TabKey =
  | 'profile'
  | 'deal'
  | 'documents'
  | 'activity'
  | 'invoices';

  type BookingStatus =
  | 'Booked'
  | 'Booking Initiated'
  | 'Not Ready';

  type LoanStage = "none" | "applied" | "approved" | "disbursed";

  type FormType = Customer & {
    planType: "" | PlanType;
  };

  type Customer = {
    id: number;
    planType: string;
    name: string;
    email: string;
    mobile: string;
    altMobile?: string;
    bookingStatus: BookingStatus;
    source: string;
    assignedTo: string;
    image: any;

    // profile info
    address?: string;
    idType?: string;
    idNumber?: string;

    coApplicantName?: string;
    relation?: string;

    nomineeName?: string;
    nomineeRelation?: string;
    nomineeAge?: string;
    age?: string;
    location?: string;
    propertyType?: string;
    requirements?: string;
    agreementPreference?: string;
    panNumber?: string;
    aadhaarNumber?: string;
  };

export default function Page() {
  const router = useRouter();
  const params = useParams();
  const [activeTab, setActiveTab] = useState<TabKey>('profile');
  const [isEditing, setIsEditing] = useState(false);
  const [openPaymentModal, setOpenPaymentModal] = useState(false);
  const [selectedRow, setSelectedRow] = useState<any>(null);
  const [selected, setSelected] = useState("Ready Cash");
  const [status, setStatus] = useState("paid");
  const [showSchedule, setShowSchedule] = useState(false);
  const [loanStage, setLoanStage] = useState<LoanStage>("none");
  const [loanForm, setLoanForm] = useState({
    bank: "",
    amount: "15000000",
  });

  const [customers, setCustomers] = useState<Customer[]>([
    {
      id: 1,
      name: 'Arun Kumar',
      email: 'arun@gmail.com',
      mobile: '9876543210',
      altMobile: '9876543210',
      source: 'Website',
      assignedTo: 'Amit Verma',
      bookingStatus: 'Booking Initiated',
      image: user,
      address: '',
      idType: '',
      idNumber: '',
      coApplicantName: '',
      nomineeName: '',
      nomineeAge: '',
      planType: '',
      propertyType: '',
      requirements: '',
      agreementPreference: '',
      age: '',
      panNumber: '',
      aadhaarNumber: '',
      location: '',
    },
  ]);

  const planOptions = [
    { label: 'Construction Linked Plan (CLP)', value: "construction_linked", },
    { label: 'Down Payment Plan (DPP)',  value: "down_payment", },
  ];
  const idTypeOptions = [
    { label: 'Passport', value: 'passport' },
    { label: 'National ID', value: 'national_id' },
    { label: 'Tax ID', value: 'tax_id' },
  ];

  const agreementOptions = [
    { label: 'Registered Agreement', value: 'registered_agreement' },
    { label: 'Notarized', value: 'notarized' },
    { label: 'Memorandum of Understanding (MoU)', value: 'mou' },
  ];
  
  const customer = useMemo(
    () => customers.find(c => c.id === Number(params.id)),
    [params.id, customers]
  );

  const [form, setForm] = useState<FormType>(() => ({
    ...(customer as Customer),
    planType: "",
  }));

  if (!customer) {
    return <div className="p-10 text-red-500">Customer not found</div>;
  }

  const tabs = [
    {
      label: 'Profile & KYC',
      value: 'profile',
      icon: PiUserCircle,
    },
    {
      label: 'Deal Structuring & Finance',
      value: 'deal',
      icon: PiHandshake,
    },
    {
      label: 'Documents & Legal',
      value: 'documents',
      icon: PiFileText,
    },
    {
      label: 'Activity History',
      value: 'activity',
      icon: PiClockCounterClockwise
    },
    {
      label: 'Invoices',
      value: 'invoices',
      icon: PiReceipt
    },
  ];

  const options = [
    "Ready Cash",
    "Bank Loan",
    "Cash + Loan",
    "Yet to Decide",
  ];

  const handleSave = () => {
    setIsEditing(false);
    setCustomers(prev =>
      prev.map(c => (c.id === customer.id ? { ...c, ...form } : c))
    );
  };

  const statusOptions = [
    { value: "paid", label: "● Paid", color: "#10b981" },
    { value: "pending", label: "● Pending", color: "#f59e0b" },
  ];

  const customStyles = {
    singleValue: (base: any, state: any) => ({
      ...base,
      color: state.data.value === "paid" ? "#10b981" : "#f59e0b",
      fontWeight: 500,
    }),
  };


  const getBadge = () => {
    switch (loanStage) {
      case "applied":
        return "APPLIED";
      case "approved":
        return "APPROVED";
      case "disbursed":
        return "DISBURSED";
      default:
        return "NOT STARTED";
    }
  };

  const scheduleData: Record<
    PlanType,
    {
      stage: string;
      date: string;
      amount: string;
      tax: string;
      payer: string;
    }[]
  > = {
    construction_linked: [
      {
        stage: "Booking Amount",
        date: "2023-09-15",
        amount: "$1,890,000",
        tax: "$90,000",
        payer: "CUSTOMER",
      },
      {
        stage: "On Agreement",
        date: "2023-10-15",
        amount: "$1,890,000",
        tax: "$90,000",
        payer: "BANK",
      },
      {
        stage: "On Plinth",
        date: "2023-11-14",
        amount: "$2,835,000",
        tax: "$135,000",
        payer: "BANK",
      },
      {
        stage: "On 1st Slab",
        date: "2023-12-14",
        amount: "$2,835,000",
        tax: "$135,000",
        payer: "BANK",
      },
      {
        stage: "On Finishing",
        date: "2024-03-13",
        amount: "$4,725,000",
        tax: "$225,000",
        payer: "BANK",
      },
      {
        stage: "On Possession",
        date: "2024-09-14",
        amount: "$4,725,000",
        tax: "$225,000",
        payer: "BANK",
      },
    ],

    down_payment: [
      {
        stage: "Booking Amount",
        date: "2023-09-15",
        amount: "$5,400,000",
        tax: "$270,000",
        payer: "CUSTOMER",
      },
      {
        stage: "Within 30 Days",
        date: "2023-10-15",
        amount: "$3,600,000",
        tax: "$180,000",
        payer: "CUSTOMER",
      },
      {
        stage: "On Agreement",
        date: "2023-11-15",
        amount: "$2,700,000",
        tax: "$135,000",
        payer: "BANK",
      },
      {
        stage: "Before Possession",
        date: "2024-06-15",
        amount: "$7,200,000",
        tax: "$360,000",
        payer: "BANK",
      },
    ],
  };

  const currentSchedule = form.planType && scheduleData[form.planType]
    ? scheduleData[form.planType]
    : [];
  
  const isApplied = loanStage === "applied" || loanStage === "approved" || loanStage === "disbursed";
  const isApproved = loanStage === "approved" || loanStage === "disbursed";
  const isDisbursed = loanStage === "disbursed";


  return (
    <>
    <div className="grid grid-cols-12 gap-6 p-4">
      <div className="col-span-12 lg:col-span-3">
        
        <button
          onClick={() => router.back()}
          className="mb-3 flex items-center gap-2 text-sm text-gray-800 bg-gray-100 rounded-lg p-2"
        >
          <PiCaretLeft /> Back
        </button>
        <div className="sticky top-4 rounded-lg border bg-white p-4 shadow-sm">
          <div className="flex flex-col gap-1 items-center py-2">
            <Image
              src={customer.image}
              alt={customer.name}
              width={110}
              height={110}
              className="rounded-full border-4 border-primary bg-slate-200 object-cover"
            />
            <h2 className="text-xl font-bold">
              {customer.name}
              <span className="bg-emerald-50 text-emerald-600 text-xs ms-2 font-medium rounded-full p-2">Active</span>
            </h2>
            <span className="text-gray-500">{customer.mobile}</span>
            <span className="bg-emerald-50 text-emerald-600 rounded-full p-2">{customer.bookingStatus}</span>
          </div>     
          <hr></hr>
          <div className="mt-3">
            <h5 className="text-sm font-semibold uppercase tracking-wider text-gray-500 mb-3">
              Contact Info
            </h5>
            <div className="space-y-2 px-4">
              <div className="flex items-center gap-3">
                <PiEnvelopeSimple className="text-lg text-gray-500" />
                <span className="text-sm text-gray-700">
                  {customer.email}
                </span>
              </div>
              <div className="flex items-center gap-3">
                <PiPhone className="text-lg text-gray-500" />
                <span className="text-sm text-gray-700">
                  +91 {customer.mobile}
                </span>
              </div>
              <div className="flex items-center gap-3">
                <PiMapPin className="text-lg text-gray-500" />
                <span className="text-sm text-gray-700">
                  {customer.location}
                </span>
              </div>
            </div>
          </div>
          <div className="mt-3">
            <h5 className="text-sm font-semibold uppercase tracking-wider text-gray-500 mb-3">
              Key Info
            </h5>
            <div className="grid grid-cols-2 gap-2 mb-2">
              <div className='flex flex-col gap-1 bg-gray-100 p-2 rounded-lg'>
                <span className="text-sm text-gray-500 flex items-center gap-1"><PiTarget/>Source</span>
                <span className="font-medium text-black">
                  {customer.source}
                </span>
              </div>
              <div className='flex flex-col gap-1 bg-gray-100 p-2 rounded-lg'>
                <span className="text-sm text-gray-500 flex items-center gap-1"><PiUser/>Assigned To</span>
                <div className="font-medium text-black">
                  {customer.assignedTo}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div className="col-span-12 lg:col-span-9">
        <div className="mb-4 flex items-center justify-between">
          <PageTabs
            tabs={tabs}
            activeTab={activeTab}
            onChange={(val) => setActiveTab(val as TabKey)}
          />
        </div>
        <div className="rounded-lg border bg-white p-5">
          {activeTab === 'profile' && 
            (
              <>
              <div className="mb-4 flex items-center justify-end mb-2">
              {!isEditing ? (
                <PrimaryButton onClick={() => setIsEditing(true)}>
                  <PiPencilSimpleLineBold className="mr-2" />
                  Edit Profile
                </PrimaryButton>
              ) : (
                <div className="flex gap-2">
                  <button
                    onClick={() => setIsEditing(false)}
                    className="rounded border px-4 py-2 text-sm flex items-center gap-2 font-semibold"
                  >
                    <PiX className='font-semibold'/>Cancel
                  </button>
                    <PrimaryButton onClick={handleSave}>
                      <PiFloppyDisk className='font-semibold text-lg'/>
                    Save Changes
                  </PrimaryButton>
                </div>
              )}
              </div>
              <div className="space-y-4">
                <ProfileSection title="Personal Information" icon={<PiUserCheck className='text-lg text-black'/>}>
                  <div className="grid grid-cols-2 gap-4">
                    <Input
                      label="Name"
                      value={form?.name || ''}
                      disabled={!isEditing}
                      onChange={(e) =>
                        setForm((prev) =>
                          prev ? { ...prev, name: e.target.value } : prev
                        )
                      }
                    />
                    <Input
                      label="Email"
                      value={form?.email || ''}
                      disabled={!isEditing}
                      onChange={(e) =>
                        setForm((prev) =>
                          prev ? { ...prev, email: e.target.value } : prev
                        )
                      }
                    />
                    <Input
                      label="Mobile"
                      value={form?.mobile || ''}
                      disabled={!isEditing}
                      onChange={(e) =>
                        setForm((prev) =>
                          prev ? { ...prev, mobile: e.target.value } : prev
                        )
                      }
                    />
                    <Input
                      label="Alternate Mobile "
                      value={form?.altMobile || ''}
                      disabled={!isEditing}
                      onChange={(e) =>
                        setForm((prev) =>
                          prev ? { ...prev, altMobile: e.target.value } : prev
                        )
                      }
                    />
                  </div>
                </ProfileSection>
                <ProfileSection title="Address & Identity"  icon={<PiMapPin className='text-lg text-black'/>}>
                  <div className="grid grid-cols-2 gap-4">
                    <Input
                      label="Address"
                      value={form?.address || ''}
                      disabled={!isEditing}
                      onChange={(e) =>
                        setForm((prev) =>
                          prev ? { ...prev, address: e.target.value } : prev
                        )
                      }
                    />
                    <div className="flex flex-col gap-1">
                      <label className="text-sm font-medium text-gray-700">
                        ID Type
                      </label>
                      <Select
                        options={idTypeOptions}
                        value={idTypeOptions.find(
                          (option) => option.value === form?.idType
                        )}
                        onChange={(selected) => {
                          setForm((prev) =>
                            prev ? { ...prev, idType: selected?.value || '' } : prev
                          );
                        }}
                        isDisabled={!isEditing}
                        className="text-sm"
                        classNamePrefix="react-select"
                        menuPortalTarget={typeof window !== "undefined" ? document.body : null}
                        styles={{
                          menuPortal: (base) => ({ ...base, zIndex: 999999 }),
                        }}
                      />
                    </div>
                    <Input
                      label="Id number"
                      value={form?.idNumber || ''}
                      disabled={!isEditing}
                      onChange={(e) =>
                        setForm((prev) =>
                          prev ? { ...prev, idNumber: e.target.value } : prev
                        )
                      }
                    />
                  </div>
                </ProfileSection>
                <ProfileSection title="Legal & Financial Details" icon={<PiFileBold className='text-lg text-black'/>}>
                  <div className="grid grid-cols-2 gap-4">
                    <Input
                      label="PAN Number"
                      value={form?.panNumber || ''}
                      disabled={!isEditing}
                      onChange={(e) =>
                        setForm((prev) =>
                          prev ? { ...prev, panNumber: e.target.value } : prev
                        )
                      }
                    />
                    <Input
                      label="Aadhaar/National Id (12-Digits)"
                      value={form?.aadhaarNumber || ''}
                      disabled={!isEditing}
                      onChange={(e) =>
                        setForm((prev) =>
                          prev ? { ...prev, aadhaarNumber: e.target.value } : prev
                        )
                      }
                    />
                    <div className="flex flex-col gap-1">
                      <label className="text-sm font-medium text-gray-700">
                        Agreement Preference
                      </label>
                      <Select
                        options={agreementOptions}
                        value={agreementOptions.find(
                          (option) => option.value === form?.agreementPreference
                        )}
                        onChange={(selected) =>
                          setForm((prev) =>
                            prev
                              ? { ...prev, agreementPreference: selected?.value || '' }
                              : prev
                          )
                        }
                        isDisabled={!isEditing}
                        className="text-sm"
                        classNamePrefix="react-select"
                        menuPortalTarget={typeof window !== "undefined" ? document.body : null}
                        styles={{
                          menuPortal: (base) => ({ ...base, zIndex: 999999 }),
                        }}
                      />
                    </div>
                  </div>
                </ProfileSection>
                <ProfileSection title="Co-Applicant & Nominee" icon={<PiUserPlus className='text-lg text-black'/>}>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-3">
                      <Input
                        label="Co-Applicant Name"
                        value={form?.coApplicantName || ''}
                        disabled={!isEditing}
                        onChange={(e) =>
                          setForm((prev) =>
                            prev ? { ...prev, coApplicantName: e.target.value } : prev
                          )
                        }
                      />
                      <Input
                        label="Relation"
                        value={form?.relation || ''}
                        disabled={!isEditing}
                        onChange={(e) =>
                          setForm((prev) =>
                            prev ? { ...prev, relation: e.target.value } : prev
                          )
                        }
                      />
                      <Input
                        label="Age"
                        value={form?.age || ''}
                        disabled={!isEditing}
                        onChange={(e) =>
                          setForm((prev) =>
                            prev ? { ...prev, age: e.target.value } : prev
                          )
                        }
                      />
                    </div>
                    <div className="space-y-3">
                      <Input
                        label="Nominee Name"
                        value={form?.nomineeName || ''}
                        disabled={!isEditing}
                        onChange={(e) =>
                          setForm((prev) =>
                            prev ? { ...prev, nomineeName: e.target.value } : prev
                          )
                        }
                      />
                      <Input
                        label="Relation"
                        value={form?.nomineeRelation || ''}
                        disabled={!isEditing}
                        onChange={(e) =>
                          setForm((prev) =>
                            prev ? { ...prev, nomineeRelation: e.target.value } : prev
                          )
                        }
                      />
                      <Input
                        label="Nominee Age"
                        value={form?.nomineeAge || ''}
                        disabled={!isEditing}
                        onChange={(e) =>
                          setForm((prev) =>
                            prev ? { ...prev, nomineeAge: e.target.value } : prev
                          )
                        }
                      />
                    </div>
                  </div>
                </ProfileSection>
                <ProfileSection title="Requirement Details" icon={<PiClipboardText className='text-lg text-black'/>}>
                  <div className="grid grid-cols-2 gap-4">
                    <Input
                      label="Preferred Property / Property Type"
                      value={form?.propertyType || ''}
                      disabled={!isEditing}
                      onChange={(e) =>
                        setForm((prev) =>
                          prev ? { ...prev, propertyType: e.target.value } : prev
                        )
                      }
                    />
                    <Textarea
                      label="Requirement Details"
                      value={form?.requirements || ''}
                      disabled={!isEditing}
                      onChange={(e) =>
                        setForm((prev) =>
                          prev ? { ...prev, requirements: e.target.value } : prev
                        )
                      }
                      rows={4}
                    />
                  </div>
                </ProfileSection>

              </div>
              </>
          )}
          {activeTab === 'deal' && (
            <div className="space-y-6">
              <div className="flex items-center justify-between">
                <div>
                  <h5 className="text-xl font-bold text-gray-900">
                    Deal Structuring & Finance
                  </h5>
                  <p className="text-sm text-gray-500 mt-1">
                    Configure payment plans, track down payments, and manage loan
                    applications.
                  </p>
                </div>
                <div className="mb-4 flex items-center justify-end mb-2">
                  {!isEditing ? (
                    <PrimaryButton onClick={() => setIsEditing(true)}>
                      <PiPencilSimpleLineBold className="mr-2" />
                      Edit Deal
                    </PrimaryButton>
                    
                  ) : (
                    <div className="flex gap-2">
                      <button
                        onClick={() => setIsEditing(false)}
                        className="rounded border px-4 py-2 text-sm flex items-center gap-2 font-semibold"
                      >
                        <PiX className='font-semibold'/>Cancel
                      </button>
                      <PrimaryButton onClick={handleSave}>
                          <PiFloppyDisk className='font-semibold text-lg'/>
                        Save Changes
                      </PrimaryButton>
                    </div>
                  )}
                  </div>
              </div>
               {!showSchedule ? (
                  /* CONFIGURATION UI */
                  <div className="bg-white rounded-2xl border border-gray-200 p-8 shadow-sm">
                    <div className="max-w-2xl mx-auto text-center">
                      <div className="w-14 h-14 rounded-full bg-slate-200 flex items-center justify-center mx-auto mb-5">
                        <span className="text-2xl">
                          <PiCalendarBlank />
                        </span>
                      </div>

                      <h3 className="text-lg font-semibold text-gray-900">
                        Payment Schedule Configuration
                      </h3>

                      <p className="text-gray-500 mt-2">
                        Select a template to auto-generate the payment schedule
                        based on the property value of{" "}
                        <span className="font-semibold text-lg text-black">
                          $18,000,000
                        </span>
                      </p>

                      <div className="mt-8 space-y-4">
                        <Select
                          options={planOptions}
                          value={planOptions.find(
                            (option) => option.value === form?.planType
                          )}
                          onChange={(selected) =>
                              setForm((prev) => ({
                                ...prev,
                                planType: (selected?.value as PlanType) || "",
                              }))
                            }
                          placeholder="-- Choose a Plan --"
                          className="text-sm"
                          classNamePrefix="react-select"
                          menuPortalTarget={
                            typeof window !== "undefined"
                              ? document.body
                              : null
                          }
                          styles={{
                            menuPortal: (base) => ({
                              ...base,
                              zIndex: 999999,
                            }),
                          }}
                        />

                        <button
                          disabled={!form?.planType}
                          onClick={() => setShowSchedule(true)}
                          className={`w-full py-3 rounded-xl font-semibold transition ${
                            form?.planType
                              ? "bg-primary hover:bg-secondary text-white"
                              : "bg-gray-200 text-gray-400 cursor-not-allowed"
                          }`}
                        >
                          Generate Schedule
                        </button>
                      </div>
                    </div>
                  </div>
                ) : (
                  /* PAYMENT SCHEDULE UI */
                  <div className="space-y-6">
                    {/* Stats */}
                    <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                      {[
                        {
                          title: "TOTAL RECEIVABLES",
                          value: "$18,900,000",
                          color: "text-black",
                        },
                        {
                          title: "TOTAL COLLECTED",
                          value: "$0",
                          color: "text-emerald-500",
                        },
                        {
                          title: "BALANCE DUE",
                          value: "$18,900,000",
                          color: "text-primary",
                        },
                        {
                          title: "OVERDUE",
                          value: "$0",
                          color: "text-black",
                        },
                      ].map((item, i) => (
                        <div
                          key={i}
                          className="bg-white border border-gray-200 rounded-2xl p-5 shadow-sm"
                        >
                          <p className="text-xs font-semibold text-gray-400 uppercase">
                            {item.title}
                          </p>

                          <h2
                            className={`text-3xl font-bold mt-2 ${item.color}`}
                          >
                            {item.value}
                          </h2>

                          {i === 1 && (
                            <div className="w-full h-1 bg-gray-100 rounded-full mt-4 overflow-hidden">
                              <div className="w-0 h-full bg-emerald-500" />
                            </div>
                          )}
                        </div>
                      ))}
                    </div>

                    {/* Table */}
                    <div className="bg-white border border-gray-200 rounded-2xl shadow-sm overflow-hidden">
                      {/* Header */}
                      <div className="flex items-center justify-between p-5 border-b border-gray-200">
                        <div className="flex items-center gap-2">
                          <PiCalendarBlank className="text-primary text-xl" />

                          <h3 className="text-lg font-semibold text-gray-900">
                            Payment Schedule
                          </h3>
                        </div>

                        <div className="flex items-center gap-3">
                          <button className="px-4 py-2 border border-gray-300 rounded-xl text-sm font-medium hover:bg-gray-50">
                            Export
                          </button>
                          <button
                            onClick={() => {
                              setShowSchedule(false);
                              setForm((prev) => ({
                                ...prev,
                                planType: "",
                              }));
                            }}
                            className="px-4 py-2 border border-red-200 text-red-500 rounded-xl text-sm font-medium hover:bg-red-50"
                          >
                            Reset
                          </button>
                        </div>
                      </div>
                      <div className="overflow-x-auto">
                        <table className="w-full">
                          <thead className="bg-gray-50 border-b border-gray-200">
                            <tr className="text-left">
                              {[
                                "STAGE",
                                "DUE DATE",
                                "AMOUNT (INC. TAX)",
                                "PAYER",
                                "STATUS",
                                "ACTION"
                              ].map((head) => (
                                <th
                                  key={head}
                                  className="px-6 py-4 text-xs font-semibold text-gray-500 uppercase"
                                >
                                  {head}
                                </th>
                              ))}
                            </tr>
                          </thead>
                          <tbody>
                            {currentSchedule.map((row, i) => (
                              <tr
                                key={i}
                                className="border-b border-gray-100 hover:bg-gray-50 transition"
                              >
                                <td className="px-6 py-5 font-medium text-gray-900">
                                  {row.stage}
                                </td>

                                <td className="px-6 py-5 text-gray-600">
                                  {row.date}
                                </td>

                                <td className="px-6 py-5">
                                  <div className="font-semibold text-gray-900">
                                    {row.amount}
                                  </div>

                                  <div className="text-xs text-gray-400">
                                    Tax: {row.tax}
                                  </div>
                                </td>
                                <td className="px-6 py-5">
                                  <span
                                    className={`px-3 py-1 rounded-md text-xs font-semibold ${
                                      row.payer === "BANK"
                                        ? "bg-purple-100 text-purple-600"
                                        : "bg-blue-100 text-blue-600"
                                    }`}
                                  >
                                    {row.payer}
                                  </span>
                                </td>
                                <td className="px-6 py-5">
                                  <span className="px-3 py-1 rounded-full bg-gray-100 text-gray-500 text-xs font-semibold">
                                    Upcoming
                                  </span>
                                </td>
                                <td className="px-6 py-5">
                                  <div className="flex items-center gap-3">
                                    <button className="text-gray-500 hover:text-black">
                                      <PiShare />
                                    </button>
                                    <button
                                      onClick={() => {
                                        setSelectedRow(row);
                                        setOpenPaymentModal(true);
                                      }}
                                      className="text-emerald-600 hover:text-emerald-700"
                                    >
                                      <PiCurrencyDollar />
                                    </button>
                                  </div>
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    </div>
                  </div>
                )}
              <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <div className="lg:col-span-2 space-y-6">
                  <div className="bg-white border border-gray-200 rounded-2xl p-6 shadow-sm">
                    <div className="flex flex-col">
                      <div className='flex items-center justify-start gap-2 mb-3'>
                        <PiHouse className='text-lg text-black'/>
                        <span className="text-sm text-gray-600 font-medium">
                          Selected Property
                        </span>
                      </div>
                      <div className="flex justify-between gap-2 items-center bg-gray-100 rounded-md p-2">
                        <div className='flex flex-col'>
                          <h4 className="text-lg font-semibold mt-3 text-gray-900">
                            Galaxy Heights - A-102
                          </h4>
                          <span className="text-sm text-gray-500">Wing A • 2BHK</span>
                        </div>
                        <div className='flex flex-col'>
                          <span className="text-xs uppercase text-gray-400">Total Price</span>
                          <h5 className="text-3xl font-bold text-gray-900 mt-2">
                            $18,000,000
                          </h5>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div className="bg-white border border-gray-200 rounded-lg p-6 shadow-sm">
                    <h5 className="text-lg font-semibold text-gray-900 mb-5 flex justify-start gap-1 items-center">
                      <PiCalculator className='text-lg text-black'/>
                      Payment Structuring
                    </h5>
                    <div className="flex flex-wrap gap-3 mb-6">
                      <label className="text-sm font-medium text-gray-700">
                        Payment Mode
                      </label>
                      <div className="flex flex-wrap gap-3">
                        {options.map((option) => {
                          const isActive = selected === option;
                          return (
                            <button
                              key={option}
                              disabled={!isEditing}
                              type="button"
                              onClick={() => setSelected(option)}
                              className={`px-5 py-2 rounded-xl font-medium transition
                                ${
                                  isActive
                                    ? "bg-primary text-white"
                                    : "border border-gray-300 text-gray-700 hover:bg-gray-50"
                                }`}
                            >
                              {option}
                            </button>
                          );
                        })}
                      </div>
                    </div>
                    <div className="grid md:grid-cols-2 gap-4">
                      <div className="border border-gray-200 rounded-lg p-5">
                        <div className="flex items-center justify-between mb-3">
                          <span className="text-sm font-medium text-gray-500">
                            Down Payment
                          </span>
                          <Select
                            options={statusOptions}
                            isDisabled={!isEditing}
                            value={statusOptions.find((o) => o.value === status)}
                            onChange={(selected) => setStatus(selected?.value || "paid")}
                            isSearchable={false}
                            className="w-40"
                            styles={customStyles}
                          />
                        </div>
                        <Input
                          value={'$ 20,00,000'}
                          disabled={!isEditing}
                        />
                        <span className="text-xs text-emerald-400 mt-2 flex items-center gap-1 justify-start"><PiCheckCircle/>Paid on N/A</span>
                      </div>
                      <div className="bg-blue-50 rounded-lg p-5 border border-blue-100">
                        <span className="text-sm font-medium text-blue-700">
                          Loan Required
                        </span>
                        <div className="text-4xl font-bold text-blue-700 mt-3">
                          $16,000,000
                        </div>
                        <span className="text-xs text-blue-500 mt-2">
                          89% of Property Value
                        </span>
                      </div>
                    </div>
                    <div className="mt-6">
                      <div className="w-full h-3 rounded-full bg-gray-200 overflow-hidden flex">
                        <div className="bg-secondary w-[11%]" />
                        <div className="bg-primary w-[89%]" />
                      </div>
                      <div className="flex justify-between mt-2 text-xs text-gray-500">
                        <span>DOWN PAYMENT (11%)</span>
                        <span>BALANCE (89%)</span>
                      </div>
                    </div>
                  </div>
                  <div className="mt-6 bg-white border border-gray-200 rounded-xl p-6 shadow-sm">
                    <div className="flex items-center justify-between border-b border-gray-200 pb-4">
                      <h5 className="text-lg font-semibold text-gray-900 flex items-center gap-2">
                        <PiBank className="text-primary text-xl" />
                        Loan Lifecycle Manager
                      </h5>
                      <span className="px-4 py-1 rounded-md bg-blue-100 text-primary text-sm font-semibold">
                        {getBadge()}
                      </span>
                    </div>
                    <div className="flex items-center justify-between mt-8 relative">
                      <div className="absolute top-5 left-0 right-0 h-[2px] bg-gray-200 z-0" />
                      <div className="relative z-10 flex flex-col items-center w-full">
                        <div className={`w-10 h-10 rounded-full flex items-center justify-center text-white shadow ${
                          isApplied ? "bg-primary" : "bg-gray-300"
                        }`}>
                          <PiCheckBold />
                        </div>
                        <span className="mt-2 text-xs font-semibold text-primary">
                          APPLIED
                        </span>
                      </div>
                      <div className="relative z-10 flex flex-col items-center w-full">
                        <div className={`w-10 h-10 rounded-full flex items-center justify-center text-white shadow ${
                          isApproved ? "bg-primary" : "bg-gray-300"
                        }`}>
                          <PiCheckBold />
                        </div>
                        <span className="mt-2 text-xs font-semibold text-primary">
                          APPROVED
                        </span>
                      </div>
                      <div className="relative z-10 flex flex-col items-center w-full">
                        <div className={`w-10 h-10 rounded-full flex items-center justify-center shadow ${
                          isDisbursed ? "bg-primary text-white" : "border-2 border-gray-300 bg-white"
                        }`}>
                          {isDisbursed ? <PiCheckBold /> : <div className="w-3 h-3 bg-gray-300 rounded-full" />}
                        </div>
                        <span className="mt-2 text-xs font-semibold text-gray-400">
                          DISBURSED
                        </span>
                      </div>
                    </div>
                    <div className="mt-8 grid md:grid-cols-2 gap-4 bg-gray-50 border border-gray-200 rounded-xl p-5">
                     
                      <div>
                        <label className="block text-sm font-medium text-gray-600 mb-2">
                          Preferred Bank
                        </label>
                        <input
                          type="text"
                          disabled={!isEditing || loanStage !== "none"}
                          value={loanForm.bank}
                          onChange={(e) =>
                            setLoanForm((prev) => ({ ...prev, bank: e.target.value }))
                          }
                          placeholder="e.g. HDFC Bank"
                        />
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-gray-600 mb-2">
                          Loan Amount Requested
                        </label>
                        <input
                          type="text"
                          disabled={!isEditing}
                           value={loanForm.amount}
                          className="w-full h-11 rounded-lg border border-gray-300 px-4 text-sm outline-none bg-white"
                        />
                      </div>
                    </div>
                    {loanStage === "none" && (
                      <button
                        disabled={!isEditing || !loanForm.bank}
                        onClick={() => setLoanStage("applied")}
                        className="w-full mt-4 h-12 bg-blue-500 text-white rounded-lg disabled:opacity-40"
                      >
                        Mark As Applied
                      </button>
                    )}
                    {loanStage === "applied" && (
                      <button
                        onClick={() => setLoanStage("approved")}
                        className="w-full mt-4 h-12 bg-yellow-500 text-white rounded-lg"
                      >
                        Record Sanction
                      </button>
                    )}
                    {loanStage === "approved" && (
                      <button
                        onClick={() => setLoanStage("disbursed")}
                        className="w-full mt-8 h-12 bg-emerald-500 text-white rounded-lg"
                      >
                        Confirm Disbursement
                      </button>
                    )}
                  </div>
                </div>
                <div className="space-y-6">
                  <div className="bg-white border border-gray-200 rounded-2xl p-6 shadow-sm">
                    <h5 className="text-lg font-semibold text-gray-900 mb-5 border-b flex items-center gap-2 justify-start">
                      <PiWallet className='text-lg text-black'/>
                        Income Profile
                    </h5>
                    <div className="space-y-4 text-sm">
                      <div className="flex justify-between">
                        <span className="text-gray-500">Employment</span>
                        <span className="font-semibold">Salaried</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-gray-500">Monthly Income</span>
                        <span className="font-semibold">$500,000</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-gray-500">Credit Score</span>
                        <span className="font-semibold text-emerald-600">780</span>
                      </div>
                    </div>
                  </div>
                  <div className="bg-[#071122] text-white rounded-2xl p-6 shadow-lg">
                    <h5 className="text-xl font-semibold mb-6 text-white flex items-center gap-2 justify-start">
                      <PiTrendUp className='text-lg text-emerald-400 font-bold'/>
                      Eligibility Engine
                    </h5>
                    <div className="space-y-5">
                      <div>
                        <span className="text-sm text-gray-400">Disposable Income</span>
                        <span className="text-xl font-bold text-emerald-400">
                          $450,000
                        </span>
                      </div>

                      <div className="border border-gray-700 rounded-2xl p-5">
                        <p className="text-xs text-gray-400 uppercase">
                          Max Loan Eligibility
                        </p>
                        <h2 className="text-2xl text-white font-bold mt-3">$48,600,000</h2>
                        <p className="text-xs text-gray-500 mt-2">
                          Est. 15yr Tenure @ 60% FOIR
                        </p>
                      </div>
                      <div className="flex justify-between text-sm">
                        <span className="text-gray-400">Loan Required</span>
                        <span>$16,000,000</span>
                      </div>

                      <div className="text-emerald-400 font-semibold text-sm">
                        Gap Analysis Fully Covered
                      </div>
                    </div>
                  </div>
                  <div className="bg-white border border-gray-200 rounded-2xl p-6 shadow-sm">
                    <div className="flex items-center justify-start gap-2 mb-5">
                      <PiTrafficCone className='text-lg text-black'/>
                      <h3 className="text-lg font-semibold text-gray-900">
                        Booking Readiness
                      </h3>
                    </div>
                    <div className="space-y-4 text-sm">
                      
                      <span className="px-4 py-1 rounded-full bg-violet-100 text-violet-700 text-sm font-medium">
                        Booked
                      </span>
                      <div className="flex justify-between">
                        <span className="text-gray-500">Property Selected</span>
                        <span className="text-emerald-500">✔</span>
                      </div>

                      <div className="flex justify-between">
                        <span className="text-gray-500">Down Payment Paid</span>
                        <span className="text-emerald-500">✔</span>
                      </div>

                      <div className="flex justify-between">
                        <span className="text-gray-500">Loan Sanctioned</span>
                        <span className="text-emerald-500">✔</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}
          {activeTab === 'documents' && (
            <div className="text-sm text-gray-500">
              Documents section
            </div>
          )}
          {activeTab === 'activity' && (
            <div className="text-sm text-gray-500">
              Activity timeline
            </div>
          )}
          {activeTab === 'invoices' && (
            <div className="text-sm text-gray-500">
              Invoice list
            </div>
          )}

        </div>
      </div>
    </div>

    <RecordPaymentModal
      open={openPaymentModal}
      onClose={() => setOpenPaymentModal(false)}
      initialAmount={selectedRow?.amount}
      onSubmit={(data: any) => {
        console.log("Payment recorded:", data);
      }}
    />
    </>
  );
}