import React, { useState } from 'react';
import { X, Send, Mail, Building2 } from 'lucide-react';
import { useCreateTenantInvitation } from '../../../hooks/usePlatform';

interface TenantInviteModalProps {
  isOpen: boolean;
  onClose: () => void;
}

const TenantInviteModal: React.FC<TenantInviteModalProps> = ({ isOpen, onClose }) => {
  const createInvitationMutation = useCreateTenantInvitation();

  const [inviteForm, setInviteForm] = useState({
    email: '',
    suggested_business_name: '',
    subscription_tier: 'PROFESSIONAL' as 'FREE' | 'STARTER' | 'PROFESSIONAL' | 'ENTERPRISE',
    custom_max_users: null as number | null,
    custom_max_resources: null as number | null,
    use_custom_limits: false,
    permissions: {
      can_manage_oauth_credentials: false,
      can_accept_payments: false,
      can_use_custom_domain: false,
      can_white_label: false,
      can_api_access: false,
    },
    // New feature limits (not yet implemented)
    limits: {
      can_add_video_conferencing: false,
      max_event_types: null as number | null, // null = unlimited
      max_calendars_connected: null as number | null, // null = unlimited
      can_connect_to_api: false,
      can_book_repeated_events: false,
      can_require_2fa: false,
      can_download_logs: false,
      can_delete_data: false,
      can_use_masked_phone_numbers: false,
      can_use_pos: false,
      can_use_mobile_app: false,
    },
    personal_message: '',
  });
  const [inviteError, setInviteError] = useState<string | null>(null);
  const [inviteSuccess, setInviteSuccess] = useState(false);

  const resetForm = () => {
    setInviteForm({
      email: '',
      suggested_business_name: '',
      subscription_tier: 'PROFESSIONAL',
      custom_max_users: null,
      custom_max_resources: null,
      use_custom_limits: false,
      permissions: {
        can_manage_oauth_credentials: false,
        can_accept_payments: false,
        can_use_custom_domain: false,
        can_white_label: false,
        can_api_access: false,
      },
      limits: {
        can_add_video_conferencing: false,
        max_event_types: null,
        max_calendars_connected: null,
        can_connect_to_api: false,
        can_book_repeated_events: false,
        can_require_2fa: false,
        can_download_logs: false,
        can_delete_data: false,
        can_use_masked_phone_numbers: false,
        can_use_pos: false,
        can_use_mobile_app: false,
      },
      personal_message: '',
    });
    setInviteError(null);
    setInviteSuccess(false);
  };

  const handleClose = () => {
    resetForm();
    onClose();
  };

  const handleInviteSend = () => {
    setInviteError(null);
    setInviteSuccess(false);

    // Validation
    if (!inviteForm.email.trim()) {
      setInviteError('Email address is required');
      return;
    }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(inviteForm.email)) {
      setInviteError('Please enter a valid email address');
      return;
    }

    // Build invitation data
    const data: any = {
      email: inviteForm.email,
      subscription_tier: inviteForm.subscription_tier,
    };

    if (inviteForm.suggested_business_name.trim()) {
      data.suggested_business_name = inviteForm.suggested_business_name.trim();
    }

    if (inviteForm.use_custom_limits) {
      if (inviteForm.custom_max_users !== null && inviteForm.custom_max_users > 0) {
        data.custom_max_users = inviteForm.custom_max_users;
      }
      if (inviteForm.custom_max_resources !== null && inviteForm.custom_max_resources > 0) {
        data.custom_max_resources = inviteForm.custom_max_resources;
      }
    }

    // Only include permissions if at least one is enabled
    const hasPermissions = Object.values(inviteForm.permissions).some(v => v === true);
    if (hasPermissions) {
      data.permissions = inviteForm.permissions;
    }

    // Only include limits if at least one is enabled (boolean true or numeric value set)
    const hasLimits = Object.entries(inviteForm.limits).some(([key, value]) => {
      if (typeof value === 'boolean') return value === true;
      if (typeof value === 'number') return true; // numeric limits are meaningful even if 0
      return false;
    });
    if (hasLimits) {
      data.limits = inviteForm.limits;
    }

    if (inviteForm.personal_message.trim()) {
      data.personal_message = inviteForm.personal_message.trim();
    }

    createInvitationMutation.mutate(data, {
      onSuccess: () => {
        setInviteSuccess(true);
        setTimeout(() => {
          handleClose();
        }, 2000);
      },
      onError: (error: any) => {
        setInviteError(error.response?.data?.detail || error.message || 'Failed to send invitation');
      },
    });
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto">
        {/* Modal Header */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-indigo-100 dark:bg-indigo-900/30 rounded-lg">
              <Send size={24} className="text-indigo-600 dark:text-indigo-400" />
            </div>
            <div>
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white">Invite New Tenant</h3>
              <p className="text-sm text-gray-500 dark:text-gray-400">Send an invitation to create a new business</p>
            </div>
          </div>
          <button
            onClick={handleClose}
            className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
          >
            <X size={20} className="text-gray-500 dark:text-gray-400" />
          </button>
        </div>

        {/* Modal Body */}
        <div className="p-6 space-y-6">
          {inviteError && (
            <div className="p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
              <p className="text-sm text-red-600 dark:text-red-400">{inviteError}</p>
            </div>
          )}

          {inviteSuccess && (
            <div className="p-4 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg">
              <p className="text-sm text-green-600 dark:text-green-400">Invitation sent successfully!</p>
            </div>
          )}

          {/* Email */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Email Address *
            </label>
            <div className="relative">
              <Mail size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
              <input
                type="email"
                value={inviteForm.email}
                onChange={(e) => setInviteForm({ ...inviteForm, email: e.target.value })}
                className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                placeholder="owner@business.com"
              />
            </div>
          </div>

          {/* Suggested Business Name */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Suggested Business Name (Optional)
            </label>
            <div className="relative">
              <Building2 size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
              <input
                type="text"
                value={inviteForm.suggested_business_name}
                onChange={(e) => setInviteForm({ ...inviteForm, suggested_business_name: e.target.value })}
                className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                placeholder="Owner can change this during onboarding"
              />
            </div>
          </div>

          {/* Subscription Tier */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Subscription Tier
            </label>
            <select
              value={inviteForm.subscription_tier}
              onChange={(e) => setInviteForm({ ...inviteForm, subscription_tier: e.target.value as any })}
              className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
            >
              <option value="FREE">Free Trial</option>
              <option value="STARTER">Starter</option>
              <option value="PROFESSIONAL">Professional</option>
              <option value="ENTERPRISE">Enterprise</option>
            </select>
          </div>

          {/* Custom Limits */}
          <div>
            <label className="flex items-center gap-2 text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              <input
                type="checkbox"
                checked={inviteForm.use_custom_limits}
                onChange={(e) => setInviteForm({ ...inviteForm, use_custom_limits: e.target.checked })}
                className="rounded border-gray-300 dark:border-gray-600"
              />
              Override tier limits with custom values
            </label>
            {inviteForm.use_custom_limits && (
              <div className="grid grid-cols-2 gap-4 mt-2">
                <div>
                  <label className="block text-xs text-gray-600 dark:text-gray-400 mb-1">Max Users</label>
                  <input
                    type="number"
                    min="1"
                    value={inviteForm.custom_max_users || ''}
                    onChange={(e) => setInviteForm({ ...inviteForm, custom_max_users: e.target.value ? parseInt(e.target.value) : null })}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    placeholder="Leave empty for tier default"
                  />
                </div>
                <div>
                  <label className="block text-xs text-gray-600 dark:text-gray-400 mb-1">Max Resources</label>
                  <input
                    type="number"
                    min="1"
                    value={inviteForm.custom_max_resources || ''}
                    onChange={(e) => setInviteForm({ ...inviteForm, custom_max_resources: e.target.value ? parseInt(e.target.value) : null })}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    placeholder="Leave empty for tier default"
                  />
                </div>
              </div>
            )}
          </div>

          {/* Platform Permissions */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
              Platform Permissions
            </label>
            <div className="space-y-2">
              <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
                <input
                  type="checkbox"
                  checked={inviteForm.permissions.can_manage_oauth_credentials}
                  onChange={(e) => setInviteForm({ ...inviteForm, permissions: { ...inviteForm.permissions, can_manage_oauth_credentials: e.target.checked } })}
                  className="rounded border-gray-300 dark:border-gray-600"
                />
                Can manage OAuth credentials
              </label>
              <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
                <input
                  type="checkbox"
                  checked={inviteForm.permissions.can_accept_payments}
                  onChange={(e) => setInviteForm({ ...inviteForm, permissions: { ...inviteForm.permissions, can_accept_payments: e.target.checked } })}
                  className="rounded border-gray-300 dark:border-gray-600"
                />
                Can accept online payments (Stripe Connect)
              </label>
              <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
                <input
                  type="checkbox"
                  checked={inviteForm.permissions.can_use_custom_domain}
                  onChange={(e) => setInviteForm({ ...inviteForm, permissions: { ...inviteForm.permissions, can_use_custom_domain: e.target.checked } })}
                  className="rounded border-gray-300 dark:border-gray-600"
                />
                Can use custom domain
              </label>
              <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
                <input
                  type="checkbox"
                  checked={inviteForm.permissions.can_white_label}
                  onChange={(e) => setInviteForm({ ...inviteForm, permissions: { ...inviteForm.permissions, can_white_label: e.target.checked } })}
                  className="rounded border-gray-300 dark:border-gray-600"
                />
                Can remove SmoothSchedule branding
              </label>
              <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
                <input
                  type="checkbox"
                  checked={inviteForm.permissions.can_api_access}
                  onChange={(e) => setInviteForm({ ...inviteForm, permissions: { ...inviteForm.permissions, can_api_access: e.target.checked } })}
                  className="rounded border-gray-300 dark:border-gray-600"
                />
                Can access API for integrations
              </label>
            </div>
          </div>

          {/* Feature Limits & Capabilities */}
          <div className="border-t border-gray-200 dark:border-gray-700 pt-6">
            <div className="flex items-center justify-between mb-3">
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                Feature Limits & Capabilities
              </label>
            </div>
            <div className="space-y-3">
              {/* Video Conferencing */}
              <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
                <input
                  type="checkbox"
                  checked={inviteForm.limits.can_add_video_conferencing}
                  onChange={(e) => setInviteForm({ ...inviteForm, limits: { ...inviteForm.limits, can_add_video_conferencing: e.target.checked } })}
                  className="rounded border-gray-300 dark:border-gray-600"
                />
                Can add video conferencing to events
              </label>

              {/* Event Types Limit */}
              <div className="flex items-start gap-3">
                <input
                  type="checkbox"
                  checked={inviteForm.limits.max_event_types === null}
                  onChange={(e) => setInviteForm({ ...inviteForm, limits: { ...inviteForm.limits, max_event_types: e.target.checked ? null : 10 } })}
                  className="rounded border-gray-300 dark:border-gray-600 mt-1"
                />
                <div className="flex-1">
                  <div className="flex items-center gap-2">
                    <span className="text-sm text-gray-700 dark:text-gray-300">Unlimited event types</span>
                  </div>
                  <input
                    type="number"
                    min="1"
                    disabled={inviteForm.limits.max_event_types === null}
                    value={inviteForm.limits.max_event_types || ''}
                    onChange={(e) => setInviteForm({ ...inviteForm, limits: { ...inviteForm.limits, max_event_types: e.target.value ? parseInt(e.target.value) : null } })}
                    placeholder="Or set a limit"
                    className="mt-1 w-32 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:opacity-50 disabled:cursor-not-allowed"
                  />
                </div>
              </div>

              {/* Calendars Connected Limit */}
              <div className="flex items-start gap-3">
                <input
                  type="checkbox"
                  checked={inviteForm.limits.max_calendars_connected === null}
                  onChange={(e) => setInviteForm({ ...inviteForm, limits: { ...inviteForm.limits, max_calendars_connected: e.target.checked ? null : 5 } })}
                  className="rounded border-gray-300 dark:border-gray-600 mt-1"
                />
                <div className="flex-1">
                  <div className="flex items-center gap-2">
                    <span className="text-sm text-gray-700 dark:text-gray-300">Unlimited calendar connections</span>
                  </div>
                  <input
                    type="number"
                    min="1"
                    disabled={inviteForm.limits.max_calendars_connected === null}
                    value={inviteForm.limits.max_calendars_connected || ''}
                    onChange={(e) => setInviteForm({ ...inviteForm, limits: { ...inviteForm.limits, max_calendars_connected: e.target.value ? parseInt(e.target.value) : null } })}
                    placeholder="Or set a limit"
                    className="mt-1 w-32 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:opacity-50 disabled:cursor-not-allowed"
                  />
                </div>
              </div>

              {/* API Access */}
              <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
                <input
                  type="checkbox"
                  checked={inviteForm.limits.can_connect_to_api}
                  onChange={(e) => setInviteForm({ ...inviteForm, limits: { ...inviteForm.limits, can_connect_to_api: e.target.checked } })}
                  className="rounded border-gray-300 dark:border-gray-600"
                />
                Can connect to external APIs
              </label>

              {/* Repeated Events */}
              <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
                <input
                  type="checkbox"
                  checked={inviteForm.limits.can_book_repeated_events}
                  onChange={(e) => setInviteForm({ ...inviteForm, limits: { ...inviteForm.limits, can_book_repeated_events: e.target.checked } })}
                  className="rounded border-gray-300 dark:border-gray-600"
                />
                Can book repeated/recurring events
              </label>

              {/* 2FA */}
              <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
                <input
                  type="checkbox"
                  checked={inviteForm.limits.can_require_2fa}
                  onChange={(e) => setInviteForm({ ...inviteForm, limits: { ...inviteForm.limits, can_require_2fa: e.target.checked } })}
                  className="rounded border-gray-300 dark:border-gray-600"
                />
                Can require 2FA for users
              </label>

              {/* Download Logs */}
              <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
                <input
                  type="checkbox"
                  checked={inviteForm.limits.can_download_logs}
                  onChange={(e) => setInviteForm({ ...inviteForm, limits: { ...inviteForm.limits, can_download_logs: e.target.checked } })}
                  className="rounded border-gray-300 dark:border-gray-600"
                />
                Can download system logs
              </label>

              {/* Delete Data */}
              <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
                <input
                  type="checkbox"
                  checked={inviteForm.limits.can_delete_data}
                  onChange={(e) => setInviteForm({ ...inviteForm, limits: { ...inviteForm.limits, can_delete_data: e.target.checked } })}
                  className="rounded border-gray-300 dark:border-gray-600"
                />
                Can permanently delete data
              </label>

              {/* Masked Phone Numbers */}
              <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
                <input
                  type="checkbox"
                  checked={inviteForm.limits.can_use_masked_phone_numbers}
                  onChange={(e) => setInviteForm({ ...inviteForm, limits: { ...inviteForm.limits, can_use_masked_phone_numbers: e.target.checked } })}
                  className="rounded border-gray-300 dark:border-gray-600"
                />
                Can use masked phone numbers for privacy
              </label>

              {/* POS Integration */}
              <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
                <input
                  type="checkbox"
                  checked={inviteForm.limits.can_use_pos}
                  onChange={(e) => setInviteForm({ ...inviteForm, limits: { ...inviteForm.limits, can_use_pos: e.target.checked } })}
                  className="rounded border-gray-300 dark:border-gray-600"
                />
                Can use Point of Sale (POS) system
              </label>

              {/* Mobile App */}
              <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
                <input
                  type="checkbox"
                  checked={inviteForm.limits.can_use_mobile_app}
                  onChange={(e) => setInviteForm({ ...inviteForm, limits: { ...inviteForm.limits, can_use_mobile_app: e.target.checked } })}
                  className="rounded border-gray-300 dark:border-gray-600"
                />
                Can use mobile app
              </label>
            </div>
          </div>

          {/* Personal Message */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Personal Message (Optional)
            </label>
            <textarea
              value={inviteForm.personal_message}
              onChange={(e) => setInviteForm({ ...inviteForm, personal_message: e.target.value })}
              rows={3}
              className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
              placeholder="Add a personal note to the invitation email..."
            />
          </div>
        </div>

        {/* Modal Footer */}
        <div className="flex items-center justify-end gap-3 p-6 border-t border-gray-200 dark:border-gray-700">
          <button
            onClick={handleClose}
            className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg font-medium text-sm transition-colors"
          >
            Cancel
          </button>
          <button
            onClick={handleInviteSend}
            disabled={createInvitationMutation.isPending || inviteSuccess}
            className="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 font-medium text-sm transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <Send size={16} />
            {createInvitationMutation.isPending ? 'Sending...' : inviteSuccess ? 'Sent!' : 'Send Invitation'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default TenantInviteModal;
