import React, { useState, FormEvent } from 'react';
import { createPortal } from 'react-dom';
import {
  Receipt, Plus, X, AlertCircle, Loader2, DollarSign,
  Tag, Calendar, CreditCard, Building2, FileText, CheckCircle2,
} from 'lucide-react';
import {
  useFinanceStore,
  EXPENSE_CATEGORIES,
  Expense,
} from '../store/finance';

interface CreateExpenseModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess?: () => void;
}

const todayISO = () => new Date().toISOString().slice(0, 10);

export const CreateExpenseModal: React.FC<CreateExpenseModalProps> = ({
  isOpen,
  onClose,
  onSuccess,
}) => {
  const { createExpense, fetchExpenseSummary, fetchExpenses } = useFinanceStore();

  const [form, setForm] = useState({
    description: '',
    amount: '',
    category: 'administrative',
    subcategory: '',
    vendor: '',
    invoice_number: '',
    expense_date: todayISO(),
    payment_method: 'bank_transfer',
    status: 'pending',
  });

  const [submitting, setSubmitting] = useState(false);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);

  if (!isOpen) return null;

  const handleChange = (field: string, value: string) => {
    setForm((prev) => ({ ...prev, [field]: value }));
  };

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setErrorMsg(null);

    const trimmedDesc = form.description.trim();
    if (!trimmedDesc) {
      setErrorMsg('Description is required.');
      return;
    }

    const numAmount = Number(form.amount);
    if (isNaN(numAmount) || numAmount <= 0) {
      setErrorMsg('Please enter a valid positive amount.');
      return;
    }

    if (!form.category) {
      setErrorMsg('Please select an expense category.');
      return;
    }

    try {
      setSubmitting(true);
      await createExpense({
        description: trimmedDesc,
        amount: numAmount,
        category: form.category,
        subcategory: form.subcategory.trim() || undefined,
        vendor: form.vendor.trim() || undefined,
        invoice_number: form.invoice_number.trim() || undefined,
        expense_date: form.expense_date || todayISO(),
        payment_method: form.payment_method || undefined,
        status: (form.status as any) || 'pending',
      });

      // Refresh list & summary metrics
      await Promise.all([
        fetchExpenses(),
        fetchExpenseSummary(),
      ]);

      setSubmitting(false);
      if (onSuccess) onSuccess();
      onClose();
    } catch (err: any) {
      setSubmitting(false);
      setErrorMsg(err?.message || err?.response?.data?.error || 'Failed to create expense. Please try again.');
    }
  };

  return createPortal(
    <div
      className="fixed inset-0 bg-[#002147]/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4 overflow-y-auto"
      onClick={onClose}
    >
      {/* Modal Panel Container per modals.md */}
      <div
        className="bg-card rounded-[2.5rem] w-full max-w-xl max-h-[90vh] flex flex-col shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 border border-border relative my-auto"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header Block with Background Watermark */}
        <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden flex-shrink-0">
          {/* Watermark Icon per modals.md */}
          <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12 pointer-events-none text-text">
            <Receipt size={180} />
          </div>

          <div className="relative z-10">
            <h2 className="text-2xl font-black text-text tracking-tight font-heading">Log New Expense</h2>
            <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">
              Record Operational Spend & Vendor Invoices
            </p>
          </div>

          <button
            type="button"
            onClick={onClose}
            className="relative z-10 w-10 h-10 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 hover:border-rose-500/20 hover:bg-rose-50/5 transition-all cursor-pointer"
            aria-label="Close modal"
          >
            <X size={20} />
          </button>
        </div>

        {/* Scrollable Form Body */}
        <form
          id="create-expense-form"
          onSubmit={handleSubmit}
          className="p-10 space-y-6 overflow-y-auto flex-1 custom-scrollbar"
        >
          {errorMsg && (
            <div className="p-4 rounded-2xl bg-rose-50 dark:bg-rose-950/30 border border-rose-200 dark:border-rose-900 text-rose-700 dark:text-rose-300 flex items-center gap-3 text-xs font-bold animate-in slide-in-from-top-2">
              <AlertCircle size={18} className="shrink-0" />
              <span>{errorMsg}</span>
            </div>
          )}

          {/* Description */}
          <div className="space-y-2">
            <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted px-1 flex items-center gap-1.5">
              <FileText size={12} className="text-primary" />
              <span>Description <span className="text-rose-500">*</span></span>
            </label>
            <input
              type="text"
              required
              placeholder="e.g. Science Lab Chemicals & Equipment Purchase"
              value={form.description}
              onChange={(e) => handleChange('description', e.target.value)}
              className="w-full px-5 py-3.5 bg-muted/50 border border-border rounded-2xl text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all text-text"
            />
          </div>

          {/* Amount & Date Grid */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
            <div className="space-y-2">
              <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted px-1 flex items-center gap-1.5">
                <DollarSign size={12} className="text-primary" />
                <span>Amount ($) <span className="text-rose-500">*</span></span>
              </label>
              <input
                type="number"
                step="0.01"
                min="0.01"
                required
                placeholder="0.00"
                value={form.amount}
                onChange={(e) => handleChange('amount', e.target.value)}
                className="w-full px-5 py-3.5 bg-muted/50 border border-border rounded-2xl text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all text-text"
              />
            </div>

            <div className="space-y-2">
              <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted px-1 flex items-center gap-1.5">
                <Calendar size={12} className="text-primary" />
                <span>Expense Date <span className="text-rose-500">*</span></span>
              </label>
              <input
                type="date"
                required
                value={form.expense_date}
                onChange={(e) => handleChange('expense_date', e.target.value)}
                className="w-full px-5 py-3.5 bg-muted/50 border border-border rounded-2xl text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all text-text"
              />
            </div>
          </div>

          {/* Category & Subcategory */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
            <div className="space-y-2">
              <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted px-1 flex items-center gap-1.5">
                <Tag size={12} className="text-primary" />
                <span>Category <span className="text-rose-500">*</span></span>
              </label>
              <select
                value={form.category}
                onChange={(e) => handleChange('category', e.target.value)}
                className="w-full px-5 py-3.5 bg-muted/50 border border-border rounded-2xl text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all text-text cursor-pointer"
              >
                {EXPENSE_CATEGORIES.map((cat) => (
                  <option key={cat.value} value={cat.value}>
                    {cat.label}
                  </option>
                ))}
              </select>
            </div>

            <div className="space-y-2">
              <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted px-1 flex items-center gap-1.5">
                <Tag size={12} className="text-text-muted" />
                <span>Subcategory (Optional)</span>
              </label>
              <input
                type="text"
                placeholder="e.g. Chemistry Supplies"
                value={form.subcategory}
                onChange={(e) => handleChange('subcategory', e.target.value)}
                className="w-full px-5 py-3.5 bg-muted/50 border border-border rounded-2xl text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all text-text"
              />
            </div>
          </div>

          {/* Vendor & Invoice */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
            <div className="space-y-2">
              <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted px-1 flex items-center gap-1.5">
                <Building2 size={12} className="text-primary" />
                <span>Vendor / Supplier</span>
              </label>
              <input
                type="text"
                placeholder="e.g. Harare Scientific Ltd"
                value={form.vendor}
                onChange={(e) => handleChange('vendor', e.target.value)}
                className="w-full px-5 py-3.5 bg-muted/50 border border-border rounded-2xl text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all text-text"
              />
            </div>

            <div className="space-y-2">
              <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted px-1 flex items-center gap-1.5">
                <FileText size={12} className="text-text-muted" />
                <span>Invoice / Receipt #</span>
              </label>
              <input
                type="text"
                placeholder="e.g. INV-2026-089"
                value={form.invoice_number}
                onChange={(e) => handleChange('invoice_number', e.target.value)}
                className="w-full px-5 py-3.5 bg-muted/50 border border-border rounded-2xl text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all text-text"
              />
            </div>
          </div>

          {/* Payment Method & Initial Status */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
            <div className="space-y-2">
              <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted px-1 flex items-center gap-1.5">
                <CreditCard size={12} className="text-primary" />
                <span>Payment Method</span>
              </label>
              <select
                value={form.payment_method}
                onChange={(e) => handleChange('payment_method', e.target.value)}
                className="w-full px-5 py-3.5 bg-muted/50 border border-border rounded-2xl text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all text-text cursor-pointer"
              >
                <option value="bank_transfer">Bank Transfer</option>
                <option value="cash">Cash</option>
                <option value="paynow">PayNow / Mobile Money</option>
                <option value="cheque">Cheque</option>
                <option value="other">Other</option>
              </select>
            </div>

            <div className="space-y-2">
              <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted px-1 flex items-center gap-1.5">
                <CheckCircle2 size={12} className="text-primary" />
                <span>Status</span>
              </label>
              <select
                value={form.status}
                onChange={(e) => handleChange('status', e.target.value)}
                className="w-full px-5 py-3.5 bg-muted/50 border border-border rounded-2xl text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary transition-all text-text cursor-pointer"
              >
                <option value="pending">Pending Approval</option>
                <option value="approved">Approved</option>
                <option value="paid">Paid</option>
              </select>
            </div>
          </div>
        </form>

        {/* Footer Actions */}
        <div className="px-10 py-6 bg-muted/30 border-t border-border flex items-center justify-end gap-3 shrink-0">
          <button
            type="button"
            onClick={onClose}
            disabled={submitting}
            className="px-6 py-3 rounded-2xl border border-border bg-card text-text hover:bg-muted font-bold text-xs uppercase tracking-wider transition-colors cursor-pointer"
          >
            Cancel
          </button>
          <button
            type="submit"
            form="create-expense-form"
            disabled={submitting}
            className="inline-flex items-center gap-2 px-6 py-3 rounded-2xl bg-primary hover:bg-primary/90 text-white font-black text-xs uppercase tracking-wider transition-all shadow-lg shadow-primary/20 active:scale-95 cursor-pointer disabled:opacity-50"
          >
            {submitting ? (
              <>
                <Loader2 size={16} className="animate-spin" />
                <span>Creating…</span>
              </>
            ) : (
              <>
                <Plus size={16} strokeWidth={2.5} />
                <span>Log Expense</span>
              </>
            )}
          </button>
        </div>
      </div>
    </div>,
    document.body
  );
};

export default CreateExpenseModal;
