import { useState } from 'react';
import { Calendar, ChevronDown, ChevronRight, FileText, X, Upload, Edit, Trash2, Plus, Home as HomeIcon, BookOpen, ArrowUpRight, ArrowDownLeft, TrendingUp, IndianRupee } from 'lucide-react';
import BreadCrumb from '../../components/BreadCrumb';
import './Cashbook.scss';
import { isMobile } from 'react-device-detect';


export default function Cashbook({ user }) {
  const [activeTab, setActiveTab] = useState('all');
  const [showInModal, setShowInModal] = useState(false);
  const [showOutModal, setShowOutModal] = useState(false);
  const [selectedEntry, setSelectedEntry] = useState(null);
  const [showDetailModal, setShowDetailModal] = useState(false);
  const [selectedInFile, setSelectedInFile] = useState(null);
  const [selectedOutFile, setSelectedOutFile] = useState(null);

  // Sample data
  const entries = [
    {
      id: 1,
      time: '10:22 AM',
      date: '03 Dec 2025',
      type: 'out',
      paymentType: 'ONLINE',
      description: 'Office Office  OfficeS Office upplies Purchase',
      category: 'Expenses',
      amount: 1200,
      photo: null
    },
    {
      id: 2,
      time: '02:30 PM',
      date: '03 Dec 2025',
      type: 'in',
      paymentType: 'CASH',
      description: 'Sales Revenue',
      category: 'Income',
      amount: 5000,
      photo: null
    },
    {
      id: 3,
      time: '04:15 PM',
      date: '03 Dec 2025',
      type: 'out',
      paymentType: 'CASH',
      description: 'Petty Cash Expense',
      category: 'Miscellaneous',
      amount: 350,
      photo: null
    },
    {
      id: 4,
      time: '05:45 PM',
      date: '03 Dec 2025',
      type: 'in',
      paymentType: 'ONLINE',
      description: 'Client Payment Received',
      category: 'Income',
      amount: 8500,
      photo: null
    }
  ];

  const totalIn = entries.filter(e => e.type === 'in').reduce((sum, e) => sum + e.amount, 0);
  const totalOut = entries.filter(e => e.type === 'out').reduce((sum, e) => sum + e.amount, 0);
  const netBalance = totalIn - totalOut;
  const todayIn = totalIn;
  const todayOut = totalOut;

  const filteredEntries = activeTab === 'all'
    ? entries
    : entries.filter(e => e.type === activeTab);

  const handleViewDetails = (entry) => {
    setSelectedEntry(entry);
    setShowDetailModal(true);
  };

  const handleInFileChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      const fileType = file.type;
      if (fileType === 'image/jpeg' || fileType === 'image/png' || fileType === 'image/jpg') {
        setSelectedInFile(file);
      } else {
        alert('Only JPG and PNG files are allowed!');
        e.target.value = '';
      }
    }
  };

  const handleOutFileChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      const fileType = file.type;
      if (fileType === 'image/jpeg' || fileType === 'image/png' || fileType === 'image/jpg') {
        setSelectedOutFile(file);
      } else {
        alert('Only JPG and PNG files are allowed!');
        e.target.value = '';
      }
    }
  };

  const handleCloseInModal = () => {
    setShowInModal(false);
    setSelectedInFile(null);
  };

  const handleCloseOutModal = () => {
    setShowOutModal(false);
    setSelectedOutFile(null);
  };

  const breadcrumbItems = [
    { icon: <HomeIcon />, label: 'Home', path: '/dashboard', active: false },
    { icon: <BookOpen />, label: 'Cashbook', path: '/cashbook', active: true }
  ];

  return (
    <div className="cashbook-home">
      <div className='relative'>
        <BreadCrumb items={breadcrumbItems} showUser={true} />
      </div>
      {/* Main Content */}
      <div className="cashbook-content">
        {/* Left Main Section */}
        <div className="main-section">
          {/* Summary Cards */}
          <div className="summary-cards" >
            <div className="summary-card green">
              <div className="card-icon">
                <ArrowDownLeft size={24} />
              </div>
              <div className="card-content">
                <span className="card-label">Money In</span>
                <span className="card-amount">₹{totalIn.toLocaleString()}</span>
                <span className="card-subtitle">{entries.filter(e => e.type === 'in').length} transactions</span>
              </div>
            </div>

            <div className="summary-card red">
              <div className="card-icon">
                <ArrowUpRight size={24} />
              </div>
              <div className="card-content">
                <span className="card-label">Money Out</span>
                <span className="card-amount">₹{totalOut.toLocaleString()}</span>
                <span className="card-subtitle">{entries.filter(e => e.type === 'out').length} transactions</span>
              </div>
            </div>

            <div className="summary-card blue">
              <div className="card-icon">
                <TrendingUp size={24} />
              </div>
              <div className="card-content">
                <span className="card-label">Net Balance</span>
                <span className="card-amount">₹{netBalance.toLocaleString()}</span>
                <span className="card-subtitle">Current balance</span>
              </div>
            </div>
          </div>

          {/* Transaction Ledger Section */}
          <div className="ledger-section">
            <div className="ledger-header">
              <div className="ledger-title">
                <h2>Transaction Ledger</h2>
                <p>Track all your cash transactions</p>
              </div>
              <div className="ledger-actions">
                <button className="entry-btn in-entry-btn" onClick={() => setShowInModal(true)}>
                  <ArrowDownLeft size={18} />
                  Money In Entry
                </button>
                <button className="entry-btn out-entry-btn" onClick={() => setShowOutModal(true)}>
                  <ArrowUpRight size={18} />
                  Money Out Entry
                </button>
              </div>
            </div>

            {/* Tabs */}
            <div className="tabs-container">
              <div className="tabs">
                <button
                  className={`tab ${activeTab === 'all' ? 'active' : ''}`}
                  onClick={() => setActiveTab('all')}
                >
                  <FileText size={18} />
                  All {!isMobile ? "Transactions" : ""}
                </button>
                <button
                  className={`tab ${activeTab === 'in' ? 'active' : ''}`}
                  onClick={() => setActiveTab('in')}
                >
                  <ArrowDownLeft size={18} />
                  Money In
                </button>
                <button
                  className={`tab ${activeTab === 'out' ? 'active' : ''}`}
                  onClick={() => setActiveTab('out')}
                >
                  <ArrowUpRight size={18} />
                  Money Out
                </button>
              </div>
            </div>

            {/* Search and Filter */}
            <div className="search-filter">
              <div className="search-box">
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
                  <path d="M9 17A8 8 0 1 0 9 1a8 8 0 0 0 0 16zM18 18l-4.35-4.35" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                </svg>
                <input type="text" placeholder="Search transactions..." />
              </div>
              <button className="filter-btn">
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
                  <path d="M4 6h12M6 10h8M8 14h4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                </svg>
              </button>
            </div>

            {/* Entries List */}
            <div className="entries-list">
              {filteredEntries.map((entry) => (
                <div
                  key={entry.id}
                  className={`entry-card ${entry.type}`}
                  onClick={() => handleViewDetails(entry)}
                >
                  <div className="entry-left">
                    <div className={`entry-avatar ${entry.type}`}>
                      {entry.type === 'in' ? <ArrowDownLeft size={20} /> : <ArrowUpRight size={20} />}
                    </div>
                    <div className="entry-info">
                      <div className="entry-header">
                        <span className="entry-desc">{entry.description}</span>
                        <span className={`entry-badge ${entry.type}`}>
                          {entry.type === 'in' ? 'IN' : 'OUT'}
                        </span>
                      </div>
                      <div className="entry-meta">
                        <span className="entry-time">
                          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                            <circle cx="7" cy="7" r="6" stroke="currentColor" strokeWidth="1.5" />
                            <path d="M7 4v3l2 2" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                          </svg>
                          {entry.time} • {entry.date}
                        </span>
                        <span className={`payment-type ${entry.paymentType.toLowerCase()}`}>
                          {entry.paymentType}
                        </span>
                      </div>
                    </div>
                  </div>
                  <div className="entry-right">
                    <span className={`entry-amount ${entry.type}`}>
                      {entry.type === 'in' ? '+ ' : '- '}₹{entry.amount.toLocaleString()}
                    </span>
                    <button className="chevron-btn">
                      <ChevronRight size={18} />
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Right Sidebar */}
        <div className="sidebar-section">
          {/* Quick Actions */}
          <div className="quick-actions-card">
            <h3>Quick Actions</h3>
            <div className="quick-actions">
              <button className="quick-action-btn in" onClick={() => setShowInModal(true)}>
                <ArrowDownLeft size={20} />
                Money In
              </button>
              <button className="quick-action-btn out" onClick={() => setShowOutModal(true)}>
                <ArrowUpRight size={20} />
                Money Out
              </button>
            </div>
          </div>

          {/* Today's Summary */}
          <div className="today-summary-card">
            <h3>Today's Summary</h3>
            <div className="summary-items">
              <div className="summary-item in">
                <div className="summary-icon">
                  <ArrowDownLeft size={18} />
                </div>
                <div className="summary-details">
                  <span className="summary-label">Money In</span>
                  <span className="summary-value">₹{todayIn.toLocaleString()}</span>
                </div>
              </div>
              <div className="summary-item out">
                <div className="summary-icon">
                  <ArrowUpRight size={18} />
                </div>
                <div className="summary-details">
                  <span className="summary-label">Money Out</span>
                  <span className="summary-value">₹{todayOut.toLocaleString()}</span>
                </div>
              </div>
            </div>
            <div className="summary-divider"></div>
            <div className="summary-total">
              <span>Net Today</span>
              <span className={todayIn - todayOut >= 0 ? 'positive' : 'negative'}>
                ₹{(todayIn - todayOut).toLocaleString()}
              </span>
            </div>
          </div>

          {/* Categories */}
          <div className="categories-card">
            <h3>Top Categories</h3>
            <div className="category-list">
              <div className="category-item">
                <div className="category-color" style={{ background: '#10B981' }}></div>
                <span className="category-name">Income</span>
                <span className="category-amount">₹13,500</span>
              </div>
              <div className="category-item">
                <div className="category-color" style={{ background: '#EF4444' }}></div>
                <span className="category-name">Expenses</span>
                <span className="category-amount">₹1,200</span>
              </div>
              <div className="category-item">
                <div className="category-color" style={{ background: '#F59E0B' }}></div>
                <span className="category-name">Miscellaneous</span>
                <span className="category-amount">₹350</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Detail Modal */}
      {showDetailModal && selectedEntry && (
        <div className="modal-overlay" onClick={() => setShowDetailModal(false)}>
          <div className="modal-content detail-modal" onClick={(e) => e.stopPropagation()}>
            <div className="modal-header">
              <h2 className={selectedEntry.type === 'in' ? 'in-title' : 'out-title'}>
                Transaction Details
              </h2>
              <button className="close-btn" onClick={() => setShowDetailModal(false)}>
                <X size={20} />
              </button>
            </div>
            <div className="modal-body">
              <div className={`detail-amount-card ${selectedEntry.type}`}>
                <div className="detail-icon">
                  {selectedEntry.type === 'in' ? <ArrowDownLeft size={28} /> : <ArrowUpRight size={28} />}
                </div>
                <div className="detail-amount-info">
                  <span className="detail-label">{selectedEntry.type === 'in' ? 'Money In' : 'Money Out'}</span>
                  <span className="detail-amount">₹{selectedEntry.amount.toLocaleString()}</span>
                </div>
              </div>

              <div className="detail-info-section">
                <div className="detail-row">
                  <span className="detail-row-label">Description</span>
                  <span className="detail-row-value">{selectedEntry.description}</span>
                </div>
                <div className="detail-row">
                  <span className="detail-row-label">Category</span>
                  <span className="detail-row-value">{selectedEntry.category}</span>
                </div>
                <div className="detail-row">
                  <span className="detail-row-label">Payment Type</span>
                  <span className={`payment-badge ${selectedEntry.paymentType.toLowerCase()}`}>
                    {selectedEntry.paymentType}
                  </span>
                </div>
                <div className="detail-row">
                  <span className="detail-row-label">Date & Time</span>
                  <span className="detail-row-value">{selectedEntry.time} • {selectedEntry.date}</span>
                </div>
              </div>

              <div className="detail-actions">
                <button className="detail-edit-btn">
                  <Edit size={16} />
                  <div>Edit</div>
                </button>
                <button className="detail-delete-btn">
                  <Trash2 size={16} />
                  <div>Delete</div>
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* In Entry Modal */}
      {showInModal && (
        <div className="modal-overlay" onClick={handleCloseInModal}>
          <div className="modal-content entry-modal" onClick={(e) => e.stopPropagation()}>
            <div className="modal-header">
              <h2 className="in-title">Money In Entry</h2>
              <button className="close-btn" onClick={handleCloseInModal}>
                <X size={20} />
              </button>
            </div>
            <div className="modal-body">
              <div className="form-group">
                <label>Amount</label>
                <div className="input-with-icon">
                  <span className="rupee-icon">₹</span>
                  <input type="number" placeholder="Enter Amount" />
                </div>
              </div>

              <div className="form-group">
                <label>Description</label>
                <textarea
                  placeholder="Enter transaction details"
                  rows={3}
                />
              </div>

              <div className="form-group">
                <label>Category</label>
                <div className="select-wrapper">
                  <select>
                    <option>Select Category</option>
                    <option>Income</option>
                    <option>Sales</option>
                    <option>Other</option>
                  </select>
                  <ChevronDown size={16} />
                </div>
              </div>

              <div className="form-group">
                <label>Payment Mode</label>
                <div className="radio-group">
                  <label className="radio-label">
                    <input type="radio" name="payment-in" value="cash" defaultChecked />
                    <span>Cash</span>
                  </label>
                  <label className="radio-label">
                    <input type="radio" name="payment-in" value="online" />
                    <span>Online</span>
                  </label>
                </div>
              </div>

              <div className="form-group">
                <label>Date</label>
                <div className="input-with-icon date-input">
                  <input type="text" value="03 Dec 2025" readOnly />
                  <Calendar size={16} />
                </div>
              </div>

              <div className="form-group">
                <label>Attach Bill (JPG or PNG only)</label>
                <div className="upload-area">
                  <input
                    type="file"
                    id="in-file-upload"
                    accept=".jpg,.jpeg,.png"
                    onChange={handleInFileChange}
                    style={{ display: 'none' }}
                  />
                  <label htmlFor="in-file-upload" className="upload-label">
                    {selectedInFile ? (
                      <div className="file-preview">
                        <FileText size={32} className="file-icon" />
                        <p className="file-name">{selectedInFile.name}</p>
                        <p className="file-size">{(selectedInFile.size / 1024).toFixed(2)} KB</p>
                      </div>
                    ) : (
                      <>
                        <Upload size={32} className="upload-icon" />
                        <p className="upload-text">Click to upload</p>
                        <p className="upload-hint">Only JPG or PNG file format supported</p>
                      </>
                    )}
                  </label>
                </div>
              </div>

              <button className="save-btn">
                Save Transaction
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Out Entry Modal */}
      {showOutModal && (
        <div className="modal-overlay" onClick={handleCloseOutModal}>
          <div className="modal-content entry-modal" onClick={(e) => e.stopPropagation()}>
            <div className="modal-header">
              <h2 className="out-title">Money Out Entry</h2>
              <button className="close-btn" onClick={handleCloseOutModal}>
                <X size={20} />
              </button>
            </div>
            <div className="modal-body">
              <div className="form-group">
                <label>Amount</label>
                <div className="input-with-icon">
                  <span className="rupee-icon">₹</span>
                  <input type="number" placeholder="Enter Amount" />
                </div>
              </div>

              <div className="form-group">
                <label>Description</label>
                <textarea
                  placeholder="Enter transaction details"
                  rows={3}
                />
              </div>

              <div className="form-group">
                <label>Category</label>
                <div className="select-wrapper">
                  <select>
                    <option>Select Category</option>
                    <option>Expenses</option>
                    <option>Purchase</option>
                    <option>Miscellaneous</option>
                  </select>
                  <ChevronDown size={16} />
                </div>
              </div>

              <div className="form-group">
                <label>Payment Mode</label>
                <div className="radio-group">
                  <label className="radio-label">
                    <input type="radio" name="payment-out" value="cash" defaultChecked />
                    <span>Cash</span>
                  </label>
                  <label className="radio-label">
                    <input type="radio" name="payment-out" value="online" />
                    <span>Online</span>
                  </label>
                </div>
              </div>

              <div className="form-group">
                <label>Date</label>
                <div className="input-with-icon date-input">
                  <input type="text" value="03 Dec 2025" readOnly />
                  <Calendar size={16} />
                </div>
              </div>

              <div className="form-group">
                <label>Attach Bill (JPG or PNG only)</label>
                <div className="upload-area">
                  <input
                    type="file"
                    id="out-file-upload"
                    accept=".jpg,.jpeg,.png"
                    onChange={handleOutFileChange}
                    style={{ display: 'none' }}
                  />
                  <label htmlFor="out-file-upload" className="upload-label">
                    {selectedOutFile ? (
                      <div className="file-preview">
                        <FileText size={32} className="file-icon" />
                        <p className="file-name">{selectedOutFile.name}</p>
                        <p className="file-size">{(selectedOutFile.size / 1024).toFixed(2)} KB</p>
                      </div>
                    ) : (
                      <>
                        <Upload size={32} className="upload-icon" />
                        <p className="upload-text">Click to upload</p>
                        <p className="upload-hint">Only JPG or PNG file format supported</p>
                      </>
                    )}
                  </label>
                </div>
              </div>

              <button className="save-btn">
                Save Transaction
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
