import React, { useEffect, useState } from 'react';
import { CheckCircle, XCircle, Clock, Eye } from 'lucide-react';
import approvalService, { ApprovalRequest } from '../../features/system/services/approvalService';
import { toast } from 'react-toastify';
import Loading from '../../shared/components/Loading';
import Pagination from '../../shared/components/Pagination';
import { formatDate } from '../../shared/utils/format';

const ApprovalManagementPage: React.FC = () => {
  const [approvals, setApprovals] = useState<ApprovalRequest[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedApproval, setSelectedApproval] = useState<ApprovalRequest | null>(null);
  const [showDetails, setShowDetails] = useState(false);
  const [processingId, setProcessingId] = useState<number | null>(null);
  const [filters, setFilters] = useState({
    approval_type: '',
  });
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const itemsPerPage = 20;

  useEffect(() => {
    fetchApprovals();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filters, currentPage]);

  const fetchApprovals = async () => {
    try {
      setLoading(true);
      const response = await approvalService.getPendingApprovals({
        ...filters,
        page: currentPage,
        limit: itemsPerPage,
      });
      setApprovals(response.data.approvals || []);
      if (response.data.pagination) {
        setTotalPages(response.data.pagination.totalPages || 1);
      }
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to load approvals');
    } finally {
      setLoading(false);
    }
  };

  const handleApprove = async (id: number) => {
    try {
      setProcessingId(id);
      await approvalService.approveRequest(id);
      toast.success('Approval request approved');
      fetchApprovals();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to approve request');
    } finally {
      setProcessingId(null);
    }
  };

  const handleReject = async (id: number) => {
    const reason = prompt('Enter rejection reason:');
    if (!reason) return;

    try {
      setProcessingId(id);
      await approvalService.rejectRequest(id, reason);
      toast.success('Approval request rejected');
      fetchApprovals();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to reject request');
    } finally {
      setProcessingId(null);
    }
  };

  const _handleCancel = async (id: number) => {
    if (!confirm('Are you sure you want to cancel this approval request?')) return;

    try {
      setProcessingId(id);
      await approvalService.cancelRequest(id);
      toast.success('Approval request cancelled');
      fetchApprovals();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to cancel request');
    } finally {
      setProcessingId(null);
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'approved':
        return <CheckCircle className="w-5 h-5 text-green-500" />;
      case 'rejected':
        return <XCircle className="w-5 h-5 text-red-500" />;
      default:
        return <Clock className="w-5 h-5 text-yellow-500" />;
    }
  };

  if (loading && approvals.length === 0) {
    return <Loading fullScreen text="Loading approvals..." />;
  }

  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">
      <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4 sm:gap-6 mb-6 sm:mb-8 md:mb-10 animate-fade-in">
        <div className="w-full lg:w-auto">
          <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-amber-400 via-orange-500 to-amber-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 tracking-tight">
              Approval Management
            </h1>
          </div>
          <p className="text-slate-600 mt-2 sm:mt-3 text-sm sm:text-base md:text-lg font-light">Review and manage pending approval requests</p>
        </div>
      </div>

      <div className="bg-white/90 backdrop-blur-md rounded-xl sm:rounded-2xl shadow-xl border border-slate-200/60 p-4 sm:p-5 md:p-6 animate-fade-in hover:shadow-2xl transition-all duration-300">
        <div className="flex flex-col sm:flex-row gap-3 sm:gap-4 mb-4 sm:mb-5 md:mb-6">
          <div className="flex-1">
            <select
              value={filters.approval_type}
              onChange={(e) => {
                setFilters({ ...filters, approval_type: e.target.value });
                setCurrentPage(1);
              }}
              className="w-full px-3 sm:px-4 py-2 sm:py-2.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md text-sm sm:text-base"
            >
              <option value="">All Types</option>
              <option value="invoice_update">Invoice Update</option>
              <option value="payment_refund">Payment Refund</option>
              <option value="invoice_mark_paid">Invoice Mark Paid</option>
              <option value="financial_adjustment">Financial Adjustment</option>
            </select>
          </div>
        </div>

        {approvals.length === 0 ? (
          <div className="text-center py-8 sm:py-12">
            <p className="text-slate-500 text-sm sm:text-base">No pending approvals</p>
          </div>
        ) : (
          <div className="space-y-3 sm:space-y-4">
            {approvals.map((approval) => (
              <div
                key={approval.id}
                className="bg-gradient-to-r from-slate-50 to-white border border-slate-200 rounded-lg sm:rounded-xl p-3 sm:p-4 hover:from-amber-50 hover:to-yellow-50 hover:border-amber-300 hover:shadow-lg transition-all duration-200"
              >
                <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 sm:gap-4">
                  <div className="flex-1 min-w-0">
                    <div className="flex flex-wrap items-center gap-2 sm:gap-3 mb-2">
                      {getStatusIcon(approval.status)}
                      <h3 className="font-semibold text-sm sm:text-base md:text-lg truncate">
                        {approval.approval_type.replace('_', ' ').toUpperCase()}
                      </h3>
                      <span className={`px-2 sm:px-3 py-1 rounded-full text-xs font-semibold border shadow-sm ${
                        approval.priority === 'urgent' ? 'bg-gradient-to-r from-red-50 to-rose-50 text-red-800 border-red-200' :
                        approval.priority === 'high' ? 'bg-gradient-to-r from-orange-50 to-amber-50 text-orange-800 border-orange-200' :
                        'bg-gradient-to-r from-blue-50 to-indigo-50 text-blue-800 border-blue-200'
                      }`}>
                        {approval.priority}
                      </span>
                    </div>
                    <p className="text-slate-600 text-xs sm:text-sm mb-1 sm:mb-2 truncate">
                      Resource: {approval.resource_type} #{approval.resource_id}
                    </p>
                    <p className="text-slate-500 text-xs">
                      Requested: {formatDate(approval.requested_at)}
                    </p>
                    {approval.notes && (
                      <p className="text-slate-600 text-xs sm:text-sm mt-2 line-clamp-2">{approval.notes}</p>
                    )}
                  </div>
                  <div className="flex gap-2 w-full sm:w-auto">
                    <button
                      onClick={() => {
                        setSelectedApproval(approval);
                        setShowDetails(true);
                      }}
                      className="p-2 sm:p-2.5 text-blue-600 hover:bg-blue-50 rounded-lg sm:rounded-xl transition-colors flex-shrink-0"
                    >
                      <Eye className="w-4 h-4 sm:w-5 sm:h-5" />
                    </button>
                    {approval.status === 'pending' && (
                      <>
                        <button
                          onClick={() => handleApprove(approval.id)}
                          disabled={processingId === approval.id}
                          className="flex-1 sm:flex-none px-3 sm:px-4 py-2 bg-gradient-to-r from-emerald-600 to-emerald-700 text-white rounded-lg sm:rounded-xl hover:from-emerald-700 hover:to-emerald-800 shadow-lg hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 text-xs sm:text-sm font-semibold"
                        >
                          Approve
                        </button>
                        <button
                          onClick={() => handleReject(approval.id)}
                          disabled={processingId === approval.id}
                          className="flex-1 sm:flex-none px-3 sm:px-4 py-2 bg-gradient-to-r from-red-600 to-red-700 text-white rounded-lg sm:rounded-xl hover:from-red-700 hover:to-red-800 shadow-lg hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 text-xs sm:text-sm font-semibold"
                        >
                          Reject
                        </button>
                      </>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}

        {totalPages > 1 && (
          <div className="mt-6">
            <Pagination
              currentPage={currentPage}
              totalPages={totalPages}
              onPageChange={setCurrentPage}
            />
          </div>
        )}
      </div>

      {showDetails && selectedApproval && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-3 sm:p-4">
          <div className="bg-white/95 backdrop-blur-md rounded-xl sm:rounded-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto p-4 sm:p-5 md:p-6 shadow-2xl border border-slate-200/60">
            <div className="flex justify-between items-center mb-4 sm:mb-5 md:mb-6">
              <h2 className="text-xl sm:text-2xl font-bold text-slate-900">Approval Details</h2>
              <button
                onClick={() => setShowDetails(false)}
                className="text-slate-500 hover:text-slate-700 p-2 hover:bg-slate-100 rounded-lg transition-colors"
              >
                ✕
              </button>
            </div>
            <div className="space-y-3 sm:space-y-4">
              <div>
                <label className="font-semibold text-sm sm:text-base text-slate-700 block mb-1">Type:</label>
                <p className="text-sm sm:text-base text-slate-900">{selectedApproval.approval_type}</p>
              </div>
              <div>
                <label className="font-semibold text-sm sm:text-base text-slate-700 block mb-1">Status:</label>
                <p className="text-sm sm:text-base text-slate-900">{selectedApproval.status}</p>
              </div>
              <div>
                <label className="font-semibold text-sm sm:text-base text-slate-700 block mb-1">Request Data:</label>
                <pre className="bg-slate-100 p-3 sm:p-4 rounded-lg sm:rounded-xl overflow-auto text-xs sm:text-sm border border-slate-200">
                  {JSON.stringify(selectedApproval.request_data, null, 2)}
                </pre>
              </div>
              {selectedApproval.current_data && (
                <div>
                  <label className="font-semibold text-sm sm:text-base text-slate-700 block mb-1">Current Data:</label>
                  <pre className="bg-slate-100 p-3 sm:p-4 rounded-lg sm:rounded-xl overflow-auto text-xs sm:text-sm border border-slate-200">
                    {JSON.stringify(selectedApproval.current_data, null, 2)}
                  </pre>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ApprovalManagementPage;

