import { useEffect, useMemo, useRef, useState } from 'react';
import { Wallet, ArrowUpRight, Calendar, Filter, Download, IndianRupee, CreditCard, X, Plus, Home as HomeIcon, Receipt } from 'lucide-react';
import BreadCrumb from '@/components/BreadCrumb';
import "./Expenses.scss"

const defaultExpenses = [
  {
    id: 1,
    title: 'Inventory Restock',
    vendor: 'Fresh Farm Wholesale',
    category: 'Inventory',
    date: '2025-12-03',
    paymentType: 'UPI',
    amount: 18500,
    status: 'Settled',
    isFixedCommitment: false,
  },
  {
    id: 2,
    title: 'Shop Rent',
    vendor: 'Sai Properties',
    category: 'Fixed Cost',
    date: '2025-12-01',
    paymentType: 'Bank Transfer',
    amount: 32000,
    status: 'Scheduled',
    isFixedCommitment: true,
  },
  {
    id: 3,
    title: 'Delivery Partner Payout',
    vendor: 'Anil Kumar',
    category: 'Logistics',
    date: '2025-11-30',
    paymentType: 'Cash',
    amount: 6500,
    status: 'Settled',
    isFixedCommitment: false,
  },
  {
    id: 4,
    title: 'Electricity Bill',
    vendor: 'TNEB',
    category: 'Utilities',
    date: '2025-11-28',
    paymentType: 'NEFT',
    amount: 5400,
    status: 'Overdue',
    isFixedCommitment: true,
  },
  {
    id: 5,
    title: 'Packing Material',
    vendor: 'BoxIt Packaging',
    category: 'Supplies',
    date: '2025-11-27',
    paymentType: 'Card',
    amount: 2600,
    status: 'Settled',
    isFixedCommitment: false,
  },
];

const defaultCategoryOptions = ['Inventory', 'Fixed Cost', 'Logistics', 'Utilities', 'Supplies', 'Miscellaneous'];
const statusOptions = ['Scheduled', 'Settled', 'Overdue'];

const formatDisplayDate = (isoDate) => {
  return new Date(isoDate).toLocaleDateString('en-GB', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
  });
};

const formatRangeLabel = (start, end) => {
  if (!start && !end) return 'All Time';
  const startDate = start ? formatDisplayDate(start) : '...';
  const endDate = end ? formatDisplayDate(end) : '...';
  return `${startDate} - ${endDate}`;
};

