import { useState } from 'react';
import { Home as HomeIcon, ChevronRight, BookOpen, FileText, Users, Package, Download, FileSpreadsheet, Calendar, Filter, Search, PieChart as PieChartIcon, BarChart3 } from 'lucide-react';
import { PieChart, Pie, Cell, ResponsiveContainer, BarChart, Bar, XAxis, YAxis, Tooltip, Legend, CartesianGrid } from 'recharts';
import BreadCrumb from '../../components/BreadCrumb';
import './Reports.scss';

export default function Reports({ user }) {
  const [activeTab, setActiveTab] = useState('cashbook');
  const [cashbookDateRange, setCashbookDateRange] = useState('This Month');
  const [transactionDateRange, setTransactionDateRange] = useState('This Month');
  const [transactionType, setTransactionType] = useState('All');
  const [showCashbookCharts, setShowCashbookCharts] = useState(false);
  const [showTransactionCharts, setShowTransactionCharts] = useState(false);

  // Sample Cashbook Data
  const cashbookData = {
    totalIn: 13500,
    totalOut: 1550,
    netBalance: 11950,
    transactions: 4,
    period: 'December 2025'
  };

  // Cashbook Chart Data
  const cashbookChartData = [
    { name: 'Week 1', moneyIn: 3500, moneyOut: 400 },
    { name: 'Week 2', moneyIn: 2800, moneyOut: 350 },
    { name: 'Week 3', moneyIn: 4200, moneyOut: 500 },
    { name: 'Week 4', moneyIn: 3000, moneyOut: 300 },
  ];

  const cashbookPieData = [
    { name: 'Money In', value: cashbookData.totalIn, color: '#10B981' },
    { name: 'Money Out', value: cashbookData.totalOut, color: '#EF4444' },
  ];

  // Sample Transaction Data
  const transactionData = {
    customers: {
      totalReceivable: 59550,
      totalReceived: 13500,
      pending: 46050,
      count: 6
    },
    suppliers: {
      totalPayable: 9800,
      totalPaid: 1550,
      pending: 8250,
      count: 5
    }
  };

  // Transaction Chart Data
  const transactionChartData = [
    { name: 'Customers', receivable: 59550, received: 13500, pending: 46050 },
    { name: 'Suppliers', receivable: 9800, received: 1550, pending: 8250 },
  ];

  const transactionPieData = [
    { name: 'Customer Receivable', value: transactionData.customers.totalReceivable, color: '#3B82F6' },
    { name: 'Supplier Payable', value: transactionData.suppliers.totalPayable, color: '#EF4444' },
  ];

  const handleDownloadPDF = (reportType) => {
    // Create simple text-based PDF content
    let content = '';

    if (reportType === 'Cashbook Report') {
      content = `
CASHBOOK REPORT
${cashbookData.period}
======================

SUMMARY:
- Total Money In: ₹${cashbookData.totalIn.toLocaleString()}
- Total Money Out: ₹${cashbookData.totalOut.toLocaleString()}
- Net Balance: ₹${cashbookData.netBalance.toLocaleString()}
- Total Transactions: ${cashbookData.transactions}

Generated on: ${new Date().toLocaleString()}
      `;
    } else {
      content = `
ALL TRANSACTION REPORT
${cashbookData.period}
======================

CUSTOMER TRANSACTIONS:
- Total Receivable: ₹${transactionData.customers.totalReceivable.toLocaleString()}
- Total Received: ₹${transactionData.customers.totalReceived.toLocaleString()}
- Pending Amount: ₹${transactionData.customers.pending.toLocaleString()}
- Total Customers: ${transactionData.customers.count}

SUPPLIER TRANSACTIONS:
- Total Payable: ₹${transactionData.suppliers.totalPayable.toLocaleString()}
- Total Paid: ₹${transactionData.suppliers.totalPaid.toLocaleString()}
- Pending Amount: ₹${transactionData.suppliers.pending.toLocaleString()}
- Total Suppliers: ${transactionData.suppliers.count}

Generated on: ${new Date().toLocaleString()}
      `;
    }

    // Create blob and download
    const blob = new Blob([content], { type: 'text/plain' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${reportType.replace(/ /g, '_')}_${new Date().toISOString().split('T')[0]}.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
  };

  const handleDownloadExcel = (reportType) => {
    let csvContent = '';

    if (reportType === 'Cashbook Report') {
      csvContent = `Cashbook Report - ${cashbookData.period}\n\n`;
      csvContent += `Category,Amount\n`;
      csvContent += `Total Money In,${cashbookData.totalIn}\n`;
      csvContent += `Total Money Out,${cashbookData.totalOut}\n`;
      csvContent += `Net Balance,${cashbookData.netBalance}\n`;
      csvContent += `Total Transactions,${cashbookData.transactions}\n`;
    } else {
      csvContent = `All Transaction Report - ${cashbookData.period}\n\n`;
      csvContent += `Customer Transactions\n`;
      csvContent += `Category,Amount\n`;
      csvContent += `Total Receivable,${transactionData.customers.totalReceivable}\n`;
      csvContent += `Total Received,${transactionData.customers.totalReceived}\n`;
      csvContent += `Pending Amount,${transactionData.customers.pending}\n`;
      csvContent += `Total Customers,${transactionData.customers.count}\n\n`;
      csvContent += `Supplier Transactions\n`;
      csvContent += `Category,Amount\n`;
      csvContent += `Total Payable,${transactionData.suppliers.totalPayable}\n`;
      csvContent += `Total Paid,${transactionData.suppliers.totalPaid}\n`;
      csvContent += `Pending Amount,${transactionData.suppliers.pending}\n`;
      csvContent += `Total Suppliers,${transactionData.suppliers.count}\n`;
    }

    // Create blob and download as CSV (Excel compatible)
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${reportType.replace(/ /g, '_')}_${new Date().toISOString().split('T')[0]}.csv`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
  };

  const breadcrumbItems = [
    { icon: <HomeIcon />, label: 'Home', path: '/dashboard', active: false },
    { icon: <FileText />, label: 'Reports', path: '/reports', active: true }
  ];

  return (
    <div className="reports-container">
      <div className='relative'>
        <BreadCrumb items={breadcrumbItems} showUser={true} />
      </div>
      {/* Page Header */}
      <div className="reports-header">
        <div className="header-title">
          <h1>Reports</h1>
          <p>Download and view your business reports with detailed analytics</p>
        </div>
      </div>

      {/* Report Tabs */}
      <div className="report-tabs">
        <button
          className={`report-tab ${activeTab === 'cashbook' ? 'active' : ''}`}
          onClick={() => setActiveTab('cashbook')}
        >
          <BookOpen size={18} />
          Cashbook Report
        </button>
        <button
          className={`report-tab ${activeTab === 'transaction' ? 'active' : ''}`}
          onClick={() => setActiveTab('transaction')}
        >
          <FileText size={18} />
          All Transaction Report
        </button>
      </div>

      {/* Cashbook Report Section */}
      {activeTab === 'cashbook' && (
        <div className="report-section">
          <div className="section-card">
            <div className="card-header">
              <div className="header-left">
                <div className="icon-wrapper blue">
                  <BookOpen size={24} />
                </div>
                <div className="header-info">
                  <h2>Cashbook Report</h2>
                  <p>Complete record of all cash transactions</p>
                </div>
              </div>
              <div className="header-actions">
                <button
                  className={`chart-toggle-btn ${showCashbookCharts ? 'active' : ''}`}
                  onClick={() => setShowCashbookCharts(!showCashbookCharts)}
                >
                  <BarChart3 size={16} />
                  {showCashbookCharts ? 'Hide Charts' : 'Show Charts'}
                </button>
                <select
                  className="date-select"
                  value={cashbookDateRange}
                  onChange={(e) => setCashbookDateRange(e.target.value)}
                >
                  <option>Today</option>
                  <option>Yesterday</option>
                  <option>This Week</option>
                  <option>This Month</option>
                  <option>Last Month</option>
                  <option>Custom Range</option>
                </select>
              </div>
            </div>

            <div className="card-body">
              <div className="summary-grid">
                <div className="summary-item green">
                  <div className="summary-label">Total Money In</div>
                  <div className="summary-value">₹{cashbookData.totalIn.toLocaleString()}</div>
                </div>
                <div className="summary-item red">
                  <div className="summary-label">Total Money Out</div>
                  <div className="summary-value">₹{cashbookData.totalOut.toLocaleString()}</div>
                </div>
                <div className="summary-item blue">
                  <div className="summary-label">Net Balance</div>
                  <div className="summary-value">₹{cashbookData.netBalance.toLocaleString()}</div>
                </div>
                <div className="summary-item grey">
                  <div className="summary-label">Total Transactions</div>
                  <div className="summary-value">{cashbookData.transactions}</div>
                </div>
              </div>

              {/* Charts Section */}
              {showCashbookCharts && (
                <div className="charts-section">
                  <div className="chart-container">
                    <div className="chart-header">
                      <BarChart3 size={20} />
                      <h3>Weekly Money Flow</h3>
                    </div>
                    <ResponsiveContainer width="100%" height={280}>
                      <BarChart data={cashbookChartData}>
                        <CartesianGrid strokeDasharray="3 3" stroke="#F0F0F0" vertical={false} />
                        <XAxis
                          dataKey="name"
                          axisLine={false}
                          tickLine={false}
                          tick={{ fill: '#6B7280', fontSize: 12 }}
                        />
                        <YAxis
                          axisLine={false}
                          tickLine={false}
                          tick={{ fill: '#6B7280', fontSize: 12 }}
                          tickFormatter={(value) => `₹${value}`}
                        />
                        <Tooltip
                          contentStyle={{
                            borderRadius: '8px',
                            border: '1px solid #E5E7EB',
                            fontSize: '13px'
                          }}
                        />
                        <Legend iconType="circle" />
                        <Bar dataKey="moneyIn" fill="#10B981" radius={[8, 8, 0, 0]} name="Money In" />
                        <Bar dataKey="moneyOut" fill="#EF4444" radius={[8, 8, 0, 0]} name="Money Out" />
                      </BarChart>
                    </ResponsiveContainer>
                  </div>

                  <div className="chart-container">
                    <div className="chart-header">
                      <PieChartIcon size={20} />
                      <h3>Money Distribution</h3>
                    </div>
                    <ResponsiveContainer width="100%" height={280}>
                      <PieChart>
                        <Pie
                          data={cashbookPieData}
                          cx="50%"
                          cy="50%"
                          labelLine={false}
                          label={({ cx, cy, midAngle, outerRadius, percent }) => {
                            const RADIAN = Math.PI / 180;
                            const radius = outerRadius * 0.6;
                            const x = cx + radius * Math.cos(-midAngle * RADIAN);
                            const y = cy + radius * Math.sin(-midAngle * RADIAN);
                            return (
                              <text x={x} y={y} fill="white" textAnchor="middle" dominantBaseline="central" fontSize="14" fontWeight="bold">
                                {`${(percent * 100).toFixed(0)}%`}
                              </text>
                            );
                          }}
                          outerRadius={90}
                          fill="#8884d8"
                          dataKey="value"
                        >
                          {cashbookPieData.map((entry, index) => (
                            <Cell key={`cell-${index}`} fill={entry.color} />
                          ))}
                        </Pie>
                        <Tooltip
                          contentStyle={{
                            borderRadius: '8px',
                            border: '1px solid #E5E7EB',
                            fontSize: '13px'
                          }}
                        />
                      </PieChart>
                    </ResponsiveContainer>
                    <div className='PoiChartChartMain'>
                      {cashbookPieData.map((entry, index) => (
                        <div key={index} className='PoiChartChart'>
                          <div className='indicationOfColor' style={{ backgroundColor: entry.color }}></div>
                          <div className='indicationOfValue'>
                            <div>{entry.name}</div>
                            <p>₹{entry.value.toLocaleString()}</p>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              )}

              <div className="download-actions">
                <button
                  className="download-btn pdf"
                  onClick={() => handleDownloadPDF('Cashbook Report')}
                >
                  <Download size={18} />
                  <div>Download PDF</div>
                </button>
                <button
                  className="download-btn excel"
                  onClick={() => handleDownloadExcel('Cashbook Report')}
                >
                  <FileSpreadsheet size={18} />
                  <div>Download Excel</div>
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* All Transaction Report Section */}
      {activeTab === 'transaction' && (
        <div className="report-section">
          <div className="section-card">
            <div className="card-header">
              <div className="header-left">
                <div className="icon-wrapper orange">
                  <FileText size={24} />
                </div>
                <div className="header-info">
                  <h2>All Transaction Report</h2>
                  <p>Comprehensive report of customer and supplier transactions</p>
                </div>
              </div>
              <div className="header-actions">
                <button
                  className={`chart-toggle-btn ${showTransactionCharts ? 'active' : ''}`}
                  onClick={() => setShowTransactionCharts(!showTransactionCharts)}
                >
                  <BarChart3 size={16} />
                  {showTransactionCharts ? 'Hide Charts' : 'Show Charts'}
                </button>
                <select
                  className="type-select"
                  value={transactionType}
                  onChange={(e) => setTransactionType(e.target.value)}
                >
                  <option>All</option>
                  <option>Customers Only</option>
                  <option>Suppliers Only</option>
                </select>
                <select
                  className="date-select"
                  value={transactionDateRange}
                  onChange={(e) => setTransactionDateRange(e.target.value)}
                >
                  <option>Today</option>
                  <option>Yesterday</option>
                  <option>This Week</option>
                  <option>This Month</option>
                  <option>Last Month</option>
                  <option>Custom Range</option>
                </select>
              </div>
            </div>

            <div className="card-body">
              {/* Customer Transactions */}
              {(transactionType === 'All' || transactionType === 'Customers Only') && (
                <div className="transaction-group">
                  <div className="group-header">
                    <Users size={20} />
                    <h3>Customer Transactions</h3>
                    <span className="count-badge">{transactionData.customers.count} Customers</span>
                  </div>
                  <div className="summary-grid">
                    <div className="summary-item green">
                      <div className="summary-label">Total Receivable</div>
                      <div className="summary-value">₹{transactionData.customers.totalReceivable.toLocaleString()}</div>
                    </div>
                    <div className="summary-item blue">
                      <div className="summary-label">Total Received</div>
                      <div className="summary-value">₹{transactionData.customers.totalReceived.toLocaleString()}</div>
                    </div>
                    <div className="summary-item orange">
                      <div className="summary-label">Pending Amount</div>
                      <div className="summary-value">₹{transactionData.customers.pending.toLocaleString()}</div>
                    </div>
                  </div>
                </div>
              )}

              {/* Supplier Transactions */}
              {(transactionType === 'All' || transactionType === 'Suppliers Only') && (
                <div className="transaction-group">
                  <div className="group-header">
                    <Package size={20} />
                    <h3>Supplier Transactions</h3>
                    <span className="count-badge">{transactionData.suppliers.count} Suppliers</span>
                  </div>
                  <div className="summary-grid">
                    <div className="summary-item red">
                      <div className="summary-label">Total Payable</div>
                      <div className="summary-value">₹{transactionData.suppliers.totalPayable.toLocaleString()}</div>
                    </div>
                    <div className="summary-item blue">
                      <div className="summary-label">Total Paid</div>
                      <div className="summary-value">₹{transactionData.suppliers.totalPaid.toLocaleString()}</div>
                    </div>
                    <div className="summary-item orange">
                      <div className="summary-label">Pending Amount</div>
                      <div className="summary-value">₹{transactionData.suppliers.pending.toLocaleString()}</div>
                    </div>
                  </div>
                </div>
              )}

              {/* Charts Section */}
              {showTransactionCharts && (
                <div className="charts-section">
                  <div className="chart-container">
                    <div className="chart-header">
                      <BarChart3 size={20} />
                      <h3>Transaction Comparison</h3>
                    </div>
                    <ResponsiveContainer width="100%" height={300}>
                      <BarChart data={transactionChartData}>
                        <CartesianGrid strokeDasharray="3 3" stroke="#F0F0F0" vertical={false} />
                        <XAxis
                          dataKey="name"
                          axisLine={false}
                          tickLine={false}
                          tick={{ fill: '#6B7280', fontSize: 12 }}
                        />
                        <YAxis
                          axisLine={false}
                          tickLine={false}
                          tick={{ fill: '#6B7280', fontSize: 12 }}
                          tickFormatter={(value) => `₹${value}`}
                        />
                        <Tooltip
                          contentStyle={{
                            borderRadius: '8px',
                            border: '1px solid #E5E7EB',
                            fontSize: '13px'
                          }}
                        />
                        <Legend iconType="circle" />
                        <Bar dataKey="receivable" fill="#3B82F6" radius={[8, 8, 0, 0]} name="Total Amount" />
                        <Bar dataKey="received" fill="#10B981" radius={[8, 8, 0, 0]} name="Paid/Received" />
                        <Bar dataKey="pending" fill="#F59E0B" radius={[8, 8, 0, 0]} name="Pending" />
                      </BarChart>
                    </ResponsiveContainer>
                  </div>

                  <div className="chart-container">
                    <div className="chart-header">
                      <PieChartIcon size={20} />
                      <h3>Amount Distribution</h3>
                    </div>
                    <ResponsiveContainer width="100%" height={300}>
                      <PieChart>
                        <Pie
                          data={transactionPieData}
                          cx="50%"
                          cy="50%"
                          labelLine={false}
                          label={({ cx, cy, midAngle, outerRadius, percent }) => {
                            const RADIAN = Math.PI / 180;
                            const radius = outerRadius * 0.6;
                            const x = cx + radius * Math.cos(-midAngle * RADIAN);
                            const y = cy + radius * Math.sin(-midAngle * RADIAN);
                            return (
                              <text x={x} y={y} fill="white" textAnchor="middle" dominantBaseline="central" fontSize="14" fontWeight="bold">
                                {`${(percent * 100).toFixed(0)}%`}
                              </text>
                            );
                          }}
                          outerRadius={95}
                          fill="#8884d8"
                          dataKey="value"
                        >
                          {transactionPieData.map((entry, index) => (
                            <Cell key={`cell-${index}`} fill={entry.color} />
                          ))}
                        </Pie>
                        <Tooltip
                          contentStyle={{
                            borderRadius: '8px',
                            border: '1px solid #E5E7EB',
                            fontSize: '13px'
                          }}
                        />
                      </PieChart>
                    </ResponsiveContainer>
                    <div className='PoiChartChartMain'>
                      {transactionPieData.map((entry, index) => (
                        <div key={index} className='PoiChartChart'>
                          <div className='indicationOfColor' style={{ backgroundColor: entry.color }}></div>
                          <div className='indicationOfValue'>
                            <div>{entry.name}</div>
                            <p>₹{entry.value.toLocaleString()}</p>
                          </div>
                        </div>
                      ))}
                    </div>

                  </div>
                </div>
              )}

              <div className="download-actions">
                <button
                  className="download-btn pdf"
                  onClick={() => handleDownloadPDF('All Transaction Report')}
                >
                  <Download size={18} />
                  Download PDF
                </button>
                <button
                  className="download-btn excel"
                  onClick={() => handleDownloadExcel('All Transaction Report')}
                >
                  <FileSpreadsheet size={18} />
                  Download Excel
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
