import React, { useState, useEffect } from 'react';
import { Play } from 'lucide-react';
import { toast } from 'react-toastify';
import reconciliationService, { ReconciliationException, ExceptionStatus } from '../../features/payments/services/reconciliationService';
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 ReconciliationPage: React.FC = () => {
  const { formatCurrency } = useFormatCurrency();
  const [loading, setLoading] = useState(false);
  const [exceptions, setExceptions] = useState<ReconciliationException[]>([]);
  const [stats, setStats] = useState<Record<string, unknown> | null>(null);
  const [selectedException, setSelectedException] = useState<ReconciliationException | null>(null);
  const [filter, setFilter] = useState<ExceptionStatus | 'all'>('all');
  const [comment, setComment] = useState('');
  const [resolutionNotes, setResolutionNotes] = useState('');

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

  const fetchExceptions = async () => {
    try {
      setLoading(true);
      const params: { limit: number; status?: ExceptionStatus } = { limit: 50 };
      if (filter !== 'all') params.status = filter;
      const response = await reconciliationService.getExceptions(params);
      setExceptions(response.data.exceptions || []);
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to load exceptions');
    } finally {
      setLoading(false);
    }
  };

  const fetchStats = async () => {
    try {
      const response = await reconciliationService.getExceptionStats();
      setStats(response.data);
    } catch (_error) {
      // Silently fail
    }
  };

  const handleRunReconciliation = async () => {
    try {
      setLoading(true);
      const response = await reconciliationService.runReconciliation();
      toast.success(`Reconciliation completed. ${response.data.exceptions_created} new exceptions created.`);
      fetchExceptions();
      fetchStats();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to run reconciliation');
    } finally {
      setLoading(false);
    }
  };

  const handleResolve = async (exceptionId: number) => {
    if (!resolutionNotes.trim()) {
      toast.error('Please provide resolution notes');
      return;
    }
    try {
      await reconciliationService.resolveException(exceptionId, resolutionNotes);
      toast.success('Exception resolved successfully');
      setSelectedException(null);
      setResolutionNotes('');
      fetchExceptions();
      fetchStats();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to resolve exception');
    }
  };

  const handleAddComment = async (exceptionId: number) => {
    if (!comment.trim()) {
      toast.error('Please enter a comment');
      return;
    }
    try {
      await reconciliationService.addComment(exceptionId, comment);
      toast.success('Comment added successfully');
      setComment('');
      fetchExceptions();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to add comment');
    }
  };

  const getSeverityColor = (severity: string) => {
    switch (severity) {
      case 'critical':
        return 'bg-red-100 text-red-800 border-red-200';
      case 'high':
        return 'bg-orange-100 text-orange-800 border-orange-200';
      case 'medium':
        return 'bg-yellow-100 text-yellow-800 border-yellow-200';
      default:
        return 'bg-blue-100 text-blue-800 border-blue-200';
    }
  };

  const getStatusColor = (status: ExceptionStatus) => {
    switch (status) {
      case 'resolved':
        return 'bg-green-100 text-green-800 border-green-200';
      case 'closed':
        return 'bg-gray-100 text-gray-800 border-gray-200';
      case 'in_review':
        return 'bg-blue-100 text-blue-800 border-blue-200';
      case 'assigned':
        return 'bg-purple-100 text-purple-800 border-purple-200';
      default:
        return 'bg-yellow-100 text-yellow-800 border-yellow-200';
    }
  };

  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">
            Reconciliation
          </h1>
        </div>
        <p className="text-slate-600 text-sm sm:text-base md:text-lg font-light">
          Manage payment and invoice reconciliation exceptions
        </p>
      </div>

      {/* Stats */}
      {stats && (
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
          <div className="bg-white rounded-xl shadow-lg p-4 border-l-4 border-blue-500">
            <p className="text-sm text-slate-600 mb-1">Total Exceptions</p>
            <p className="text-2xl font-bold">{stats.total}</p>
          </div>
          <div className="bg-white rounded-xl shadow-lg p-4 border-l-4 border-yellow-500">
            <p className="text-sm text-slate-600 mb-1">Open</p>
            <p className="text-2xl font-bold">{stats.by_status?.open || 0}</p>
          </div>
          <div className="bg-white rounded-xl shadow-lg p-4 border-l-4 border-green-500">
            <p className="text-sm text-slate-600 mb-1">Resolved</p>
            <p className="text-2xl font-bold">{stats.by_status?.resolved || 0}</p>
          </div>
          <div className="bg-white rounded-xl shadow-lg p-4 border-l-4 border-red-500">
            <p className="text-sm text-slate-600 mb-1">Critical</p>
            <p className="text-2xl font-bold">{stats.by_severity?.critical || 0}</p>
          </div>
        </div>
      )}

      {/* Actions */}
      <div className="bg-white rounded-xl shadow-lg p-4 mb-6 flex justify-between items-center">
        <div className="flex gap-2 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-slate-100 text-slate-700 hover:bg-slate-200'
            }`}
          >
            All
          </button>
          <button
            onClick={() => setFilter('open')}
            className={`px-4 py-2 rounded-lg font-semibold transition-colors ${
              filter === 'open' ? 'bg-emerald-500 text-white' : 'bg-slate-100 text-slate-700 hover:bg-slate-200'
            }`}
          >
            Open
          </button>
          <button
            onClick={() => setFilter('resolved')}
            className={`px-4 py-2 rounded-lg font-semibold transition-colors ${
              filter === 'resolved' ? 'bg-emerald-500 text-white' : 'bg-slate-100 text-slate-700 hover:bg-slate-200'
            }`}
          >
            Resolved
          </button>
        </div>
        <button
          onClick={handleRunReconciliation}
          disabled={loading}
          className="px-4 py-2 bg-emerald-500 text-white rounded-lg hover:bg-emerald-600 flex items-center gap-2 disabled:opacity-50"
        >
          <Play className="w-4 h-4" />
          Run Reconciliation
        </button>
      </div>

      {/* Exceptions List */}
      <div className="bg-white rounded-xl shadow-lg p-6">
        {loading && exceptions.length === 0 ? (
          <Loading text="Loading exceptions..." />
        ) : exceptions.length === 0 ? (
          <EmptyState title="No Exceptions" description="Reconciliation exceptions will appear here" />
        ) : (
          <div className="space-y-4">
            {exceptions.map((exception) => (
              <div
                key={exception.id}
                className="border border-slate-200 rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer"
                onClick={() => setSelectedException(exception)}
              >
                <div className="flex justify-between items-start">
                  <div className="flex-1">
                    <div className="flex items-center gap-3 mb-2">
                      <AlertTriangle className={`w-5 h-5 ${
                        exception.severity === 'critical' ? 'text-red-500' :
                        exception.severity === 'high' ? 'text-orange-500' :
                        'text-yellow-500'
                      }`} />
                      <h3 className="font-bold text-lg">{exception.exception_type.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())}</h3>
                      <span className={`px-3 py-1 rounded-full text-xs font-semibold border ${getSeverityColor(exception.severity)}`}>
                        {exception.severity}
                      </span>
                      <span className={`px-3 py-1 rounded-full text-xs font-semibold border ${getStatusColor(exception.status)}`}>
                        {exception.status}
                      </span>
                    </div>
                    <p className="text-slate-600 mb-2">{exception.description}</p>
                    <div className="flex flex-wrap gap-4 text-sm text-slate-500">
                      {exception.expected_amount && (
                        <span>Expected: {formatCurrency(exception.expected_amount)}</span>
                      )}
                      {exception.actual_amount && (
                        <span>Actual: {formatCurrency(exception.actual_amount)}</span>
                      )}
                      {exception.difference && (
                        <span className="font-semibold text-red-600">
                          Difference: {formatCurrency(Math.abs(exception.difference))}
                        </span>
                      )}
                      <span>•</span>
                      <span>{formatDate(exception.created_at)}</span>
                    </div>
                  </div>
                  {exception.status === 'open' && (
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        setSelectedException(exception);
                      }}
                      className="px-4 py-2 bg-emerald-500 text-white rounded-lg hover:bg-emerald-600"
                    >
                      Review
                    </button>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Exception Detail Modal */}
      {selectedException && (
        <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">
                    {selectedException.exception_type.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())}
                  </h2>
                  <div className="flex gap-2">
                    <span className={`px-3 py-1 rounded-full text-xs font-semibold border ${getSeverityColor(selectedException.severity)}`}>
                      {selectedException.severity}
                    </span>
                    <span className={`px-3 py-1 rounded-full text-xs font-semibold border ${getStatusColor(selectedException.status)}`}>
                      {selectedException.status}
                    </span>
                  </div>
                </div>
                <button
                  onClick={() => {
                    setSelectedException(null);
                    setComment('');
                    setResolutionNotes('');
                  }}
                  className="text-slate-500 hover:text-slate-700"
                >
                  <AlertTriangle 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">{selectedException.description}</p>
              </div>
              {selectedException.expected_amount && (
                <div>
                  <h3 className="font-semibold mb-2">Expected Amount</h3>
                  <p className="text-lg font-bold">{formatCurrency(selectedException.expected_amount)}</p>
                </div>
              )}
              {selectedException.actual_amount && (
                <div>
                  <h3 className="font-semibold mb-2">Actual Amount</h3>
                  <p className="text-lg font-bold">{formatCurrency(selectedException.actual_amount)}</p>
                </div>
              )}
              {selectedException.difference && (
                <div>
                  <h3 className="font-semibold mb-2">Difference</h3>
                  <p className="text-lg font-bold text-red-600">{formatCurrency(Math.abs(selectedException.difference))}</p>
                </div>
              )}
              {selectedException.comments && selectedException.comments.length > 0 && (
                <div>
                  <h3 className="font-semibold mb-2">Comments</h3>
                  <div className="space-y-2">
                    {selectedException.comments.map((c, idx) => (
                      <div key={idx} className="bg-slate-50 p-3 rounded">
                        <p className="text-sm text-slate-600">{c.comment}</p>
                        <p className="text-xs text-slate-400 mt-1">{formatDate(c.created_at)}</p>
                      </div>
                    ))}
                  </div>
                </div>
              )}
              <div>
                <h3 className="font-semibold mb-2">Add Comment</h3>
                <textarea
                  value={comment}
                  onChange={(e) => setComment(e.target.value)}
                  className="w-full p-3 border border-slate-300 rounded-lg"
                  rows={3}
                  placeholder="Add a comment..."
                />
                <button
                  onClick={() => handleAddComment(selectedException.id)}
                  className="mt-2 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
                >
                  Add Comment
                </button>
              </div>
              {selectedException.status === 'open' && (
                <div>
                  <h3 className="font-semibold mb-2">Resolution Notes</h3>
                  <textarea
                    value={resolutionNotes}
                    onChange={(e) => setResolutionNotes(e.target.value)}
                    className="w-full p-3 border border-slate-300 rounded-lg"
                    rows={4}
                    placeholder="Enter resolution notes..."
                  />
                  <button
                    onClick={() => handleResolve(selectedException.id)}
                    className="mt-2 px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600"
                  >
                    Resolve Exception
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ReconciliationPage;

