import { useEffect, useState, FormEvent } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { Save, X, AlertCircle, Loader } from 'lucide-react';
import {
  useFinanceStore,
  EXPENSE_CATEGORIES,
  EXPENSE_STATUSES,
  Expense,
} from '../../store/finance';

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

export default function ExpenseEdit() {
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const expenseId = id ? parseInt(id, 10) : NaN;

  const { currentExpense, fetchExpense, updateExpense, loading, error } = useFinanceStore();

  const [form, setForm] = useState<Partial<Expense>>({});
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);

  useEffect(() => {
    if (!Number.isFinite(expenseId)) {
      navigate('/finance/expenses');
      return;
    }
    if (!currentExpense || currentExpense.id !== expenseId) {
      fetchExpense(expenseId).then((row) => {
        if (!row) navigate('/finance/expenses');
      });
    } else {
      setForm({
        category: currentExpense.category,
        subcategory: currentExpense.subcategory || '',
        description: currentExpense.description,
        amount: currentExpense.amount,
        expense_date: (currentExpense.expense_date || '').slice(0, 10),
        vendor: currentExpense.vendor || '',
        invoice_number: currentExpense.invoice_number || '',
        payment_method: currentExpense.payment_method || '',
        status: currentExpense.status,
      });
    }
  }, [expenseId, currentExpense, fetchExpense, navigate]);

  const onChange = (k: keyof Expense) => (e: any) => {
    const v = e?.target?.value;
    setForm((f) => ({ ...f, [k]: v }));
  };

  const onSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setSubmitError(null);

    if (!form.description?.trim()) {
      setSubmitError('Description is required');
      return;
    }
    if (!form.amount || Number(form.amount) <= 0) {
      setSubmitError('Amount must be greater than 0');
      return;
    }
    if (!form.category) {
      setSubmitError('Category is required');
      return;
    }

    setSubmitting(true);
    const updated = await updateExpense(expenseId, {
      ...form,
      amount: Number(form.amount),
    });
    setSubmitting(false);
    if (updated) {
      navigate('/finance/expenses');
    } else {
      setSubmitError('Failed to save expense. Please try again.');
    }
  };

  if (loading && !currentExpense) {
    return (
      <div className="flex flex-col justify-center items-center h-[60vh] gap-4 text-text-muted">
        <Loader className="animate-spin" size={28} />
        <p>Loading expense…</p>
      </div>
    );
  }

  if (error && !currentExpense) {
    return (
      <div className="flex flex-col justify-center items-center h-[60vh] gap-4">
        <AlertCircle size={48} className="text-red-500" />
        <p className="text-text-muted font-medium">{error}</p>
        <button
          onClick={() => navigate('/finance/expenses')}
          className="px-4 py-2 bg-primary text-white rounded-xl"
        >
          Back to list
        </button>
      </div>
    );
  }

  return (
    <div className="space-y-6 animate-in fade-in duration-300 pb-10 max-w-3xl">
      <div className="flex items-center gap-3">
        <button
          onClick={() => navigate('/finance/expenses')}
          className="p-2 rounded-xl hover:bg-muted text-text-muted"
          aria-label="Back"
        >
          <X size={20} />
        </button>
        <div>
          <h1 className="text-3xl font-extrabold text-text tracking-tight">
            Edit Expense #{expenseId}
          </h1>
          <p className="text-text-muted text-sm">Update an existing expense record.</p>
        </div>
      </div>

      {submitError && (
        <div className="bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-900 rounded-2xl p-4 flex items-center gap-3 text-red-700 dark:text-red-300">
          <AlertCircle size={18} />
          <span className="text-sm">{submitError}</span>
        </div>
      )}

      <form onSubmit={onSubmit} className="bg-card rounded-2xl border border-border p-6 shadow-sm space-y-5">
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <Field label="Category" required>
            <select
              value={form.category}
              onChange={onChange('category')}
              className="form-input"
              required
            >
              {EXPENSE_CATEGORIES.map((c) => (
                <option key={c.value} value={c.value}>{c.label}</option>
              ))}
            </select>
          </Field>

          <Field label="Subcategory">
            <input
              type="text"
              value={form.subcategory || ''}
              onChange={onChange('subcategory')}
              className="form-input"
            />
          </Field>

          <Field label="Description" required className="sm:col-span-2">
            <input
              type="text"
              value={form.description || ''}
              onChange={onChange('description')}
              className="form-input"
              required
            />
          </Field>

          <Field label="Amount (USD)" required>
            <input
              type="number"
              step="0.01"
              min="0.01"
              value={form.amount || ''}
              onChange={onChange('amount')}
              className="form-input"
              required
            />
          </Field>

          <Field label="Date" required>
            <input
              type="date"
              value={(form.expense_date || '').slice(0, 10)}
              max={todayISO()}
              onChange={onChange('expense_date')}
              className="form-input"
              required
            />
          </Field>

          <Field label="Vendor">
            <input
              type="text"
              value={form.vendor || ''}
              onChange={onChange('vendor')}
              className="form-input"
            />
          </Field>

          <Field label="Invoice number">
            <input
              type="text"
              value={form.invoice_number || ''}
              onChange={onChange('invoice_number')}
              className="form-input"
            />
          </Field>

          <Field label="Payment method">
            <input
              type="text"
              value={form.payment_method || ''}
              onChange={onChange('payment_method')}
              className="form-input"
            />
          </Field>

          <Field label="Status">
            <select
              value={form.status || 'pending'}
              onChange={onChange('status')}
              className="form-input"
            >
              {EXPENSE_STATUSES.map((s) => (
                <option key={s.value} value={s.value}>{s.label}</option>
              ))}
            </select>
          </Field>
        </div>

        <div className="pt-2 flex items-center justify-end gap-2 border-t border-border">
          <button
            type="button"
            onClick={() => navigate('/finance/expenses')}
            className="px-4 py-2.5 rounded-xl border border-border text-text text-sm font-bold hover:bg-muted transition-all"
            disabled={submitting}
          >
            Cancel
          </button>
          <button
            type="submit"
            disabled={submitting}
            className="flex items-center gap-2 px-5 py-2.5 rounded-xl bg-primary text-white text-sm font-bold hover:bg-primary-dark transition-all shadow-lg shadow-blue-900/10 disabled:opacity-60"
          >
            <Save size={16} />
            <span>{submitting ? 'Saving…' : 'Save Changes'}</span>
          </button>
        </div>
      </form>

      <style>{`
        .form-input {
          width: 100%;
          padding: 0.625rem 0.875rem;
          background: rgba(148, 163, 184, 0.08);
          border: 1px solid rgb(226 232 240);
          border-radius: 0.75rem;
          font-size: 0.875rem;
          color: rgb(15 23 42);
          outline: none;
          transition: all 0.15s ease;
        }
        .form-input:focus {
          border-color: #0047AB;
          box-shadow: 0 0 0 3px rgba(0, 71, 171, 0.15);
          background: transparent;
        }
      `}</style>
    </div>
  );
}

function Field({ label, children, required, className = '' }: any) {
  return (
    <label className={`block space-y-1 ${className}`}>
      <span className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted">
        {label} {required && <span className="text-red-500">*</span>}
      </span>
      {children}
    </label>
  );
}
