import React, { useState, useEffect } from 'react';
import { Download, Filter } from 'lucide-react';
import { toast } from 'react-toastify';
import financialAuditService, { FinancialAuditRecord } from '../../features/payments/services/financialAuditService';
import Loading from '../../shared/components/Loading';
import EmptyState from '../../shared/components/EmptyState';
import { formatDate } from '../../shared/utils/format';
import { useFormatCurrency } from '../../features/payments/hooks/useFormatCurrency';

const AuditTrailPage: React.FC = () => {
  const { formatCurrency } = useFormatCurrency();
  const [loading, setLoading] = useState(true);
  const [records, setRecords] = useState<FinancialAuditRecord[]>([]);
  const [pagination, setPagination] = useState<unknown>(null);
  const [filters, setFilters] = useState({
    action_type: '',
    user_id: '',
    start_date: '',
    end_date: '',
    payment_id: '',
    invoice_id: '',
    booking_id: '',
    page: 1,
    limit: 50,
  });
  const [showFilters, setShowFilters] = useState(false);

  useEffect(() => {
    fetchAuditTrail();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filters.page, filters.action_type, filters.user_id, filters.start_date, filters.end_date]);

  const fetchAuditTrail = async () => {
    try {
      setLoading(true);
      const response = await financialAuditService.getAuditTrail(filters);
      if (response.status === 'success' && response.data) {
        setRecords(response.data.audit_trail || []);
        setPagination(response.data.pagination);
      }
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to load audit trail');
    } finally {
      setLoading(false);
    }
  };

  const handleExport = async (format: 'csv' | 'json') => {
    try {
      const blob = await financialAuditService.exportAuditTrail(filters, format);
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `audit-trail-${new Date().toISOString().split('T')[0]}.${format}`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      toast.success('Audit trail exported successfully');
    } catch (error: unknown) {
      toast.error('Failed to export audit trail');
    }
  };

  const getActionTypeColor = (type: string) => {
    if (type.includes('create') || type.includes('approve')) return 'bg-green-100 text-green-800';
    if (type.includes('update') || type.includes('modify')) return 'bg-blue-100 text-blue-800';
    if (type.includes('delete') || type.includes('reject')) return 'bg-red-100 text-red-800';
    if (type.includes('export')) return 'bg-purple-100 text-purple-800';
    return 'bg-gray-100 text-gray-800';
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-50 px-3 sm:px-4 md:px-6 lg:px-8 py-6 sm:py-8 md:py-10">
      {/* Header */}
      <div className="mb-6 sm:mb-8 md:mb-10">
        <div className="flex items-center gap-2 sm:gap-3 mb-2 sm:mb-3">
          <div className="h-1 w-12 sm:w-16 md:w-20 bg-gradient-to-r from-emerald-400 via-green-500 to-emerald-600 rounded-full"></div>
          <h1 className="text-2xl sm:text-3xl md:text-4xl font-bold bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 bg-clip-text text-transparent">
            Financial Audit Trail
          </h1>
        </div>
        <p className="text-slate-600 text-sm sm:text-base md:text-lg font-light">
          Complete audit log of all financial actions
        </p>
      </div>

      {/* Actions */}
      <div className="bg-white rounded-xl shadow-lg p-4 mb-6 flex justify-between items-center flex-wrap gap-4">
        <div className="flex gap-2">
          <button
            onClick={() => setShowFilters(!showFilters)}
            className="px-4 py-2 bg-slate-100 text-slate-700 rounded-lg hover:bg-slate-200 flex items-center gap-2"
          >
            <Filter className="w-4 h-4" />
            Filters
          </button>
        </div>
        <div className="flex gap-2">
          <button
            onClick={() => handleExport('csv')}
            className="px-4 py-2 bg-emerald-500 text-white rounded-lg hover:bg-emerald-600 flex items-center gap-2"
          >
            <Download className="w-4 h-4" />
            Export CSV
          </button>
          <button
            onClick={() => handleExport('json')}
            className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 flex items-center gap-2"
          >
            <Download className="w-4 h-4" />
            Export JSON
          </button>
        </div>
      </div>

      {/* Filters */}
      {showFilters && (
        <div className="bg-white rounded-xl shadow-lg p-4 mb-6">
          <div className="grid md:grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-semibold mb-2">Action Type</label>
              <input
                type="text"
                value={filters.action_type}
                onChange={(e) => setFilters({ ...filters, action_type: e.target.value, page: 1 })}
                className="w-full px-4 py-2 border border-slate-300 rounded-lg"
                placeholder="Filter by action type"
              />
            </div>
            <div>
              <label className="block text-sm font-semibold mb-2">Start Date</label>
              <input
                type="date"
                value={filters.start_date}
                onChange={(e) => setFilters({ ...filters, start_date: e.target.value, page: 1 })}
                className="w-full px-4 py-2 border border-slate-300 rounded-lg"
              />
            </div>
            <div>
              <label className="block text-sm font-semibold mb-2">End Date</label>
              <input
                type="date"
                value={filters.end_date}
                onChange={(e) => setFilters({ ...filters, end_date: e.target.value, page: 1 })}
                className="w-full px-4 py-2 border border-slate-300 rounded-lg"
              />
            </div>
            <div>
              <label className="block text-sm font-semibold mb-2">Payment ID</label>
              <input
                type="number"
                value={filters.payment_id}
                onChange={(e) => setFilters({ ...filters, payment_id: e.target.value, page: 1 })}
                className="w-full px-4 py-2 border border-slate-300 rounded-lg"
                placeholder="Filter by payment ID"
              />
            </div>
            <div>
              <label className="block text-sm font-semibold mb-2">Invoice ID</label>
              <input
                type="number"
                value={filters.invoice_id}
                onChange={(e) => setFilters({ ...filters, invoice_id: e.target.value, page: 1 })}
                className="w-full px-4 py-2 border border-slate-300 rounded-lg"
                placeholder="Filter by invoice ID"
              />
            </div>
            <div>
              <label className="block text-sm font-semibold mb-2">User ID</label>
              <input
                type="number"
                value={filters.user_id}
                onChange={(e) => setFilters({ ...filters, user_id: e.target.value, page: 1 })}
                className="w-full px-4 py-2 border border-slate-300 rounded-lg"
                placeholder="Filter by user ID"
              />
            </div>
          </div>
        </div>
      )}

      {/* Audit Trail */}
      <div className="bg-white rounded-xl shadow-lg p-6">
        {loading && records.length === 0 ? (
          <Loading text="Loading audit trail..." />
        ) : records.length === 0 ? (
          <EmptyState title="No Audit Records" description="Audit trail records will appear here" />
        ) : (
          <>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-slate-200">
                    <th className="text-left p-3">Date</th>
                    <th className="text-left p-3">Action Type</th>
                    <th className="text-left p-3">Description</th>
                    <th className="text-left p-3">Performed By</th>
                    <th className="text-right p-3">Amount</th>
                    <th className="text-left p-3">Related IDs</th>
                  </tr>
                </thead>
                <tbody>
                  {records.map((record) => (
                    <tr key={record.id} className="border-b border-slate-100 hover:bg-slate-50">
                      <td className="p-3 text-sm">{formatDate(record.created_at)}</td>
                      <td className="p-3">
                        <span className={`px-2 py-1 rounded-full text-xs font-semibold ${getActionTypeColor(record.action_type)}`}>
                          {record.action_type.replace(/_/g, ' ')}
                        </span>
                      </td>
                      <td className="p-3">{record.action_description}</td>
                      <td className="p-3 text-sm">{record.performed_by_email || `User #${record.performed_by}`}</td>
                      <td className="p-3 text-right">
                        {record.amount ? formatCurrency(record.amount) : '-'}
                      </td>
                      <td className="p-3 text-sm text-slate-500">
                        {record.payment_id && `Payment: ${record.payment_id} `}
                        {record.invoice_id && `Invoice: ${record.invoice_id} `}
                        {record.booking_id && `Booking: ${record.booking_id}`}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            {pagination && (
              <div className="flex justify-between items-center mt-4 pt-4 border-t border-slate-200">
                <div className="text-sm text-slate-600">
                  Showing {((pagination.page - 1) * pagination.limit) + 1} to {Math.min(pagination.page * pagination.limit, pagination.total)} of {pagination.total} records
                </div>
                <div className="flex gap-2">
                  <button
                    onClick={() => setFilters({ ...filters, page: filters.page - 1 })}
                    disabled={pagination.page === 1}
                    className="px-4 py-2 bg-slate-100 text-slate-700 rounded-lg hover:bg-slate-200 disabled:opacity-50"
                  >
                    Previous
                  </button>
                  <button
                    onClick={() => setFilters({ ...filters, page: filters.page + 1 })}
                    disabled={pagination.page >= pagination.total_pages}
                    className="px-4 py-2 bg-slate-100 text-slate-700 rounded-lg hover:bg-slate-200 disabled:opacity-50"
                  >
                    Next
                  </button>
                </div>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
};

export default AuditTrailPage;

