import React, { useState, useEffect } from 'react';
import { CheckCircle2, XCircle, Clock, Eye } from 'lucide-react';
import { toast } from 'react-toastify';
import approvalService, { FinancialApproval, ApprovalStatus } from '../../features/payments/services/approvalService';
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 ApprovalManagementPage: React.FC = () => {
  const { formatCurrency } = useFormatCurrency();
  const [loading, setLoading] = useState(true);
  const [approvals, setApprovals] = useState<FinancialApproval[]>([]);
  const [selectedApproval, setSelectedApproval] = useState<FinancialApproval | null>(null);
  const [filter, setFilter] = useState<ApprovalStatus | 'all'>('all');
  const [responseNotes, setResponseNotes] = useState('');

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

  const fetchApprovals = async () => {
    try {
      setLoading(true);
      const params: { status?: string } = {};
      if (filter !== 'all') params.status = filter;
      const response = await approvalService.getApprovals(params);
      setApprovals(response.data || []);
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to load approvals');
    } finally {
      setLoading(false);
    }
  };

  const handleRespond = async (approvalId: number, status: 'approved' | 'rejected') => {
    if (!responseNotes.trim() && status === 'rejected') {
      toast.error('Please provide notes for rejection');
      return;
    }
    try {
      await approvalService.respondToApproval(approvalId, {
        status,
        response_notes: responseNotes || undefined
      });
      toast.success(`Approval ${status} successfully`);
      setSelectedApproval(null);
      setResponseNotes('');
      fetchApprovals();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to respond to approval');
    }
  };

  const getStatusColor = (status: ApprovalStatus) => {
    switch (status) {
      case 'approved':
        return 'bg-green-100 text-green-800 border-green-200';
      case 'rejected':
        return 'bg-red-100 text-red-800 border-red-200';
      case 'pending':
        return 'bg-yellow-100 text-yellow-800 border-yellow-200';
      default:
        return 'bg-gray-100 text-gray-800 border-gray-200';
    }
  };

  const getActionTypeLabel = (type: string) => {
    return type.split('_').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
  };

  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">
      {/* 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">
            Approval Management
          </h1>
        </div>
        <p className="text-slate-600 text-sm sm:text-base md:text-lg font-light">
          Review and respond to financial approval requests
        </p>
      </div>

      {/* Filters */}
      <div className="flex gap-2 mb-6 flex-wrap">
        <button
          onClick={() => setFilter('all')}
          className={`px-4 py-2 rounded-lg font-semibold transition-colors ${
            filter === 'all' ? 'bg-emerald-500 text-white' : 'bg-white text-slate-700 hover:bg-slate-100'
          }`}
        >
          All
        </button>
        <button
          onClick={() => setFilter('pending')}
          className={`px-4 py-2 rounded-lg font-semibold transition-colors ${
            filter === 'pending' ? 'bg-emerald-500 text-white' : 'bg-white text-slate-700 hover:bg-slate-100'
          }`}
        >
          <Clock className="inline w-4 h-4 mr-2" />
          Pending
        </button>
        <button
          onClick={() => setFilter('approved')}
          className={`px-4 py-2 rounded-lg font-semibold transition-colors ${
            filter === 'approved' ? 'bg-emerald-500 text-white' : 'bg-white text-slate-700 hover:bg-slate-100'
          }`}
        >
          <CheckCircle2 className="inline w-4 h-4 mr-2" />
          Approved
        </button>
        <button
          onClick={() => setFilter('rejected')}
          className={`px-4 py-2 rounded-lg font-semibold transition-colors ${
            filter === 'rejected' ? 'bg-emerald-500 text-white' : 'bg-white text-slate-700 hover:bg-slate-100'
          }`}
        >
          <XCircle className="inline w-4 h-4 mr-2" />
          Rejected
        </button>
      </div>

      {/* Approvals List */}
      <div className="bg-white rounded-xl shadow-lg p-6">
        {approvals.length === 0 ? (
          <EmptyState title="No Approvals" description="Approval requests will appear here" />
        ) : (
          <div className="space-y-4">
            {approvals.map((approval) => (
              <div
                key={approval.id}
                className="border border-slate-200 rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer"
                onClick={() => setSelectedApproval(approval)}
              >
                <div className="flex justify-between items-start">
                  <div className="flex-1">
                    <div className="flex items-center gap-3 mb-2">
                      <h3 className="font-bold text-lg">{getActionTypeLabel(approval.action_type)}</h3>
                      <span className={`px-3 py-1 rounded-full text-xs font-semibold border ${getStatusColor(approval.status)}`}>
                        {approval.status.charAt(0).toUpperCase() + approval.status.slice(1)}
                      </span>
                    </div>
                    <p className="text-slate-600 mb-2">{approval.action_description}</p>
                    <div className="flex flex-wrap gap-4 text-sm text-slate-500">
                      <span>Requested by: {approval.requested_by_email || `User #${approval.requested_by}`}</span>
                      <span>•</span>
                      <span>{formatDate(approval.requested_at)}</span>
                      {approval.amount && (
                        <>
                          <span>•</span>
                          <span className="font-semibold text-slate-700">{formatCurrency(approval.amount)}</span>
                        </>
                      )}
                    </div>
                    {approval.request_reason && (
                      <p className="mt-2 text-sm text-slate-600 bg-slate-50 p-2 rounded">
                        <strong>Reason:</strong> {approval.request_reason}
                      </p>
                    )}
                  </div>
                  {approval.status === 'pending' && (
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        setSelectedApproval(approval);
                      }}
                      className="px-4 py-2 bg-emerald-500 text-white rounded-lg hover:bg-emerald-600 flex items-center gap-2"
                    >
                      <Eye className="w-4 h-4" />
                      Review
                    </button>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Approval Detail Modal */}
      {selectedApproval && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
            <div className="p-6 border-b border-slate-200">
              <div className="flex justify-between items-start">
                <div>
                  <h2 className="text-2xl font-bold mb-2">{getActionTypeLabel(selectedApproval.action_type)}</h2>
                  <span className={`px-3 py-1 rounded-full text-xs font-semibold border ${getStatusColor(selectedApproval.status)}`}>
                    {selectedApproval.status.charAt(0).toUpperCase() + selectedApproval.status.slice(1)}
                  </span>
                </div>
                <button
                  onClick={() => {
                    setSelectedApproval(null);
                    setResponseNotes('');
                  }}
                  className="text-slate-500 hover:text-slate-700"
                >
                  <XCircle className="w-6 h-6" />
                </button>
              </div>
            </div>
            <div className="p-6 space-y-4">
              <div>
                <h3 className="font-semibold mb-2">Description</h3>
                <p className="text-slate-600">{selectedApproval.action_description}</p>
              </div>
              {selectedApproval.request_reason && (
                <div>
                  <h3 className="font-semibold mb-2">Request Reason</h3>
                  <p className="text-slate-600">{selectedApproval.request_reason}</p>
                </div>
              )}
              {selectedApproval.amount && (
                <div>
                  <h3 className="font-semibold mb-2">Amount</h3>
                  <p className="text-lg font-bold text-emerald-600">{formatCurrency(selectedApproval.amount)}</p>
                </div>
              )}
              {selectedApproval.previous_value && (
                <div>
                  <h3 className="font-semibold mb-2">Previous Value</h3>
                  <pre className="bg-slate-50 p-3 rounded text-sm overflow-x-auto">
                    {JSON.stringify(selectedApproval.previous_value, null, 2)}
                  </pre>
                </div>
              )}
              {selectedApproval.new_value && (
                <div>
                  <h3 className="font-semibold mb-2">New Value</h3>
                  <pre className="bg-slate-50 p-3 rounded text-sm overflow-x-auto">
                    {JSON.stringify(selectedApproval.new_value, null, 2)}
                  </pre>
                </div>
              )}
              {selectedApproval.status === 'pending' && (
                <div>
                  <h3 className="font-semibold mb-2">Response Notes</h3>
                  <textarea
                    value={responseNotes}
                    onChange={(e) => setResponseNotes(e.target.value)}
                    className="w-full p-3 border border-slate-300 rounded-lg"
                    rows={4}
                    placeholder="Add notes for your response..."
                  />
                  <div className="flex gap-3 mt-4">
                    <button
                      onClick={() => handleRespond(selectedApproval.id, 'approved')}
                      className="flex-1 px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 flex items-center justify-center gap-2"
                    >
                      <CheckCircle2 className="w-4 h-4" />
                      Approve
                    </button>
                    <button
                      onClick={() => handleRespond(selectedApproval.id, 'rejected')}
                      className="flex-1 px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 flex items-center justify-center gap-2"
                    >
                      <XCircle className="w-4 h-4" />
                      Reject
                    </button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ApprovalManagementPage;

