import React, { useState } from 'react';
import { X, Plus, Building2, Key, User, Mail, Lock } from 'lucide-react';
import { useCreateBusiness } from '../../../hooks/usePlatform';
import { getBaseDomain } from '../../../utils/domain';

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

const BusinessCreateModal: React.FC<BusinessCreateModalProps> = ({ isOpen, onClose }) => {
  const createBusinessMutation = useCreateBusiness();

  const [createForm, setCreateForm] = useState({
    name: '',
    subdomain: '',
    subscription_tier: 'FREE',
    is_active: true,
    max_users: 5,
    max_resources: 10,
    max_pages: 1,
    contact_email: '',
    phone: '',
    can_manage_oauth_credentials: false,
    // Owner fields
    create_owner: false,
    owner_email: '',
    owner_name: '',
    owner_password: '',
  });
  const [createError, setCreateError] = useState<string | null>(null);

  const resetForm = () => {
    setCreateForm({
      name: '',
      subdomain: '',
      subscription_tier: 'FREE',
      is_active: true,
      max_users: 5,
      max_resources: 10,
      max_pages: 1,
      contact_email: '',
      phone: '',
      can_manage_oauth_credentials: false,
      create_owner: false,
      owner_email: '',
      owner_name: '',
      owner_password: '',
    });
    setCreateError(null);
  };

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

  const handleCreateSave = () => {
    setCreateError(null);

    // Basic validation
    if (!createForm.name.trim()) {
      setCreateError('Business name is required');
      return;
    }
    if (!createForm.subdomain.trim()) {
      setCreateError('Subdomain is required');
      return;
    }
    if (createForm.create_owner) {
      if (!createForm.owner_email.trim()) {
        setCreateError('Owner email is required');
        return;
      }
      if (!createForm.owner_name.trim()) {
        setCreateError('Owner name is required');
        return;
      }
      if (!createForm.owner_password.trim()) {
        setCreateError('Owner password is required');
        return;
      }
      if (createForm.owner_password.length < 8) {
        setCreateError('Password must be at least 8 characters');
        return;
      }
    }

    const data: any = {
      name: createForm.name,
      subdomain: createForm.subdomain,
      subscription_tier: createForm.subscription_tier,
      is_active: createForm.is_active,
      max_users: createForm.max_users,
      max_resources: createForm.max_resources,
      max_pages: createForm.max_pages,
      can_manage_oauth_credentials: createForm.can_manage_oauth_credentials,
    };

    if (createForm.contact_email) {
      data.contact_email = createForm.contact_email;
    }
    if (createForm.phone) {
      data.phone = createForm.phone;
    }
    if (createForm.create_owner) {
      data.owner_email = createForm.owner_email;
      data.owner_name = createForm.owner_name;
      data.owner_password = createForm.owner_password;
    }

    createBusinessMutation.mutate(data, {
      onSuccess: () => {
        handleClose();
      },
      onError: (error: any) => {
        const errorMessage = error?.response?.data?.subdomain?.[0]
          || error?.response?.data?.owner_email?.[0]
          || error?.response?.data?.detail
          || error?.message
          || 'Failed to create business';
        setCreateError(errorMessage);
      },
    });
  };

  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-4 border-b border-gray-200 dark:border-gray-700">
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
            <Building2 size={20} className="text-indigo-500" />
            Create New Business
          </h3>
          <button
            onClick={handleClose}
            className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200"
          >
            <X size={20} />
          </button>
        </div>

        {/* Modal Body */}
        <div className="p-4 space-y-4">
          {/* Error Message */}
          {createError && (
            <div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-red-700 dark:text-red-300 text-sm">
              {createError}
            </div>
          )}

          {/* Business Details Section */}
          <div className="space-y-4">
            <h4 className="text-sm font-semibold text-gray-900 dark:text-white flex items-center gap-2">
              <Building2 size={16} className="text-indigo-500" />
              Business Details
            </h4>

            {/* Business Name */}
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Business Name <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                value={createForm.name}
                onChange={(e) => setCreateForm({ ...createForm, name: e.target.value })}
                placeholder="My Awesome Business"
                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 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              />
            </div>

            {/* Subdomain */}
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Subdomain <span className="text-red-500">*</span>
              </label>
              <div className="flex items-center">
                <input
                  type="text"
                  value={createForm.subdomain}
                  onChange={(e) => setCreateForm({ ...createForm, subdomain: e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, '') })}
                  placeholder="mybusiness"
                  className="flex-1 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-l-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                />
                <span className="px-3 py-2 bg-gray-100 dark:bg-gray-600 border border-l-0 border-gray-300 dark:border-gray-600 rounded-r-lg text-gray-500 dark:text-gray-400 text-sm">
                  .{getBaseDomain()}
                </span>
              </div>
              <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                Only lowercase letters, numbers, and hyphens. Must start with a letter.
              </p>
            </div>

            {/* Contact Info */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Contact Email
                </label>
                <input
                  type="email"
                  value={createForm.contact_email}
                  onChange={(e) => setCreateForm({ ...createForm, contact_email: e.target.value })}
                  placeholder="contact@business.com"
                  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 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Phone
                </label>
                <input
                  type="tel"
                  value={createForm.phone}
                  onChange={(e) => setCreateForm({ ...createForm, phone: e.target.value })}
                  placeholder="+1 (555) 123-4567"
                  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 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                />
              </div>
            </div>

            {/* Status */}
            <div className="flex items-center justify-between">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                  Active Status
                </label>
                <p className="text-xs text-gray-500 dark:text-gray-400">
                  Create business as active
                </p>
              </div>
              <button
                type="button"
                onClick={() => setCreateForm({ ...createForm, is_active: !createForm.is_active })}
                className={`${createForm.is_active ? 'bg-green-600' : 'bg-gray-300 dark:bg-gray-600'} relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-indigo-500`}
                role="switch"
              >
                <span className={`${createForm.is_active ? 'translate-x-5' : 'translate-x-0'} pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out`} />
              </button>
            </div>

            {/* Subscription Tier */}
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Subscription Tier
              </label>
              <select
                value={createForm.subscription_tier}
                onChange={(e) => setCreateForm({ ...createForm, subscription_tier: e.target.value })}
                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 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              >
                <option value="FREE">Free Trial</option>
                <option value="STARTER">Starter</option>
                <option value="PROFESSIONAL">Professional</option>
                <option value="ENTERPRISE">Enterprise</option>
              </select>
            </div>

            {/* Limits */}
            <div className="grid grid-cols-3 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Max Users
                </label>
                <input
                  type="number"
                  min="1"
                  value={createForm.max_users}
                  onChange={(e) => setCreateForm({ ...createForm, max_users: parseInt(e.target.value) || 1 })}
                  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 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Max Resources
                </label>
                <input
                  type="number"
                  min="1"
                  value={createForm.max_resources}
                  onChange={(e) => setCreateForm({ ...createForm, max_resources: parseInt(e.target.value) || 1 })}
                  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 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Max Pages
                </label>
                <input
                  type="number"
                  min="1"
                  value={createForm.max_pages}
                  onChange={(e) => setCreateForm({ ...createForm, max_pages: parseInt(e.target.value) || 1 })}
                  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 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                />
              </div>
            </div>
          </div>

          {/* Permissions Section */}
          <div className="pt-4 border-t border-gray-200 dark:border-gray-700">
            <h4 className="text-sm font-semibold text-gray-900 dark:text-white mb-3 flex items-center gap-2">
              <Key size={16} className="text-purple-500" />
              Platform Permissions
            </h4>

            {/* Can Manage OAuth Credentials */}
            <div className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-900/50 rounded-lg">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                  Manage OAuth Credentials
                </label>
                <p className="text-xs text-gray-500 dark:text-gray-400">
                  Allow this business to configure their own OAuth app credentials
                </p>
              </div>
              <button
                type="button"
                onClick={() => setCreateForm({ ...createForm, can_manage_oauth_credentials: !createForm.can_manage_oauth_credentials })}
                className={`${createForm.can_manage_oauth_credentials ? 'bg-purple-600' : 'bg-gray-300 dark:bg-gray-600'} relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-purple-500`}
                role="switch"
              >
                <span className={`${createForm.can_manage_oauth_credentials ? 'translate-x-5' : 'translate-x-0'} pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out`} />
              </button>
            </div>
          </div>

          {/* Owner Section */}
          <div className="pt-4 border-t border-gray-200 dark:border-gray-700">
            <div className="flex items-center justify-between mb-3">
              <h4 className="text-sm font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                <User size={16} className="text-blue-500" />
                Create Owner Account
              </h4>
              <button
                type="button"
                onClick={() => setCreateForm({ ...createForm, create_owner: !createForm.create_owner })}
                className={`${createForm.create_owner ? 'bg-blue-600' : 'bg-gray-300 dark:bg-gray-600'} relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-blue-500`}
                role="switch"
              >
                <span className={`${createForm.create_owner ? 'translate-x-5' : 'translate-x-0'} pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out`} />
              </button>
            </div>

            {createForm.create_owner && (
              <div className="space-y-3 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    <Mail size={14} className="inline mr-1" />
                    Owner Email <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="email"
                    value={createForm.owner_email}
                    onChange={(e) => setCreateForm({ ...createForm, owner_email: e.target.value })}
                    placeholder="owner@business.com"
                    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 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    <User size={14} className="inline mr-1" />
                    Owner Name <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    value={createForm.owner_name}
                    onChange={(e) => setCreateForm({ ...createForm, owner_name: e.target.value })}
                    placeholder="John Doe"
                    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 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    <Lock size={14} className="inline mr-1" />
                    Password <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="password"
                    value={createForm.owner_password}
                    onChange={(e) => setCreateForm({ ...createForm, owner_password: e.target.value })}
                    placeholder="Min. 8 characters"
                    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 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
              </div>
            )}

            {!createForm.create_owner && (
              <p className="text-xs text-gray-500 dark:text-gray-400">
                You can create an owner account later or invite one via email.
              </p>
            )}
          </div>
        </div>

        {/* Modal Footer */}
        <div className="flex items-center justify-end gap-3 p-4 border-t border-gray-200 dark:border-gray-700">
          <button
            onClick={handleClose}
            className="px-4 py-2 text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 font-medium text-sm transition-colors"
          >
            Cancel
          </button>
          <button
            onClick={handleCreateSave}
            disabled={createBusinessMutation.isPending}
            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"
          >
            <Plus size={16} />
            {createBusinessMutation.isPending ? 'Creating...' : 'Create Business'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default BusinessCreateModal;
