'use client';

import { useState } from 'react';
import { Globe, Copy, Check } from 'lucide-react';
import { cn } from '@/lib/utils';

function getAppUrl(): string {
  // Use environment variable or fall back to window location
  if (typeof window !== 'undefined') {
    return process.env.NEXT_PUBLIC_APP_URL || window.location.origin;
  }
  return process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';
}

interface CopyFieldProps {
  label: string;
  value: string;
}

function CopyField({ label, value }: CopyFieldProps) {
  const [copied, setCopied] = useState(false);

  async function handleCopy() {
    try {
      await navigator.clipboard.writeText(value);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      // Fallback for older browsers
      const el = document.createElement('textarea');
      el.value = value;
      el.style.position = 'fixed';
      el.style.opacity = '0';
      document.body.appendChild(el);
      el.select();
      document.execCommand('copy');
      document.body.removeChild(el);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  }

  return (
    <div>
      <label className="block text-xs font-medium text-slate-400 mb-1.5">{label}</label>
      <div className="flex items-center gap-2">
        <div className="flex-1 rounded-lg border border-slate-700/30 bg-slate-800/30 px-3 py-2 text-xs text-cyan-400/80 font-mono overflow-x-auto whitespace-nowrap scrollbar-none">
          {value}
        </div>
        <button
          onClick={handleCopy}
          className={cn(
            'flex items-center justify-center h-9 w-9 rounded-lg border transition-all flex-shrink-0',
            copied
              ? 'border-green-500/30 bg-green-500/10 text-green-400'
              : 'border-slate-700/50 bg-slate-800/50 text-slate-400 hover:text-white hover:bg-slate-700/50'
          )}
          title={copied ? 'Copied!' : 'Copy to clipboard'}
        >
          {copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
        </button>
      </div>
    </div>
  );
}

export default function WebhookUrlsCard() {
  const appUrl = getAppUrl();

  const inboundUrl = `${appUrl}/api/webhooks/twilio/inbound`;
  const statusUrl = `${appUrl}/api/webhooks/twilio/status`;
  const responseUrl = `${appUrl}/api/webhooks/closebot/response`;

  return (
    <div className="card p-6 space-y-5">
      {/* Header */}
      <div className="flex items-center gap-3">
        <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-green-500/10 border border-green-500/20">
          <Globe className="h-5 w-5 text-green-400" />
        </div>
        <div>
          <h3 className="text-sm font-semibold text-white">Webhook URLs</h3>
          <p className="text-xs text-slate-500">Configure these URLs in Twilio & CloseBot</p>
        </div>
      </div>

      {/* URLs */}
      <div className="space-y-4">
        <CopyField
          label="Twilio Inbound SMS Webhook"
          value={inboundUrl}
        />
        <CopyField
          label="Twilio Status Callback"
          value={statusUrl}
        />
        <CopyField
          label="CloseBot Response Webhook"
          value={responseUrl}
        />
      </div>

      {/* Setup hint */}
      <div className="rounded-lg border border-slate-700/30 bg-slate-800/20 px-4 py-3">
        <p className="text-xs text-slate-500 leading-relaxed">
          <span className="text-slate-400 font-medium">Setup:</span>{' '}
          Copy the Inbound URL to your Twilio phone number&apos;s &ldquo;A Message Comes In&rdquo; webhook.
          Set the Status Callback URL for delivery tracking.
          Add the Response URL in CloseBot&apos;s webhook source settings.
        </p>
      </div>
    </div>
  );
}
