
import React, { useState } from 'react';
import { StatCard } from '../../components/StatCard';
import { Modal } from '../../components/Modal';
import { useToast } from '../../context/ToastContext';
import { useData } from '../../context/DataContext';
import { Invoice } from '../../types';

export const Finance: React.FC = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [paymentModalOpen, setPaymentModalOpen] = useState(false);
  const [selectedInvoice, setSelectedInvoice] = useState<Invoice | null>(null);
  const [previewInvoice, setPreviewInvoice] = useState<Invoice | null>(null); // For printing
  const { invoices, addInvoice, tenants, clinicType } = useData();
  const { addToast } = useToast();
  
  // Get clinic info for invoice header
  const tenant = tenants.find(t => t.clinicType === clinicType);

  const totalIncome = invoices.reduce((sum, inv) => inv.status === 'paid' ? sum + inv.amount : sum, 0);
  const pendingAmount = invoices.reduce((sum, inv) => inv.status === 'pending' ? sum + inv.amount : sum, 0);

  const handleCreateInvoice = (e: React.FormEvent) => {
    e.preventDefault();
    const form = e.target as HTMLFormElement;
    const patientName = (form.elements.namedItem('patientName') as HTMLInputElement).value;
    const service = (form.elements.namedItem('service') as HTMLSelectElement).value;
    const amount = (form.elements.namedItem('amount') as HTMLInputElement).value;
    const date = (form.elements.namedItem('date') as HTMLInputElement).value;
    const status = (form.querySelector('input[name="status"]:checked') as HTMLInputElement).value as 'paid' | 'pending';

    if (patientName && amount) {
        const newInvoice: Invoice = {
            id: `INV-${Date.now().toString().slice(-4)}`,
            patientName,
            service,
            date,
            amount: parseFloat(amount),
            status: status
        };
        addInvoice(newInvoice);
        addToast('تم إصدار الفاتورة بنجاح', 'success');
        setIsModalOpen(false);
    }
  };

  const handlePrint = (invoice: Invoice) => {
      setPreviewInvoice(invoice);
  };

  const printPreview = () => {
      window.print();
  };

  const openPaymentModal = (invoice: Invoice) => {
      setSelectedInvoice(invoice);
      setPaymentModalOpen(true);
  };

  const processPayment = () => {
      addToast('جاري معالجة الدفع...', 'info');
      setTimeout(() => {
          addToast('تمت عملية الدفع بنجاح! (محاكاة)', 'success');
          setPaymentModalOpen(false);
          // In real app, would update invoice status here
      }, 1500);
  };

  return (
    <div className="space-y-6">
      <header className="flex justify-between items-center mb-6">
        <div>
          <h2 className="text-2xl font-bold text-gray-800">المحاسبة</h2>
          <p className="text-gray-500">الفواتير والمدفوعات</p>
        </div>
        <button 
          onClick={() => setIsModalOpen(true)}
          className="bg-primary hover:bg-primary-dark text-white px-5 py-2.5 rounded-xl shadow-md transition-colors flex items-center gap-2"
        >
          <i className="fas fa-file-invoice-dollar"></i>
          <span>فاتورة جديدة</span>
        </button>
      </header>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <StatCard title="الدخل المحقق" value={`${totalIncome} $`} icon="fa-wallet" color="success" trend="+15% هذا الشهر" />
        <StatCard title="مبالغ معلقة" value={`${pendingAmount} $`} icon="fa-clock" color="warning" />
        <StatCard title="فواتير متأخرة" value="1" icon="fa-exclamation-triangle" color="danger" />
      </div>

      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
        <div className="p-6 border-b border-gray-100">
          <h3 className="text-lg font-bold text-gray-800">سجل الفواتير</h3>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-4 text-right text-sm font-semibold text-gray-600">رقم الفاتورة</th>
                <th className="px-6 py-4 text-right text-sm font-semibold text-gray-600">المريض</th>
                <th className="px-6 py-4 text-right text-sm font-semibold text-gray-600">الخدمة</th>
                <th className="px-6 py-4 text-right text-sm font-semibold text-gray-600">التاريخ</th>
                <th className="px-6 py-4 text-right text-sm font-semibold text-gray-600">المبلغ</th>
                <th className="px-6 py-4 text-right text-sm font-semibold text-gray-600">الحالة</th>
                <th className="px-6 py-4 text-center text-sm font-semibold text-gray-600">إجراءات</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {invoices.map((inv) => (
                <tr key={inv.id} className="hover:bg-gray-50 transition-colors">
                  <td className="px-6 py-4 font-mono text-sm text-gray-600">{inv.id}</td>
                  <td className="px-6 py-4 font-medium text-gray-800">{inv.patientName}</td>
                  <td className="px-6 py-4 text-gray-600">{inv.service}</td>
                  <td className="px-6 py-4 text-gray-600">{inv.date}</td>
                  <td className="px-6 py-4 font-bold text-gray-800">{inv.amount} $</td>
                  <td className="px-6 py-4">
                    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                      inv.status === 'paid' ? 'bg-green-100 text-green-800' :
                      inv.status === 'pending' ? 'bg-yellow-100 text-yellow-800' :
                      'bg-red-100 text-red-800'
                    }`}>
                      {inv.status === 'paid' ? 'مدفوع' : inv.status === 'pending' ? 'معلق' : 'متأخر'}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-center flex justify-center gap-2">
                    <button 
                        onClick={() => handlePrint(inv)}
                        className="text-gray-400 hover:text-primary transition-colors" 
                        title="طباعة"
                    >
                      <i className="fas fa-print"></i>
                    </button>
                    {inv.status === 'pending' && (
                        <button 
                            onClick={() => openPaymentModal(inv)}
                            className="text-gray-400 hover:text-green-500 transition-colors" 
                            title="دفع إلكتروني"
                        >
                            <i className="fas fa-credit-card"></i>
                        </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* New Invoice Modal */}
      <Modal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)} title="إنشاء فاتورة جديدة">
        <form className="space-y-4" onSubmit={handleCreateInvoice}>
            <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">اسم المريض</label>
                <input name="patientName" type="text" placeholder="بحث عن مريض..." className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary bg-white text-gray-900" required />
            </div>
            <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">نوع الخدمة</label>
                <select name="service" className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary bg-white text-gray-900">
                    <option value="كشف عام">كشف عام</option>
                    <option value="تحاليل مخبرية">تحاليل مخبرية</option>
                    <option value="أشعة">أشعة</option>
                    <option value="جراحة صغرى">جراحة صغرى</option>
                    <option value="خدمة أخرى">خدمة أخرى</option>
                </select>
            </div>
            <div className="grid grid-cols-2 gap-4">
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">المبلغ ($)</label>
                    <input name="amount" type="number" className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary bg-white text-gray-900" required />
                </div>
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">تاريخ الفاتورة</label>
                    <input name="date" type="date" defaultValue={new Date().toISOString().split('T')[0]} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary bg-white text-gray-900" />
                </div>
            </div>
            <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">حالة الدفع</label>
                <div className="flex gap-4 mt-1">
                    <label className="flex items-center gap-2 cursor-pointer">
                        <input type="radio" name="status" value="paid" className="text-primary focus:ring-primary" defaultChecked />
                        <span className="text-sm text-gray-900">مدفوع بالكامل</span>
                    </label>
                    <label className="flex items-center gap-2 cursor-pointer">
                        <input type="radio" name="status" value="pending" className="text-primary focus:ring-primary" />
                        <span className="text-sm text-gray-900">معلق (آجل)</span>
                    </label>
                </div>
            </div>
            <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">ملاحظات</label>
                <textarea rows={2} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary bg-white text-gray-900"></textarea>
            </div>
            <button type="submit" className="w-full bg-primary text-white py-2.5 rounded-xl font-bold hover:bg-primary-dark transition-colors">
                إصدار الفاتورة
            </button>
        </form>
      </Modal>

      {/* Payment Modal */}
      {selectedInvoice && (
          <Modal isOpen={paymentModalOpen} onClose={() => setPaymentModalOpen(false)} title="دفع الفاتورة إلكترونياً">
              <div className="space-y-4">
                  <div className="bg-blue-50 p-4 rounded-xl flex justify-between items-center border border-blue-100">
                      <span className="text-gray-700">المبلغ المستحق:</span>
                      <span className="text-xl font-bold text-primary">${selectedInvoice.amount}</span>
                  </div>
                  
                  <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">اختر وسيلة الدفع</label>
                      <div className="grid grid-cols-2 gap-4">
                          <button className="border border-gray-200 rounded-xl p-3 flex flex-col items-center hover:border-primary hover:bg-blue-50 transition-all focus:ring-2 ring-primary">
                              <i className="fab fa-cc-visa text-3xl text-blue-800 mb-1"></i>
                              <span className="text-sm font-medium text-gray-900">Credit Card</span>
                          </button>
                          <button className="border border-gray-200 rounded-xl p-3 flex flex-col items-center hover:border-blue-400 hover:bg-blue-50 transition-all focus:ring-2 ring-blue-400">
                              <i className="fab fa-paypal text-3xl text-blue-600 mb-1"></i>
                              <span className="text-sm font-medium text-gray-900">PayPal</span>
                          </button>
                      </div>
                  </div>

                  <div className="border-t border-gray-100 pt-4">
                       <button onClick={processPayment} className="w-full bg-green-600 hover:bg-green-700 text-white py-3 rounded-xl font-bold shadow-lg transition-colors">
                           تأكيد الدفع
                       </button>
                  </div>
              </div>
          </Modal>
      )}

      {/* Invoice Print Preview Modal */}
      {previewInvoice && (
          <Modal isOpen={!!previewInvoice} onClose={() => setPreviewInvoice(null)} title="معاينة الفاتورة">
              <div className="print-area bg-white p-8 border border-gray-200 shadow-sm mb-4 text-right" id="invoice-print">
                  {/* Header - Hides Email explicitly */}
                  <div className="border-b-2 border-gray-800 pb-4 mb-6 flex justify-between items-start">
                      <div>
                          <h1 className="text-2xl font-bold text-gray-900">{tenant?.clinicName || 'اسم العيادة'}</h1>
                          <p className="text-gray-600 text-sm mt-1">{tenant?.clinicType} Clinic</p>
                      </div>
                      <div className="text-left text-sm text-gray-500">
                          {/* Note: Email is intentionally excluded here as requested */}
                          <p className="font-bold text-gray-800">{tenant?.phone}</p>
                          <p>{tenant?.email ? '' : ''}</p> {/* Explicitly empty logic if needed to prove removal, basically just don't render it */}
                          <p>المملكة العربية السعودية</p>
                      </div>
                  </div>

                  {/* Invoice Meta */}
                  <div className="flex justify-between items-center bg-gray-50 p-4 rounded-lg border border-gray-200 mb-8">
                      <div>
                          <p className="text-xs text-gray-500 uppercase font-bold">فاتورة رقم</p>
                          <p className="text-lg font-mono font-bold text-gray-800">{previewInvoice.id}</p>
                      </div>
                      <div className="text-left">
                          <p className="text-xs text-gray-500 uppercase font-bold">التاريخ</p>
                          <p className="text-lg font-medium text-gray-800">{previewInvoice.date}</p>
                      </div>
                  </div>

                  {/* Patient Info */}
                  <div className="mb-8">
                      <p className="text-sm text-gray-500 mb-1">فاتورة إلى:</p>
                      <h3 className="text-xl font-bold text-gray-900">{previewInvoice.patientName}</h3>
                  </div>

                  {/* Line Items */}
                  <div className="mb-8">
                      <table className="w-full text-sm">
                          <thead>
                              <tr className="border-b-2 border-gray-200 text-gray-600">
                                  <th className="text-right py-3">الوصف / الخدمة</th>
                                  <th className="text-left py-3">المبلغ</th>
                              </tr>
                          </thead>
                          <tbody>
                              <tr className="border-b border-gray-100">
                                  <td className="py-4 font-medium text-gray-800">{previewInvoice.service}</td>
                                  <td className="py-4 text-left font-bold">{previewInvoice.amount} $</td>
                              </tr>
                          </tbody>
                      </table>
                  </div>

                  {/* Totals */}
                  <div className="flex justify-end">
                      <div className="w-1/2">
                          <div className="flex justify-between py-2 border-b border-gray-100">
                              <span className="text-gray-600">المجموع الفرعي:</span>
                              <span className="font-medium">{previewInvoice.amount} $</span>
                          </div>
                          <div className="flex justify-between py-2 border-b border-gray-100">
                              <span className="text-gray-600">الضريبة (0%):</span>
                              <span className="font-medium">0.00 $</span>
                          </div>
                          <div className="flex justify-between py-3 text-lg font-bold text-gray-900">
                              <span>الإجمالي:</span>
                              <span>{previewInvoice.amount} $</span>
                          </div>
                      </div>
                  </div>

                  {/* Status Stamp */}
                  <div className="mt-8 text-center">
                      <span className={`inline-block border-2 px-4 py-1 rounded uppercase font-bold tracking-widest opacity-50 transform -rotate-12 ${previewInvoice.status === 'paid' ? 'border-green-600 text-green-600' : 'border-red-600 text-red-600'}`}>
                          {previewInvoice.status === 'paid' ? 'PAID' : 'PENDING'}
                      </span>
                  </div>

                  {/* Footer */}
                  <div className="mt-12 pt-8 border-t border-gray-200 text-center text-xs text-gray-400">
                      <p>شكراً لثقتكم بنا. نتمنى لكم دوام الصحة والعافية.</p>
                  </div>
              </div>
              
              <button onClick={printPreview} className="w-full bg-gray-800 text-white py-3 rounded-xl font-bold flex items-center justify-center gap-2 hover:bg-gray-900 shadow-lg">
                  <i className="fas fa-print"></i> طباعة الفاتورة
              </button>
              
              <style>{`
                  @media print {
                      body * { visibility: hidden; }
                      .print-area, .print-area * { visibility: visible; }
                      .print-area { position: absolute; left: 0; top: 0; width: 100%; margin: 0; padding: 20px; border: none; shadow: none; }
                      .modal-close, button { display: none; }
                  }
              `}</style>
          </Modal>
      )}
    </div>
  );
};
