'use client';

import React, { useState, useEffect } from 'react';
import { Smartphone, CheckCircle2, XCircle, Loader2, RefreshCw } from 'lucide-react';
import Modal from '@/components/ui/Modal';

interface MpesaModalProps {
  open: boolean;
  onClose: () => void;
  amount: number;
  phone: string;
  onSuccess: () => void;
}

type MpesaState = 'idle' | 'sending' | 'waiting' | 'confirmed' | 'failed' | 'timeout';

export default function MpesaModal({ open, onClose, amount, phone, onSuccess }: MpesaModalProps) {
  const [phoneInput, setPhoneInput] = useState(phone);
  const [state, setState] = useState<MpesaState>('idle');
  const [countdown, setCountdown] = useState(60);
  const [mpesaRef, setMpesaRef] = useState('');

  useEffect(() => {
    if (phone) setPhoneInput(phone);
  }, [phone]);

  useEffect(() => {
    if (!open) {
      setState('idle');
      setCountdown(60);
      setMpesaRef('');
    }
  }, [open]);

  useEffect(() => {
    let timer: ReturnType<typeof setInterval>;
    if (state === 'waiting') {
      timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(timer);
            setState('timeout');
            return 0;
          }
          return prev - 1;
        });
      }, 1000);

      // Simulate M-Pesa confirmation after 4 seconds
      // Backend integration point: poll GET /api/mpesa/status/{checkoutRequestId}
      const confirmTimer = setTimeout(() => {
        clearInterval(timer);
        const ref = `QHX${Math.random().toString(36).slice(2, 10).toUpperCase()}`;
        setMpesaRef(ref);
        setState('confirmed');
      }, 4000);

      return () => {
        clearInterval(timer);
        clearTimeout(confirmTimer);
      };
    }
    return () => {};
  }, [state]);

  // Backend integration point: POST /api/mpesa/stk-push
  const sendSTKPush = async () => {
    if (!phoneInput || phoneInput.length < 10) return;
    setState('sending');
    await new Promise((r) => setTimeout(r, 1200));
    setCountdown(60);
    setState('waiting');
  };

  const handleSuccess = () => {
    onSuccess();
  };

  const stateContent = () => {
    switch (state) {
      case 'idle':
        return (
          <div className="space-y-4">
            <div className="bg-info-bg border border-blue-200 rounded-lg p-3">
              <p className="text-xs text-muted-foreground leading-relaxed">
                An STK Push prompt will be sent to the customer's Safaricom number. They will receive a pop-up on their phone asking them to enter their M-Pesa PIN.
              </p>
            </div>
            <div>
              <label className="block text-xs font-600 text-foreground mb-1.5">
                Customer Phone Number
              </label>
              <input
                type="tel"
                value={phoneInput}
                onChange={(e) => setPhoneInput(e.target.value)}
                placeholder="07XXXXXXXX or 2547XXXXXXXX"
                className="w-full h-10 px-3 text-sm bg-card border border-border rounded-lg outline-none focus:border-primary focus:ring-1 focus:ring-primary/20 text-foreground placeholder:text-muted-foreground"
              />
              <p className="text-xs text-muted-foreground mt-1">Must be a Safaricom number registered for M-Pesa</p>
            </div>
            <div className="bg-muted rounded-lg px-4 py-3 flex items-center justify-between">
              <span className="text-sm text-muted-foreground">Amount to collect</span>
              <span className="text-xl font-800 text-foreground font-tabular">KES {amount.toLocaleString()}</span>
            </div>
          </div>
        );

      case 'sending':
        return (
          <div className="flex flex-col items-center justify-center py-8 gap-4">
            <div className="w-14 h-14 rounded-full bg-info-bg flex items-center justify-center">
              <Loader2 size={28} className="text-info animate-spin" />
            </div>
            <div className="text-center">
              <p className="text-sm font-600 text-foreground">Sending STK Push…</p>
              <p className="text-xs text-muted-foreground mt-1">Contacting Safaricom M-Pesa servers</p>
            </div>
          </div>
        );

      case 'waiting':
        return (
          <div className="flex flex-col items-center justify-center py-6 gap-4">
            <div className="relative w-16 h-16">
              <div className="absolute inset-0 rounded-full border-4 border-info/20" />
              <div
                className="absolute inset-0 rounded-full border-4 border-info border-t-transparent animate-spin"
                style={{ animationDuration: '2s' }}
              />
              <div className="absolute inset-0 flex items-center justify-center">
                <Smartphone size={24} className="text-info" />
              </div>
            </div>
            <div className="text-center">
              <p className="text-sm font-700 text-foreground">Waiting for customer confirmation</p>
              <p className="text-xs text-muted-foreground mt-1">
                STK Push sent to <span className="font-700 text-foreground">{phoneInput}</span>
              </p>
              <p className="text-xs text-muted-foreground mt-1">
                Customer should enter M-Pesa PIN on their phone
              </p>
            </div>
            <div className="bg-muted rounded-full px-4 py-1.5 flex items-center gap-2">
              <span className="text-xs text-muted-foreground">Times out in</span>
              <span className={`text-sm font-800 font-tabular ${countdown <= 15 ? 'text-danger' : 'text-foreground'}`}>
                {countdown}s
              </span>
            </div>
            <div className="bg-info-bg border border-blue-200 rounded-lg px-4 py-2 w-full text-center">
              <p className="text-xs text-info font-600">Amount: KES {amount.toLocaleString()}</p>
            </div>
          </div>
        );

      case 'confirmed':
        return (
          <div className="flex flex-col items-center justify-center py-6 gap-4">
            <div className="w-16 h-16 rounded-full bg-success/20 flex items-center justify-center">
              <CheckCircle2 size={36} className="text-success" />
            </div>
            <div className="text-center">
              <p className="text-lg font-700 text-foreground">Payment Confirmed!</p>
              <p className="text-xs text-muted-foreground mt-1">M-Pesa transaction successful</p>
            </div>
            <div className="bg-success-bg border border-green-200 rounded-lg px-5 py-3 w-full space-y-1.5">
              <div className="flex justify-between text-xs">
                <span className="text-muted-foreground">M-Pesa Ref</span>
                <span className="font-mono font-700 text-foreground">{mpesaRef}</span>
              </div>
              <div className="flex justify-between text-xs">
                <span className="text-muted-foreground">Amount</span>
                <span className="font-700 text-success font-tabular">KES {amount.toLocaleString()}</span>
              </div>
              <div className="flex justify-between text-xs">
                <span className="text-muted-foreground">Phone</span>
                <span className="font-600 text-foreground">{phoneInput}</span>
              </div>
              <div className="flex justify-between text-xs">
                <span className="text-muted-foreground">Time</span>
                <span className="font-600 text-foreground">09:19 AM</span>
              </div>
            </div>
          </div>
        );

      case 'failed':
        return (
          <div className="flex flex-col items-center justify-center py-6 gap-4">
            <div className="w-16 h-16 rounded-full bg-danger/10 flex items-center justify-center">
              <XCircle size={36} className="text-danger" />
            </div>
            <div className="text-center">
              <p className="text-sm font-700 text-foreground">Payment Failed</p>
              <p className="text-xs text-muted-foreground mt-1">Customer cancelled or entered wrong PIN</p>
            </div>
          </div>
        );

      case 'timeout':
        return (
          <div className="flex flex-col items-center justify-center py-6 gap-4">
            <div className="w-16 h-16 rounded-full bg-warning/10 flex items-center justify-center">
              <XCircle size={36} className="text-warning" />
            </div>
            <div className="text-center">
              <p className="text-sm font-700 text-foreground">Request Timed Out</p>
              <p className="text-xs text-muted-foreground mt-1">Customer did not respond within 60 seconds</p>
            </div>
          </div>
        );
    }
  };

  const footerContent = () => {
    switch (state) {
      case 'idle':
        return (
          <div className="flex gap-2">
            <button
              onClick={onClose}
              className="flex-1 h-9 border border-border rounded-lg text-sm font-600 text-foreground hover:bg-muted transition-colors"
            >
              Cancel
            </button>
            <button
              onClick={sendSTKPush}
              disabled={!phoneInput || phoneInput.length < 10}
              className="flex-1 h-9 btn-primary rounded-lg text-sm font-600 text-white disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
            >
              <Smartphone size={14} />
              Send STK Push
            </button>
          </div>
        );
      case 'waiting':
        return (
          <div className="flex gap-2">
            <button
              onClick={() => setState('failed')}
              className="flex-1 h-9 border border-border rounded-lg text-sm font-600 text-foreground hover:bg-muted transition-colors"
            >
              Cancel Request
            </button>
          </div>
        );
      case 'confirmed':
        return (
          <button
            onClick={handleSuccess}
            className="w-full h-10 btn-primary rounded-lg text-sm font-700 text-white flex items-center justify-center gap-2"
          >
            <CheckCircle2 size={15} />
            Complete Sale
          </button>
        );
      case 'failed': case'timeout':
        return (
          <div className="flex gap-2">
            <button
              onClick={onClose}
              className="flex-1 h-9 border border-border rounded-lg text-sm font-600 text-foreground hover:bg-muted transition-colors"
            >
              Cancel
            </button>
            <button
              onClick={() => setState('idle')}
              className="flex-1 h-9 btn-primary rounded-lg text-sm font-600 text-white flex items-center justify-center gap-2"
            >
              <RefreshCw size={13} />
              Try Again
            </button>
          </div>
        );
      default:
        return null;
    }
  };

  const titleMap: Record<MpesaState, string> = {
    idle: 'M-Pesa Payment',
    sending: 'Sending STK Push',
    waiting: 'Awaiting Confirmation',
    confirmed: 'Payment Successful',
    failed: 'Payment Failed',
    timeout: 'Request Timed Out',
  };

  return (
    <Modal
      open={open}
      onClose={state === 'waiting' || state === 'sending' ? () => {} : onClose}
      title={titleMap[state]}
      subtitle={state === 'idle' ? `KES ${amount.toLocaleString()} via Safaricom M-Pesa` : undefined}
      size="sm"
      footer={footerContent() ?? undefined}
    >
      {stateContent()}
    </Modal>
  );
}