/**
 * Booking Settings Page
 *
 * Manage booking URLs and customer redirect settings.
 */

import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useOutletContext } from 'react-router-dom';
import {
  Calendar, Link2, Copy, ExternalLink, Save, CheckCircle
} from 'lucide-react';
import { Business, User } from '../../types';

const BookingSettings: React.FC = () => {
  const { t } = useTranslation();
  const { business, user, updateBusiness } = useOutletContext<{
    business: Business;
    user: User;
    updateBusiness: (updates: Partial<Business>) => void;
  }>();

  // Local state
  const [showToast, setShowToast] = useState(false);
  const [returnUrl, setReturnUrl] = useState(business.bookingReturnUrl || '');
  const [returnUrlSaving, setReturnUrlSaving] = useState(false);

  const isOwner = user.role === 'owner';

  const handleSaveReturnUrl = async () => {
    setReturnUrlSaving(true);
    try {
      await updateBusiness({ bookingReturnUrl: returnUrl });
      setShowToast(true);
      setTimeout(() => setShowToast(false), 3000);
    } catch (error) {
      alert(t('settings.booking.failedToSaveReturnUrl', 'Failed to save return URL'));
    } finally {
      setReturnUrlSaving(false);
    }
  };

  if (!isOwner) {
    return (
      <div className="text-center py-12">
        <p className="text-gray-500 dark:text-gray-400">
          {t('settings.booking.onlyOwnerCanAccess', 'Only the business owner can access these settings.')}
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h2 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-3">
          <Calendar className="text-brand-500" />
          {t('settings.booking.title', 'Booking')}
        </h2>
        <p className="text-gray-500 dark:text-gray-400 mt-1">
          {t('settings.booking.description', 'Configure your booking page URL and customer redirect settings')}
        </p>
      </div>

      {/* Booking URL */}
      <section className="bg-white dark:bg-gray-800 p-6 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm">
        <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center gap-2">
          <Link2 size={20} className="text-brand-500" /> {t('settings.booking.yourBookingUrl', 'Your Booking URL')}
        </h3>
        <p className="text-sm text-gray-500 dark:text-gray-400 mb-4">
          {t('settings.booking.shareWithCustomers', 'Share this URL with your customers so they can book appointments with you.')}
        </p>
        <div className="flex items-center gap-3 p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg">
          <code className="flex-1 text-sm font-mono text-gray-900 dark:text-white">
            {business.subdomain}.smoothschedule.com
          </code>
          <button
            onClick={() => {
              navigator.clipboard.writeText(`https://${business.subdomain}.smoothschedule.com`);
              setShowToast(true);
              setTimeout(() => setShowToast(false), 2000);
            }}
            className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
            title={t('settings.booking.copyToClipboard', 'Copy to clipboard')}
          >
            <Copy size={16} />
          </button>
          <a
            href={`https://${business.subdomain}.smoothschedule.com`}
            target="_blank"
            rel="noopener noreferrer"
            className="p-2 text-brand-500 hover:text-brand-600 dark:hover:text-brand-400 transition-colors"
            title={t('settings.booking.openBookingPage', 'Open booking page')}
          >
            <ExternalLink size={16} />
          </a>
        </div>
        <p className="mt-3 text-xs text-gray-500 dark:text-gray-400">
          {t('settings.booking.customDomainPrompt', 'Want to use your own domain? Set up a')} <a href="/settings/custom-domains" className="text-brand-500 hover:underline">{t('settings.booking.customDomain', 'custom domain')}</a>.
        </p>
      </section>

      {/* Return URL - Where to redirect customers after booking */}
      <section className="bg-white dark:bg-gray-800 p-6 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm">
        <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2 flex items-center gap-2">
          <ExternalLink size={20} className="text-green-500" /> {t('settings.booking.returnUrl', 'Return URL')}
        </h3>
        <p className="text-sm text-gray-500 dark:text-gray-400 mb-4">
          {t('settings.booking.returnUrlDescription', 'After a customer completes a booking, redirect them to this URL (e.g., a thank you page on your website).')}
        </p>
        <div className="flex gap-2">
          <input
            type="url"
            value={returnUrl}
            onChange={(e) => setReturnUrl(e.target.value)}
            placeholder={t('settings.booking.returnUrlPlaceholder', 'https://yourbusiness.com/thank-you')}
            className="flex-1 px-4 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white rounded-lg focus:ring-2 focus:ring-brand-500 text-sm"
          />
          <button
            onClick={handleSaveReturnUrl}
            disabled={returnUrlSaving}
            className="inline-flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium text-sm"
          >
            <Save size={16} />
            {returnUrlSaving ? t('settings.booking.saving', 'Saving...') : t('settings.booking.save', 'Save')}
          </button>
        </div>
        <p className="mt-2 text-xs text-gray-500 dark:text-gray-400">
          {t('settings.booking.leaveEmpty', 'Leave empty to keep customers on the booking confirmation page.')}
        </p>
      </section>

      {/* Toast */}
      {showToast && (
        <div className="fixed bottom-4 right-4 flex items-center gap-2 px-4 py-3 bg-green-500 text-white rounded-lg shadow-lg">
          <CheckCircle size={18} />
          {t('settings.booking.copiedToClipboard', 'Copied to clipboard')}
        </div>
      )}
    </div>
  );
};

export default BookingSettings;
