/**
 * Payment Confirmation Modal
 * Allows users to submit manual payment confirmation details
 * Uploads proof of payment and submits to backend for admin approval
 */

import { useState } from 'react';
import { Modal } from '../ui/modal';
import Button from '../ui/button/Button';
import Label from '../form/Label';
import Input from '../form/input/InputField';
import { Loader2, Upload, X, CheckCircle } from 'lucide-react';
import { API_BASE_URL } from '../../services/api';
import { useAuthStore } from '../../store/authStore';

export interface PaymentConfirmationData {
  invoice_id: number;
  payment_method: string;
  amount: string;
  manual_reference: string;
  manual_notes?: string;
  proof_url?: string;
}

interface PaymentConfirmationModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess?: () => void;
  invoice: {
    id: number;
    invoice_number: string;
    total?: string;  // For backward compatibility
    total_amount?: string;  // Backend returns 'total_amount'
    currency?: string;
  };
  paymentMethod: {
    payment_method: string;
    display_name: string;
  };
}

export default function PaymentConfirmationModal({
  isOpen,
  onClose,
  onSuccess,
  invoice,
  paymentMethod,
}: PaymentConfirmationModalProps) {
  const [formData, setFormData] = useState({
    manual_reference: '',
    manual_notes: '',
    proof_url: '',
  });
  const [uploadedFile, setUploadedFile] = useState<File | null>(null);
  const [uploadedFileName, setUploadedFileName] = useState('');
  const [loading, setLoading] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);
  const { user } = useAuthStore();

  const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // Validate file size (max 5MB)
    if (file.size > 5 * 1024 * 1024) {
      setError('File size must be less than 5MB');
      return;
    }

    // Validate file type
    const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'application/pdf'];
    if (!allowedTypes.includes(file.type)) {
      setError('Only JPEG, PNG, and PDF files are allowed');
      return;
    }

    setUploadedFile(file);
    setUploadedFileName(file.name);
    setError('');

    // Simulate file upload to S3 (replace with actual S3 upload)
    // For now, we'll just store the file locally and pass a placeholder URL
    setUploading(true);
    try {
      // TODO: Implement actual S3 upload here
      // const uploadedUrl = await uploadToS3(file);
      // For demo, use a placeholder
      const placeholderUrl = `https://s3.amazonaws.com/igny8-payments/${Date.now()}-${file.name}`;
      setFormData({ ...formData, proof_url: placeholderUrl });
    } catch (err) {
      setError('Failed to upload file. Please try again.');
    } finally {
      setUploading(false);
    }
  };

  const handleRemoveFile = () => {
    setUploadedFile(null);
    setUploadedFileName('');
    setFormData({ ...formData, proof_url: '' });
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    if (!formData.manual_reference.trim()) {
      setError('Transaction reference is required');
      return;
    }

    // Create AbortController for timeout handling
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 30000); // 30 second timeout

    try {
      setLoading(true);

      const token = useAuthStore.getState().token;
      const response = await fetch(`${API_BASE_URL}/v1/billing/admin/payments/confirm/`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...(token && { Authorization: `Bearer ${token}` }),
        },
        credentials: 'include',
        signal: controller.signal,
        body: JSON.stringify({
          invoice_id: invoice.id,
          payment_method: paymentMethod.payment_method,
          amount: invoice.total_amount || invoice.total || '0',  // Handle both field names
          manual_reference: formData.manual_reference.trim(),
          manual_notes: formData.manual_notes.trim() || undefined,
          proof_url: formData.proof_url || undefined,
        }),
      });

      clearTimeout(timeoutId);

      const data = await response.json();

      if (!response.ok || !data.success) {
        throw new Error(data.error || data.message || 'Failed to submit payment confirmation');
      }

      setSuccess(true);

      // Show success message for 5 seconds (increased from 2s), then close and call onSuccess
      setTimeout(() => {
        onClose();
        onSuccess?.();
        // Reset form
        setFormData({ manual_reference: '', manual_notes: '', proof_url: '' });
        setUploadedFile(null);
        setUploadedFileName('');
        setSuccess(false);
      }, 5000);
    } catch (err: any) {
      clearTimeout(timeoutId);
      if (err.name === 'AbortError') {
        setError('Request timeout. Please check your connection and try again.');
      } else {
        setError(err.message || 'Failed to submit payment confirmation');
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal isOpen={isOpen} onClose={onClose} className="max-w-2xl p-0">
      <div className="p-6 sm:p-8">
        {success ? (
          <div className="text-center py-8">
            <CheckCircle className="w-16 h-16 text-green-500 mx-auto mb-4" />
            <h3 className="text-2xl font-semibold text-gray-900 dark:text-white mb-2">
              Payment Submitted!
            </h3>
            <p className="text-gray-600 dark:text-gray-400">
              Your payment confirmation has been submitted for admin approval.
              You'll receive an email once it's processed.
            </p>
          </div>
        ) : (
          <>
            <h2 className="text-2xl font-semibold text-gray-900 dark:text-white mb-2">
              Confirm Payment
            </h2>
            <p className="text-sm text-gray-600 dark:text-gray-400 mb-6">
              Submit proof of payment for invoice #{invoice.invoice_number}
            </p>

            {error && (
              <div className="mb-4 p-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg dark:bg-red-900/20 dark:text-red-400 dark:border-red-800">
                {error}
              </div>
            )}

            {/* Invoice Details */}
            <div className="mb-6 p-4 rounded-lg bg-gray-50 dark:bg-gray-800">
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <span className="text-gray-600 dark:text-gray-400">Invoice Number:</span>
                  <p className="font-semibold text-gray-900 dark:text-white">
                    #{invoice.invoice_number}
                  </p>
                </div>
                <div>
                  <span className="text-gray-600 dark:text-gray-400">Amount:</span>
                  <p className="font-semibold text-gray-900 dark:text-white">
                    {invoice.currency?.toUpperCase() || 'USD'} {parseFloat(invoice.total_amount || invoice.total || '0').toFixed(2)}
                  </p>
                </div>
                <div className="col-span-2">
                  <span className="text-gray-600 dark:text-gray-400">Payment Method:</span>
                  <p className="font-semibold text-gray-900 dark:text-white">
                    {paymentMethod.display_name}
                  </p>
                </div>
              </div>
            </div>

            <form onSubmit={handleSubmit} className="space-y-5">
              {/* Transaction Reference */}
              <div>
                <Label>
                  Transaction Reference / ID<span className="text-error-500">*</span>
                </Label>
                <Input
                  type="text"
                  id="manual_reference"
                  name="manual_reference"
                  value={formData.manual_reference}
                  onChange={(e) => setFormData({ ...formData, manual_reference: e.target.value })}
                  placeholder="TXN123456789 or Bank Reference Number"
                  disabled={loading}
                />
                <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                  Enter the transaction ID from your bank or payment receipt
                </p>
              </div>

              {/* Additional Notes */}
              <div>
                <Label>Additional Notes (Optional)</Label>
                <textarea
                  id="manual_notes"
                  name="manual_notes"
                  value={formData.manual_notes}
                  onChange={(e) => setFormData({ ...formData, manual_notes: e.target.value })}
                  placeholder="Any additional information about the payment..."
                  rows={3}
                  disabled={loading}
                  className="w-full px-4 py-3 text-sm border border-gray-300 rounded-lg focus:border-brand-500 focus:ring-2 focus:ring-brand-500/20 dark:bg-gray-800 dark:border-gray-700 dark:text-white dark:focus:border-brand-400"
                />
              </div>

              {/* Proof Upload */}
              <div>
                <Label>Upload Proof of Payment (Optional)</Label>
                {!uploadedFileName ? (
                  <div className="mt-2">
                    <label
                      htmlFor="proof-upload"
                      className="flex flex-col items-center justify-center w-full h-32 border-2 border-dashed border-gray-300 rounded-lg cursor-pointer hover:border-brand-500 hover:bg-brand-50 dark:border-gray-700 dark:hover:border-brand-400 dark:hover:bg-brand-500/10 transition-colors"
                    >
                      <div className="flex flex-col items-center justify-center pt-5 pb-6">
                        <Upload className="w-10 h-10 mb-3 text-gray-400" />
                        <p className="mb-2 text-sm text-gray-500 dark:text-gray-400">
                          <span className="font-semibold">Click to upload</span> or drag and drop
                        </p>
                        <p className="text-xs text-gray-500 dark:text-gray-400">
                          PNG, JPG or PDF (max. 5MB)
                        </p>
                      </div>
                      <input
                        id="proof-upload"
                        type="file"
                        className="hidden"
                        onChange={handleFileSelect}
                        accept=".jpg,.jpeg,.png,.pdf"
                        disabled={loading || uploading}
                      />
                    </label>
                  </div>
                ) : (
                  <div className="mt-2 flex items-center justify-between p-3 bg-gray-50 border border-gray-200 rounded-lg dark:bg-gray-800 dark:border-gray-700">
                    <div className="flex items-center gap-2">
                      <CheckCircle className="w-5 h-5 text-green-500" />
                      <span className="text-sm text-gray-700 dark:text-gray-300">
                        {uploadedFileName}
                      </span>
                    </div>
                    <button
                      type="button"
                      onClick={handleRemoveFile}
                      disabled={loading}
                      className="p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded transition-colors"
                    >
                      <X className="w-4 h-4 text-gray-500" />
                    </button>
                  </div>
                )}
                {uploading && (
                  <div className="mt-2 flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400">
                    <Loader2 className="w-4 h-4 animate-spin" />
                    <span>Uploading...</span>
                  </div>
                )}
              </div>

              {/* Action Buttons */}
              <div className="flex gap-3 pt-4">
                <Button
                  type="button"
                  variant="outline"
                  onClick={onClose}
                  disabled={loading}
                  className="flex-1"
                >
                  Cancel
                </Button>
                <Button
                  type="submit"
                  variant="primary"
                  disabled={loading || uploading}
                  className="flex-1"
                >
                  {loading ? (
                    <>
                      <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                      Submitting...
                    </>
                  ) : (
                    'Submit Payment Confirmation'
                  )}
                </Button>
              </div>
            </form>
          </>
        )}
      </div>
    </Modal>
  );
}
