import React, { useState } from "react";

interface RecoveryCodesDisplayProps {
  codes: string[];
  onAcknowledge?: () => void;
  showAcknowledgeButton?: boolean;
}

const RecoveryCodesDisplay: React.FC<RecoveryCodesDisplayProps> = ({
  codes,
  onAcknowledge,
  showAcknowledgeButton = true,
}) => {
  const [acknowledged, setAcknowledged] = useState(false);
  const [copied, setCopied] = useState(false);

  const handleCopyAll = async () => {
    const codesText = codes.join("\n");
    try {
      await navigator.clipboard.writeText(codesText);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      console.error("Failed to copy codes:", err);
    }
  };

  const handleDownload = () => {
    if (
      !window.confirm(
        "Warning: This will create an unencrypted file on your device. " +
        "Consider using a password manager instead. Continue?"
      )
    ) {
      return;
    }
    const codesText = `Village Share Recovery Codes\n${"=".repeat(30)}\n\nSave these codes in a secure location.\nEach code can only be used once.\n\n${codes.join("\n")}\n\nGenerated: ${new Date().toLocaleString()}`;
    const blob = new Blob([codesText], { type: "text/plain" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "village-share-recovery-codes.txt";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  const handlePrint = () => {
    if (
      !window.confirm(
        "Warning: Printed documents can be easily compromised. " +
        "Consider using a password manager instead. Continue?"
      )
    ) {
      return;
    }
    const printWindow = window.open("", "_blank");
    if (printWindow) {
      printWindow.document.write(`
        <html>
          <head>
            <title>Recovery Codes - Village Share</title>
            <style>
              body { font-family: monospace; padding: 20px; }
              h1 { font-size: 18px; }
              .codes { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin-top: 20px; }
              .code { background: #f0f0f0; padding: 10px; border-radius: 4px; text-align: center; }
              .warning { color: #856404; background: #fff3cd; padding: 15px; border-radius: 4px; margin-top: 20px; }
            </style>
          </head>
          <body>
            <h1>Village Share Recovery Codes</h1>
            <p>Save these codes in a secure location. Each code can only be used once.</p>
            <div class="codes">
              ${codes.map((code) => `<div class="code">${code}</div>`).join("")}
            </div>
            <div class="warning">
              <strong>Warning:</strong> These codes will not be shown again. Store them securely.
            </div>
            <p style="margin-top: 20px; font-size: 12px; color: #666;">Generated: ${new Date().toLocaleString()}</p>
          </body>
        </html>
      `);
      printWindow.document.close();
      printWindow.print();
    }
  };

  return (
    <div>
      <div className="alert alert-warning mb-3">
        <i className="bi bi-exclamation-triangle me-2"></i>
        <strong>Important:</strong> Save these recovery codes in a secure
        location. You will not be able to see them again.
      </div>

      <div className="row row-cols-2 g-2 mb-3">
        {codes.map((code, index) => (
          <div key={index} className="col">
            <div
              className="bg-light border rounded p-2 text-center font-monospace"
              style={{ fontSize: "0.9rem", letterSpacing: "1px" }}
            >
              {code}
            </div>
          </div>
        ))}
      </div>

      <div className="d-flex gap-2 mb-3">
        <button
          className="btn btn-outline-secondary btn-sm flex-fill"
          onClick={handleCopyAll}
        >
          <i className={`bi ${copied ? "bi-check" : "bi-clipboard"} me-1`}></i>
          {copied ? "Copied!" : "Copy All"}
        </button>
        <button
          className="btn btn-outline-secondary btn-sm flex-fill"
          onClick={handleDownload}
        >
          <i className="bi bi-download me-1"></i>
          Download
        </button>
        <button
          className="btn btn-outline-secondary btn-sm flex-fill"
          onClick={handlePrint}
        >
          <i className="bi bi-printer me-1"></i>
          Print
        </button>
      </div>

      {showAcknowledgeButton && (
        <>
          <div className="form-check mb-3">
            <input
              className="form-check-input"
              type="checkbox"
              id="acknowledgeRecoveryCodes"
              checked={acknowledged}
              onChange={(e) => setAcknowledged(e.target.checked)}
            />
            <label
              className="form-check-label"
              htmlFor="acknowledgeRecoveryCodes"
            >
              I have saved my recovery codes in a secure location
            </label>
          </div>

          <button
            className="btn btn-success w-100"
            disabled={!acknowledged}
            onClick={onAcknowledge}
          >
            Continue
          </button>
        </>
      )}
    </div>
  );
};

export default RecoveryCodesDisplay;