export default function Expenses({ user }) {
  const [searchQuery, setSearchQuery] = useState('');
  const [expenses, setExpenses] = useState(defaultExpenses);
  const [categoryOptions, setCategoryOptions] = useState(defaultCategoryOptions);
  const [filters, setFilters] = useState({
    startDate: '2025-11-15',
    endDate: '2025-12-03',
    categories: [],
    statuses: [],
  });
  const [isDatePickerOpen, setIsDatePickerOpen] = useState(false);
  const [isFiltersOpen, setIsFiltersOpen] = useState(false);
  const [isRecordModalOpen, setIsRecordModalOpen] = useState(false);
  const [isAddingCategory, setIsAddingCategory] = useState(false);
  const [newCategory, setNewCategory] = useState('');
  const [formData, setFormData] = useState({
    title: '',
    vendor: '',
    category: 'Inventory',
    date: new Date().toISOString().slice(0, 10),
    paymentType: 'Cash',
    amount: '',
    status: 'Scheduled',
    isFixedCommitment: false,
  });
  const datePickerRef = useRef(null);
  const filtersRef = useRef(null);

  useEffect(() => {
    const handleDocumentClick = (event) => {
      const isInsideDatePicker = datePickerRef.current?.contains(event.target);
      const isInsideFilters = filtersRef.current?.contains(event.target);
      if (!isInsideDatePicker) {
        setIsDatePickerOpen(false);
      }
      if (!isInsideFilters) {
        setIsFiltersOpen(false);
      }
    };

    document.addEventListener('click', handleDocumentClick);
    return () => document.removeEventListener('click', handleDocumentClick);
  }, []);

  const totalSpent = expenses.reduce((sum, expense) => sum + expense.amount, 0);
  const recurringExpenses = expenses.filter((expense) => expense.isFixedCommitment);
  const pendingAmount = expenses
    .filter((expense) => expense.status !== 'Settled')
    .reduce((sum, expense) => sum + expense.amount, 0);

  const filteredExpenses = useMemo(() => {
    const query = searchQuery.toLowerCase();
    return expenses.filter((expense) => {
      const matchesSearch =
        !query ||
        expense.title.toLowerCase().includes(query) ||
        expense.vendor.toLowerCase().includes(query) ||
        expense.category.toLowerCase().includes(query);
      const matchesCategory =
        !filters.categories.length || filters.categories.includes(expense.category);
      const matchesStatus =
        !filters.statuses.length || filters.statuses.includes(expense.status);
      const matchesDate =
        (!filters.startDate || new Date(expense.date) >= new Date(filters.startDate)) &&
        (!filters.endDate || new Date(expense.date) <= new Date(filters.endDate));
      return matchesSearch && matchesCategory && matchesStatus && matchesDate;
    });
  }, [expenses, filters.categories, filters.endDate, filters.startDate, filters.statuses, searchQuery]);

  const handleChange = (field) => (event) => {
    const value =
      field === 'amount'
        ? event.target.value.replace(/[^\d]/g, '')
        : field === 'isFixedCommitment'
          ? event.target.checked
          : event.target.value;
    setFormData((prev) => ({
      ...prev,
      [field]: value,
    }));
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    if (!formData.title.trim() || !formData.vendor.trim() || !formData.amount) {
      return;
    }

    const newExpense = {
      id: Date.now(),
      ...formData,
      amount: Number(formData.amount),
    };

    setExpenses((prev) => [newExpense, ...prev]);
    setIsRecordModalOpen(false);
    setFormData({
      title: '',
      vendor: '',
      category: 'Inventory',
      date: new Date().toISOString().slice(0, 10),
      paymentType: 'Cash',
      amount: '',
      status: 'Scheduled',
      isFixedCommitment: false,
    });
  };

  const breadcrumbItems = [
    { icon: <HomeIcon />, label: 'Home', active: false },
    { icon: <Receipt />, label: 'Expenses', active: true }
  ];

  return (
    <div className="space-y-4 sm:space-y-6  md:space-y-7 lg:space-y-8">
      <div className='relative'>
        <BreadCrumb items={breadcrumbItems} showUser={true} />
      </div>      <header className="flex flex-col gap-3 sm:gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold text-gray-900 mt-1">Expenses</h1>
        </div>
        <div className="flex items-center gap-2 sm:gap-3">
          <button
            className="flex items-center gap-2 px-3 py-2 sm:px-4 sm:py-2.5 
            bg-gradient-to-r from-[#FF6B00] to-[#FF8534] text-white rounded-xl
             text-xs sm:text-sm font-semibold hover:shadow-lg transition-all   sm:w-auto justify-center"
            onClick={() => setIsRecordModalOpen(true)}
          >
            <span className="hidden sm:inline">Record Expense</span>
            <span className="sm:hidden">Record</span>
            <Plus className="w-4 h-4" />
          </button>
        </div>
      </header>

      <section className="grid gap-4 sm:gap-5 grid-cols-1 sm:grid-cols-2 lg:grid-cols-3">
        {/* Total Spent */}
        <div className="rounded-xl sm:rounded-2xl p-4 sm:p-5 shadow-sm border border-orange-100 bg-orange-50/80">
          <div className="flex items-center justify-between text-gray-500 text-xs font-semibold uppercase tracking-wide">
            Total Spent
            <Wallet className="w-4 h-4" />
          </div>
          <p className="text-2xl sm:text-3xl font-bold text-gray-900 mt-2 sm:mt-3">₹ {totalSpent.toLocaleString()}</p>
          <p className="text-xs sm:text-sm text-gray-500 mt-1 sm:mt-2">Across {expenses.length} expense entries</p>
        </div>

        {/* Recurring Bills / Fixed commitments */}
        <div className="rounded-xl sm:rounded-2xl p-4 sm:p-5 shadow-sm border border-emerald-100 bg-emerald-50/80">
          <div className="flex items-center justify-between text-gray-500 text-xs font-semibold uppercase tracking-wide">
            Recurring Bills
            <CreditCard className="w-4 h-4" />
          </div>
          <p className="text-2xl sm:text-3xl font-bold text-gray-900 mt-2 sm:mt-3">₹ {recurringExpenses.reduce((sum, expense) => sum + expense.amount, 0).toLocaleString()}</p>
          <p className="text-xs sm:text-sm text-gray-500 mt-1 sm:mt-2">{recurringExpenses.length} upcoming fixed commitments</p>
        </div>

        {/* Pending exposure */}
        <div className="rounded-xl sm:rounded-2xl p-4 sm:p-5 shadow-sm border border-rose-100 bg-rose-50/80">
          <div className="flex items-center justify-between text-gray-500 text-xs font-semibold uppercase tracking-wide">
            Pending
            <IndianRupee className="w-4 h-4" />
          </div>
          <p className="text-2xl sm:text-3xl font-bold text-red-600 mt-2 sm:mt-3">₹ {pendingAmount.toLocaleString()}</p>
          <p className="text-xs sm:text-sm text-gray-500 mt-1 sm:mt-2">Needs attention before month end</p>
        </div>
      </section>

      <section className="bg-white border border-gray-200 rounded-xl sm:rounded-2xl shadow-sm overflow-hidden">
        <div className="flex flex-col flex-wrap gap-3 sm:gap-4 border-b border-gray-100 p-4 sm:p-6 md:flex-row md:items-center md:justify-between">
          <div>
            <h2 className="text-lg sm:text-xl font-bold text-gray-900">Expense Ledger</h2>
            <p className="text-xs sm:text-sm text-gray-500">Search, filter and export detailed expenses</p>
          </div>
          <div className="flex items-center gap-2 flex-wrap max-sm:flex-col">
            <div className="relative  max-sm:w-full lg:flex-none" ref={datePickerRef}>
              <button
                type="button"
                className="flex items-center gap-1.5 px-2 sm:px-4 py-2 
                border border-gray-200 rounded-xl text-xs sm:text-sm font-medium text-gray-700
                 hover:bg-gray-50 transition-colors w-full sm:w-auto justify-center "
                onClick={(event) => {
                  event.stopPropagation();
                  setIsDatePickerOpen((prev) => !prev);
                  setIsFiltersOpen(false);
                }}
              >
                <Calendar className="w-4 h-4 flex-shrink-0" />
                <span className="truncate">{formatRangeLabel(filters.startDate, filters.endDate)}</span>
              </button>
              {isDatePickerOpen && (
                <div className="fixed sm:absolute left-1/2 -translate-x-1/2 top-1/2 -translate-y-1/2 sm:left-auto sm:right-40 sm:top-auto sm:translate-x-0 sm:translate-y-0 mt-0 sm:mt-2 w-[calc(100vw-4rem)] sm:w-64 max-w-sm rounded-xl sm:rounded-2xl border border-gray-200 bg-white shadow-xl p-3 sm:p-4 space-y-3 z-50">
                  <div>
                    <label className="text-xs font-semibold text-gray-500 uppercase">From</label>
                    <input
                      type="date"
                      value={filters.startDate}
                      onChange={(event) =>
                        setFilters((prev) => ({ ...prev, startDate: event.target.value }))
                      }
                      className="mt-1 w-full rounded-xl border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[#FF6B00]"
                    />
                  </div>
                  <div>
                    <label className="text-xs font-semibold text-gray-500 uppercase">To</label>
                    <input
                      type="date"
                      value={filters.endDate}
                      onChange={(event) =>
                        setFilters((prev) => ({ ...prev, endDate: event.target.value }))
                      }
                      className="mt-1 w-full rounded-xl border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[#FF6B00]"
                    />
                  </div>
                  <button
                    type="button"
                    className="w-full rounded-xl border border-gray-200 px-3 py-2 text-sm font-medium text-gray-600 hover:bg-gray-50"
                    onClick={(event) => {
                      event.stopPropagation();
                      setFilters((prev) => ({ ...prev, startDate: '', endDate: '' }));
                    }}
                  >
                    Clear Range
                  </button>
                </div>
              )}
            </div>
            <div className="relative max-sm:w-full lg:flex-none" ref={filtersRef}>
              <button
                type="button"
                className="flex items-center gap-1.5 px-2 sm:px-4 py-2 border border-gray-200 rounded-xl text-xs sm:text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors w-full sm:w-auto justify-center"
                onClick={(event) => {
                  event.stopPropagation();
                  setIsFiltersOpen((prev) => !prev);
                  setIsDatePickerOpen(false);
                }}
              >
                <Filter className="  h-4  " />
                <span>Filters</span>
                {(filters.categories.length > 0 || filters.statuses.length > 0) && (
                  <span className="ml-1 text-xs font-semibold text-[#FF6B00]">
                    {filters.categories.length + filters.statuses.length}
                  </span>
                )}
              </button>
              {isFiltersOpen && (
                <div className="fixed sm:absolute left-1/2 -translate-x-1/2 top-1/2 -translate-y-1/2 sm:left-auto sm:right-0 sm:top-auto sm:translate-x-0 sm:translate-y-0 mt-0 sm:mt-2 w-[calc(100vw-4rem)] sm:w-72 max-w-sm rounded-xl sm:rounded-2xl border border-gray-200 bg-white shadow-xl p-3 sm:p-4 space-y-4 z-10">
                  <div>
                    <p className="text-xs font-semibold text-gray-500 uppercase mb-2">Categories</p>
                    <div className="flex flex-wrap gap-2">
                      {categoryOptions.map((category) => {
                        const isActive = filters.categories.includes(category);
                        return (
                          <button
                            key={category}
                            type="button"
                            onClick={() =>
                              setFilters((prev) => ({
                                ...prev,
                                categories: isActive
                                  ? prev.categories.filter((item) => item !== category)
                                  : [...prev.categories, category],
                              }))
                            }
                            className={`px-3 py-1.5 rounded-full text-xs font-semibold border ${isActive
                              ? 'bg-[#FFF4F0] text-[#FF6B00] border-[#FFBB8B]'
                              : 'text-gray-600 border-gray-200 hover:bg-gray-50'
                              }`}
                          >
                            {category}
                          </button>
                        );
                      })}
                    </div>
                  </div>
                  <div>
                    <p className="text-xs font-semibold text-gray-500 uppercase mb-2">Status</p>
                    <div className="flex flex-wrap gap-2">
                      {statusOptions.map((status) => {
                        const isActive = filters.statuses.includes(status);
                        return (
                          <button
                            key={status}
                            type="button"
                            onClick={() =>
                              setFilters((prev) => ({
                                ...prev,
                                statuses: isActive
                                  ? prev.statuses.filter((item) => item !== status)
                                  : [...prev.statuses, status],
                              }))
                            }
                            className={`px-3 py-1.5 rounded-full text-xs font-semibold border ${isActive
                              ? 'bg-[#ECFDF3] text-[#15803D] border-[#86EFAC]'
                              : 'text-gray-600 border-gray-200 hover:bg-gray-50'
                              }`}
                          >
                            {status}
                          </button>
                        );
                      })}
                    </div>
                  </div>
                  <div className="flex justify-between">
                    <button
                      type="button"
                      className="text-xs font-semibold text-gray-500 hover:text-gray-700"
                      onClick={() => setFilters((prev) => ({ ...prev, categories: [], statuses: [] }))}
                    >
                      Clear filters
                    </button>
                    <button
                      type="button"
                      className="text-xs font-semibold text-[#FF6B00] hover:text-[#FF8534]"
                      onClick={() => setIsFiltersOpen(false)}
                    >
                      Done
                    </button>
                  </div>
                </div>
              )}
            </div>
            <button
              type="button"
              className="flex items-center gap-1.5 px-2 sm:px-5 py-2 bg-gray-900 text-white
               rounded-xl text-xs sm:text-sm font-semibold hover:bg-gray-800 transition-colors
                    justify-center max-sm:w-full"
              onClick={() => {
                if (!filteredExpenses.length) return;
                const header = ['Title', 'Vendor', 'Category', 'Date', 'Payment Mode', 'Status', 'Amount'];
                const rows = filteredExpenses.map((expense) => [
                  expense.title,
                  expense.vendor,
                  expense.category,
                  formatDisplayDate(expense.date),
                  expense.paymentType,
                  expense.status,
                  expense.amount,
                ]);
                const csv = [header, ...rows]
                  .map((row) => row.map((value) => `"${String(value).replace(/"/g, '""')}"`).join(','))
                  .join('\n');
                const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
                const url = URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = url;
                link.download = `expenses-${Date.now()}.csv`;
                link.click();
                URL.revokeObjectURL(url);
              }}
            >
              <Download className="w-4 h-4" />
              Export CSV
            </button>
          </div>
        </div>

        <div className="p-4 sm:p-6 border-b border-gray-100 bg-gray-50">
          <div className="relative">
            <input
              type="text"
              value={searchQuery}
              onChange={(event) => setSearchQuery(event.target.value)}
              placeholder="Search vendor, category, amount..."
              className="  pl-9 sm:pl-11 pr-4 py-2.5 sm:py-3 bg-white 
              border border-gray-200 rounded-xl text-xs sm:text-sm focus:outline-none focus:ring-2 
              focus:ring-[#FF6B00] focus:border-transparent max-sm:w-full w-80"
            />
          </div>
        </div>

      </section>
      {/* Table Section */}

      <div className="overflow-x-auto  2xl:w-[90%] md:w-[100%] ">
        <div className="inline-block min-w-full align-middle tableSectionMedia">
          <table className="min-w-full divide-y divide-gray-100">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-3 sm:px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wide">Expense</th>
                <th className="sm:table-cell px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wide">Category</th>
                <th className="md:table-cell px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wide">Date</th>
                <th className="lg:table-cell px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wide w-max whitespace-nowrap">Payment Mode</th>
                <th className="px-3 sm:px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wide">Status</th>
                <th className="px-3 sm:px-6 py-3 text-right text-xs font-semibold text-gray-500 uppercase tracking-wide">Amount</th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-100">
              {filteredExpenses.map((expense) => (
                <tr key={expense.id} className="hover:bg-gray-50 transitioStatus	Amount
                Inventory Restock
                
                Fresh Farm Wholesale
                
                UPI
                Inventory	03 Dec 2025	
                Settled
                ₹ 18,500
                Shop Rent
                
                Sai Properties
                
                Bank Transfer
                Fixed Cost	01 Dec 2025	
                Scheduled
                ₹ 32,000
                Delivery Partner Payout
                
                Anil Kumar
                
                Cash
                Logistics	30 Nov 2025	
                Settled
                ₹ 6,500
                Electricity Bill
                
                TNEB
                
                NEFT
                Utilities	28 Nov 2025	
                Overdue
                ₹ 5,400
                Packing Material
                
                BoxIt Packaging
                
                Card
                Supplies	27 Nov 2025	
                Settled
                ₹ 2,600n-colors">
                  <td className="px-3 sm:px-6 py-3 sm:py-4">
                    <p className="text-xs sm:text-sm font-semibold text-gray-900">{expense.title}</p>
                    <p className="text-xs text-gray-500 mt-0.5">{expense.vendor}</p>
                    <div className="sm:hidden mt-1 flex flex-wrap gap-1.5">
                      <span className="text-xs text-gray-500">{expense.category}</span>
                      <span className="text-xs text-gray-400">•</span>
                      <span className="text-xs text-gray-500">{formatDisplayDate(expense.date)}</span>
                    </div>
                    <div className="md:hidden sm:flex hidden mt-1 flex-wrap gap-1.5">
                      <span className="text-xs text-gray-500">{formatDisplayDate(expense.date)}</span>
                    </div>
                    <div className="lg:hidden md:flex hidden mt-1">
                      <span className="text-xs text-gray-500">{expense.paymentType}</span>
                    </div>
                  </td>
                  <td className="sm:table-cell px-6 py-4 text-sm font-medium text-gray-700">{expense.category}</td>
                  <td className="md:table-cell px-6 py-4 text-sm text-gray-500">{formatDisplayDate(expense.date)}</td>
                  <td className="lg:table-cell px-6 py-4 text-sm text-gray-500">{expense.paymentType}</td>
                  <td className="px-3 sm:px-6 py-3 sm:py-4">
                    <span
                      className={`inline-flex items-center gap-1 px-2 sm:px-3 py-1 rounded-full text-xs font-semibold whitespace-nowrap ${expense.status === 'Settled'
                        ? 'bg-green-100 text-green-700'
                        : expense.status === 'Overdue'
                          ? 'bg-red-100 text-red-700'
                          : 'bg-amber-100 text-amber-700'
                        }`}
                    >
                      <ArrowUpRight className="w-3 h-3 rotate-45 flex-shrink-0" />
                      <span>{expense.status}</span>
                    </span>
                  </td>
                  <td className="px-3 sm:px-6 py-3 sm:py-4 text-right text-xs sm:text-sm font-bold text-gray-900 ">
                    <div className="flex whitespace-nowrap gap-4 justify-end">
                      ₹ {expense.amount.toLocaleString()}
                    </div>                    </td>
                </tr>
              ))}
              {!filteredExpenses.length && (
                <tr>
                  <td colSpan={6} className="px-4 sm:px-6 py-8 sm:py-10 text-center text-xs sm:text-sm text-gray-500">
                    No expenses match "{searchQuery}".
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {isRecordModalOpen && (
        <div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center px-4 py-4 sm:py-8 z-50 overflow-y-auto" onClick={() => setIsRecordModalOpen(false)}>
          <div
            className="w-full max-w-lg bg-white rounded-xl sm:rounded-2xl shadow-2xl border border-gray-100 p-4 sm:p-6 my-auto max-h-[90vh] overflow-y-auto"
            onClick={(event) => event.stopPropagation()}
          >
            <div className="flex items-center justify-between mb-4 sm:mb-6">
              <div>
                <h3 className="text-lg sm:text-xl font-bold text-gray-900">Record Expense</h3>
                <p className="text-xs sm:text-sm text-gray-500">Capture business spending instantly</p>
              </div>
              <button className="p-2 rounded-full hover:bg-gray-100 flex-shrink-0" onClick={() => setIsRecordModalOpen(false)}>
                <X className="w-5 h-5 text-gray-500" />
              </button>
            </div>

            <form className="space-y-3 sm:space-y-4" onSubmit={handleSubmit}>
              <div className="grid gap-3 sm:gap-4 grid-cols-1 sm:grid-cols-2">
                <label className="text-xs sm:text-sm font-medium text-gray-700">
                  Expense Title
                  <input
                    type="text"
                    value={formData.title}
                    onChange={handleChange('title')}
                    placeholder="e.g., Rent payment"
                    className="mt-1 w-full rounded-xl border border-gray-200 px-3 py-2 text-xs sm:text-sm focus:outline-none focus:ring-2 focus:ring-[#FF6B00]"
                    required
                  />
                </label>

                <label className="text-xs sm:text-sm font-medium text-gray-700">
                  Vendor / Payee
                  <input
                    type="text"
                    value={formData.vendor}
                    onChange={handleChange('vendor')}
                    placeholder="e.g., Sai Properties"
                    className="mt-1 w-full rounded-xl border border-gray-200 px-3 py-2 text-xs sm:text-sm focus:outline-none focus:ring-2 focus:ring-[#FF6B00]"
                    required
                  />
                </label>
              </div>

              <div className="grid gap-3 sm:gap-4 grid-cols-1 sm:grid-cols-2">
                <label className="text-xs sm:text-sm font-medium text-gray-700">
                  Category
                  <select
                    value={formData.category}
                    onChange={handleChange('category')}
                    className="mt-1 w-full rounded-xl border border-gray-200 px-3 py-2 text-xs sm:text-sm focus:outline-none focus:ring-2 focus:ring-[#FF6B00]"
                  >
                    {categoryOptions.map((option) => (
                      <option key={option} value={option}>
                        {option}
                      </option>
                    ))}
                  </select>
                  <button
                    type="button"
                    className="mt-1 text-xs font-semibold text-[#FF6B00] hover:text-[#FF8534]"
                    onClick={() => {
                      setIsAddingCategory(true);
                      setNewCategory('');
                    }}
                  >
                    + Add new category
                  </button>
                  {isAddingCategory && (
                    <div className="mt-2 flex flex-col sm:flex-row gap-2 items-stretch sm:items-center">
                      <input
                        type="text"
                        value={newCategory}
                        onChange={(event) => setNewCategory(event.target.value)}
                        placeholder="e.g., Salary, Personal, Marketing"
                        className="flex-1 rounded-xl border border-gray-200 px-3 py-2 text-xs focus:outline-none focus:ring-2 focus:ring-[#FF6B00]"
                      />
                      <div className="flex gap-2">
                        <button
                          type="button"
                          className="flex-1 sm:flex-none px-3 py-1.5 rounded-xl bg-gray-900 text-white text-xs font-semibold hover:bg-gray-800"
                          onClick={() => {
                            const label = newCategory.trim();
                            if (!label) return;
                            if (!categoryOptions.includes(label)) {
                              setCategoryOptions((prev) => [...prev, label]);
                            }
                            setFormData((prev) => ({ ...prev, category: label }));
                            setIsAddingCategory(false);
                            setNewCategory('');
                          }}
                        >
                          Save
                        </button>
                        <button
                          type="button"
                          className="flex-1 sm:flex-none px-2 py-1.5 rounded-xl border border-gray-200 text-xs font-medium text-gray-600 hover:bg-gray-50"
                          onClick={() => {
                            setIsAddingCategory(false);
                            setNewCategory('');
                          }}
                        >
                          Cancel
                        </button>
                      </div>
                    </div>
                  )}
                </label>

                <label className="text-xs sm:text-sm font-medium text-gray-700">
                  Payment Mode
                  <select
                    value={formData.paymentType}
                    onChange={handleChange('paymentType')}
                    className="mt-1 w-full rounded-xl border border-gray-200 px-3 py-2 text-xs sm:text-sm focus:outline-none focus:ring-2 focus:ring-[#FF6B00]"
                  >
                    <option>Cash</option>
                    <option>Card</option>
                    <option>UPI</option>
                    <option>Bank Transfer</option>
                    <option>NEFT</option>
                  </select>
                </label>
              </div>

              <div className="grid gap-3 sm:gap-4 grid-cols-1 sm:grid-cols-2">
                <label className="text-xs sm:text-sm font-medium text-gray-700">
                  Expense Date
                  <input
                    type="date"
                    value={formData.date}
                    onChange={handleChange('date')}
                    className="mt-1 w-full rounded-xl border border-gray-200 px-3 py-2 text-xs sm:text-sm focus:outline-none focus:ring-2 focus:ring-[#FF6B00]"
                  />
                </label>

                <label className="text-xs sm:text-sm font-medium text-gray-700">
                  Status
                  <select
                    value={formData.status}
                    onChange={handleChange('status')}
                    className="mt-1 w-full rounded-xl border border-gray-200 px-3 py-2 text-xs sm:text-sm focus:outline-none focus:ring-2 focus:ring-[#FF6B00]"
                  >
                    <option>Scheduled</option>
                    <option>Settled</option>
                    <option>Overdue</option>
                  </select>
                </label>
              </div>

              <div className="grid gap-3 sm:gap-4 grid-cols-1 sm:grid-cols-2 items-end">
                <label className="text-xs sm:text-sm font-medium text-gray-700">
                  Amount
                  <div className="mt-1 flex items-center rounded-xl border border-gray-200 px-3 py-2 focus-within:ring-2 focus-within:ring-[#FF6B00]">
                    <span className="text-gray-500 mr-2 text-xs sm:text-sm">₹</span>
                    <input
                      type="number"
                      value={formData.amount}
                      onChange={handleChange('amount')}
                      placeholder="0"
                      min="0"
                      className="w-full bg-transparent text-xs sm:text-sm focus:outline-none"
                      required
                    />
                  </div>
                </label>

                <label className="flex items-center gap-2 text-xs sm:text-sm font-medium text-gray-700">
                  <input
                    type="checkbox"
                    checked={formData.isFixedCommitment}
                    onChange={handleChange('isFixedCommitment')}
                    className="h-4 w-4 rounded border-gray-300 text-[#FF6B00] focus:ring-[#FF6B00] flex-shrink-0"
                  />
                  <span>
                    Mark as <span className="font-semibold">fixed commitment</span>
                  </span>
                </label>
              </div>

              <div className="flex flex-col-reverse sm:flex-row items-stretch sm:items-center justify-end gap-2 sm:gap-3 pt-2">
                <button
                  type="button"
                  className="px-4 py-2.5 sm:py-2 rounded-xl border border-gray-200 text-xs sm:text-sm font-medium text-gray-600 hover:bg-gray-50"
                  onClick={() => setIsRecordModalOpen(false)}
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-5 py-2.5 sm:py-2 rounded-xl bg-gradient-to-r from-[#FF6B00] to-[#FF8534] text-white text-xs sm:text-sm font-semibold hover:shadow-lg transition-shadow"
                >
                  Save Expense
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}

