import React, { useState, useEffect } from "react";
import QRCode from "react-qr-code";
import { formatCurrency } from "../utils/formatters";
import { Input } from "./ui/input";
import { Label } from "./ui/label";

interface ReceivePixDialogProps {
  isOpen: boolean;
  onClose: () => void;
  onConfirm: (value: number) => void;
  orderId: number;
  customerName: string;
  orderValue: number;
  showQrCode: boolean;
  qrCodeValue?: string;
  pixValue?: number;
  processing?: boolean;
}

const ReceivePixDialog: React.FC<ReceivePixDialogProps> = ({
  isOpen,
  onClose,
  onConfirm,
  orderId,
  customerName,
  orderValue,
  showQrCode,
  qrCodeValue = "",
  pixValue = 0,
  processing = false,
}) => {
  const [inputValue, setInputValue] = useState<string>("");
  const [isModalAnimating, setIsModalAnimating] = useState(false);
  const [shouldRenderModal, setShouldRenderModal] = useState(false);

  useEffect(() => {
    if (isOpen) {
      setShouldRenderModal(true);
      setTimeout(() => setIsModalAnimating(true), 10);
      if (!showQrCode) {
        setInputValue(orderValue.toFixed(2));
      }
    } else {
      setIsModalAnimating(false);
      const timer = setTimeout(() => setShouldRenderModal(false), 300);
      return () => clearTimeout(timer);
    }
  }, [isOpen, showQrCode, orderValue]);

  const handleConfirm = () => {
    const value = parseFloat(inputValue);
    if (isNaN(value) || value <= 0) {
      return;
    }
    onConfirm(value);
  };

  const handleCopyQrCode = () => {
    if (qrCodeValue) {
      navigator.clipboard.writeText(qrCodeValue);
    }
  };

  if (!shouldRenderModal) return null;

  return (
    <div className="fixed inset-0 z-[200] flex items-center justify-center">
      {/* Overlay */}
      <div
        className={`absolute inset-0 bg-[#001f3f]/60 backdrop-blur-sm transition-opacity duration-300 ${
          isModalAnimating ? "opacity-100" : "opacity-0"
        }`}
        onClick={onClose}
      ></div>

      {/* Dialog */}
      <div
        className={`relative bg-white rounded-3xl shadow-2xl max-w-md w-full mx-4 transform transition-all duration-300 ${
          isModalAnimating ? "scale-100 opacity-100" : "scale-95 opacity-0"
        }`}
      >
        {/* Header */}
        <div className="p-6 bg-[#002147] text-white rounded-t-3xl relative overflow-hidden">
          <div className="relative z-10">
            <div className="flex items-center gap-3 mb-2">
              <div className="w-12 h-12 bg-teal-500/20 rounded-2xl flex items-center justify-center">
                <svg
                  className="w-6 h-6 text-teal-400"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth="2.5"
                    d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"
                  />
                </svg>
              </div>
              <div className="flex-1">
                <h3 className="text-xl font-black">Recebimento via PIX</h3>
                <p className="text-xs text-blue-400 font-bold uppercase tracking-wider mt-0.5">
                  {showQrCode ? "QR Code gerado" : "Informe o valor"}
                </p>
              </div>
              <button
                onClick={onClose}
                className="p-2 text-slate-400 hover:text-slate-600 rounded-lg transition-colors"
              >
                <svg
                  className="w-6 h-6"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M6 18L18 6M6 6l12 12"
                  />
                </svg>
              </button>
            </div>
          </div>
          <div className="absolute right-[-10%] top-[-10%] w-32 h-32 bg-teal-400/10 rounded-full blur-2xl"></div>
        </div>

        {/* Content */}
        <div className="p-6">
          {!showQrCode ? (
            <div className="space-y-4">
              <div>
                <Label htmlFor="pixValue">Informe o valor a ser recebido via PIX</Label>
                <Input
                  id="pixValue"
                  type="number"
                  step="0.01"
                  min="0.01"
                  max={orderValue}
                  value={inputValue}
                  onChange={(e) => setInputValue(e.target.value)}
                  placeholder="0.00"
                  className="mt-2"
                />
                <p className="text-xs text-slate-500 mt-1">
                  Valor máximo: {formatCurrency(orderValue)}
                </p>
              </div>
            </div>
          ) : (
            <div className="space-y-4">
              {/* Informações do pedido */}
              <div className="grid grid-cols-2 gap-4 mb-4">
                <div>
                  <Label className="text-xs text-slate-500">Pedido</Label>
                  <p className="text-sm font-bold text-slate-800">{orderId}</p>
                </div>
                <div>
                  <Label className="text-xs text-slate-500">Cliente</Label>
                  <p className="text-sm font-bold text-slate-800 truncate">{customerName}</p>
                </div>
                <div className="col-span-2">
                  <Label className="text-xs text-slate-500">Valor</Label>
                  <p className="text-lg font-black text-teal-600">
                    {formatCurrency(pixValue)}
                  </p>
                </div>
              </div>

              {/* QR Code */}
              <div className="flex justify-center p-4 bg-slate-50 rounded-xl">
                <div className="bg-white p-4 rounded-lg">
                  <QRCode
                    value={qrCodeValue}
                    size={200}
                    level="M"
                  />
                </div>
              </div>

              {/* Código PIX */}
              <div>
                <Label className="text-xs text-slate-500 mb-2 block">
                  Código PIX (copiar e colar)
                </Label>
                <div className="flex gap-2">
                  <Input
                    readOnly
                    value={qrCodeValue}
                    onClick={(e) => (e.target as HTMLInputElement).select()}
                    className="font-mono text-xs"
                  />
                  <button
                    onClick={handleCopyQrCode}
                    className="px-4 py-2 bg-slate-200 text-slate-700 rounded-lg hover:bg-slate-300 transition-colors text-sm font-medium"
                    title="Copiar código PIX"
                  >
                    Copiar
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Actions */}
        <div className="p-6 pt-0 flex justify-end gap-3">
          {!showQrCode ? (
            <>
              <button
                onClick={onClose}
                className="flex-1 py-3 px-4 bg-gray-200 text-gray-700 font-black uppercase text-xs tracking-wider rounded-xl transition-all shadow-lg shadow-gray-300/20 active:scale-95 hover:bg-gray-300"
              >
                Cancelar
              </button>
              <button
                onClick={handleConfirm}
                disabled={processing || !inputValue || parseFloat(inputValue) <= 0}
                className="flex-1 py-3 px-4 bg-teal-500 text-white font-black uppercase text-xs tracking-wider rounded-xl transition-all shadow-lg shadow-teal-500/20 active:scale-95 hover:bg-teal-600 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {processing ? "Gerando..." : "Gerar"}
              </button>
            </>
          ) : (
            <button
              onClick={onClose}
              className="flex-1 py-3 px-4 bg-teal-500 text-white font-black uppercase text-xs tracking-wider rounded-xl transition-all shadow-lg shadow-teal-500/20 active:scale-95 hover:bg-teal-600"
            >
              Fechar
            </button>
          )}
        </div>
      </div>
    </div>
  );
};

export default ReceivePixDialog;

