/**
 * General Settings Page
 *
 * Business identity settings: name, subdomain, timezone, contact info.
 */

import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useOutletContext } from 'react-router-dom';
import { Building2, Save, Check, Globe } from 'lucide-react';
import { Business, User } from '../../types';

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

  const [formState, setFormState] = useState({
    name: business.name,
    subdomain: business.subdomain,
    contactEmail: business.contactEmail || '',
    phone: business.phone || '',
    timezone: business.timezone || 'America/New_York',
    timezoneDisplayMode: business.timezoneDisplayMode || 'business',
  });
  const [showToast, setShowToast] = useState(false);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormState(prev => ({ ...prev, [name]: value }));
  };

  // IANA timezones grouped by region
  const timezoneGroups = [
    {
      label: 'United States',
      timezones: [
        'America/New_York',
        'America/Chicago',
        'America/Denver',
        'America/Los_Angeles',
        'America/Anchorage',
        'Pacific/Honolulu',
        'America/Phoenix',
        'America/Detroit',
        'America/Indiana/Indianapolis',
        'America/Boise',
      ],
    },
    {
      label: 'Canada',
      timezones: [
        'America/Toronto',
        'America/Vancouver',
        'America/Edmonton',
        'America/Winnipeg',
        'America/Halifax',
        'America/St_Johns',
      ],
    },
    {
      label: 'Mexico & Central America',
      timezones: [
        'America/Mexico_City',
        'America/Tijuana',
        'America/Cancun',
        'America/Guatemala',
        'America/Costa_Rica',
        'America/Panama',
      ],
    },
    {
      label: 'South America',
      timezones: [
        'America/Sao_Paulo',
        'America/Argentina/Buenos_Aires',
        'America/Santiago',
        'America/Bogota',
        'America/Lima',
        'America/Caracas',
      ],
    },
    {
      label: 'Europe',
      timezones: [
        'Europe/London',
        'Europe/Dublin',
        'Europe/Paris',
        'Europe/Berlin',
        'Europe/Madrid',
        'Europe/Rome',
        'Europe/Amsterdam',
        'Europe/Brussels',
        'Europe/Vienna',
        'Europe/Zurich',
        'Europe/Stockholm',
        'Europe/Oslo',
        'Europe/Copenhagen',
        'Europe/Helsinki',
        'Europe/Athens',
        'Europe/Bucharest',
        'Europe/Warsaw',
        'Europe/Prague',
        'Europe/Moscow',
        'Europe/Istanbul',
      ],
    },
    {
      label: 'Asia',
      timezones: [
        'Asia/Tokyo',
        'Asia/Seoul',
        'Asia/Shanghai',
        'Asia/Hong_Kong',
        'Asia/Taipei',
        'Asia/Singapore',
        'Asia/Kuala_Lumpur',
        'Asia/Bangkok',
        'Asia/Ho_Chi_Minh',
        'Asia/Jakarta',
        'Asia/Manila',
        'Asia/Kolkata',
        'Asia/Mumbai',
        'Asia/Dubai',
        'Asia/Riyadh',
        'Asia/Jerusalem',
        'Asia/Karachi',
        'Asia/Dhaka',
      ],
    },
    {
      label: 'Australia & Pacific',
      timezones: [
        'Australia/Sydney',
        'Australia/Melbourne',
        'Australia/Brisbane',
        'Australia/Perth',
        'Australia/Adelaide',
        'Australia/Darwin',
        'Pacific/Auckland',
        'Pacific/Fiji',
        'Pacific/Guam',
      ],
    },
    {
      label: 'Africa',
      timezones: [
        'Africa/Johannesburg',
        'Africa/Cairo',
        'Africa/Lagos',
        'Africa/Nairobi',
        'Africa/Casablanca',
      ],
    },
    {
      label: 'Other',
      timezones: [
        'UTC',
      ],
    },
  ];

  const handleSave = async () => {
    await updateBusiness(formState);
    setShowToast(true);
    setTimeout(() => setShowToast(false), 3000);
  };

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

  if (!isOwner) {
    return (
      <div className="text-center py-12">
        <p className="text-gray-500 dark:text-gray-400">
          {t('settings.ownerOnly', '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">
          <Building2 className="text-brand-500" />
          {t('settings.general.title', 'General Settings')}
        </h2>
        <p className="text-gray-500 dark:text-gray-400 mt-1">
          {t('settings.general.subtitle', 'Manage your business identity and contact information.')}
        </p>
      </div>

      {/* Business Identity */}
      <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">
          {t('settings.businessIdentity', 'Business Identity')}
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              {t('settings.businessName', 'Business Name')}
            </label>
            <input
              type="text"
              name="name"
              value={formState.name}
              onChange={handleChange}
              className="w-full 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"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              {t('settings.subdomain', 'Subdomain')}
            </label>
            <div className="flex">
              <input
                type="text"
                name="subdomain"
                value={formState.subdomain}
                className="flex-1 min-w-0 px-4 py-2 border border-r-0 border-gray-300 dark:border-gray-600 rounded-l-lg bg-gray-50 dark:bg-gray-900 text-gray-500 dark:text-gray-400 cursor-not-allowed"
                readOnly
              />
              <span className="inline-flex items-center px-4 py-2 border border-l-0 border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-500 dark:text-gray-400 text-sm rounded-r-lg">
                .smoothschedule.com
              </span>
            </div>
            <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
              {t('settings.subdomainHint', 'Contact support to change your subdomain.')}
            </p>
          </div>
        </div>
      </section>

      {/* Timezone Settings */}
      <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">
          <Globe size={20} className="text-brand-500" />
          {t('settings.timezone.title', 'Timezone Settings')}
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              {t('settings.timezone.businessTimezone', 'Business Timezone')}
            </label>
            <select
              name="timezone"
              value={formState.timezone}
              onChange={handleChange}
              className="w-full 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"
            >
              {timezoneGroups.map(group => (
                <optgroup key={group.label} label={group.label}>
                  {group.timezones.map(tz => (
                    <option key={tz} value={tz}>
                      {tz}
                    </option>
                  ))}
                </optgroup>
              ))}
            </select>
            <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
              {t('settings.timezone.businessTimezoneHint', 'The timezone where your business operates.')}
            </p>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              {t('settings.timezone.displayMode', 'Time Display Mode')}
            </label>
            <select
              name="timezoneDisplayMode"
              value={formState.timezoneDisplayMode}
              onChange={handleChange}
              className="w-full 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"
            >
              <option value="business">
                {t('settings.timezone.businessMode', 'Business Timezone')}
              </option>
              <option value="viewer">
                {t('settings.timezone.viewerMode', "Viewer's Local Timezone")}
              </option>
            </select>
            <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
              {formState.timezoneDisplayMode === 'business'
                ? t('settings.timezone.businessModeHint', 'All appointment times are displayed in your business timezone.')
                : t('settings.timezone.viewerModeHint', 'Appointment times adapt to each viewer\'s local timezone.')}
            </p>
          </div>
        </div>
      </section>

      {/* Contact Information */}
      <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">
          {t('settings.contactInfo', 'Contact Information')}
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              {t('settings.contactEmail', 'Contact Email')}
            </label>
            <input
              type="email"
              name="contactEmail"
              value={formState.contactEmail}
              onChange={handleChange}
              placeholder="contact@yourbusiness.com"
              className="w-full 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"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              {t('settings.phone', 'Phone Number')}
            </label>
            <input
              type="tel"
              name="phone"
              value={formState.phone}
              onChange={handleChange}
              placeholder="+1 (555) 123-4567"
              className="w-full 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"
            />
          </div>
        </div>
      </section>

      {/* Save Button */}
      <div className="flex justify-end">
        <button
          onClick={handleSave}
          className="flex items-center gap-2 px-6 py-2.5 bg-brand-600 hover:bg-brand-700 text-white font-medium rounded-lg transition-colors"
        >
          <Save size={18} />
          {t('common.saveChanges', 'Save Changes')}
        </button>
      </div>

      {/* 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 animate-fade-in">
          <Check size={18} />
          {t('common.saved', 'Changes saved successfully')}
        </div>
      )}
    </div>
  );
};

export default GeneralSettings;
