import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Eye, ShieldCheck, Ban, Pencil, Send, ChevronDown, ChevronRight, Building2, Check, Trash2 } from 'lucide-react';
import { useBusinesses, useUpdateBusiness, useDeleteBusiness } from '../../hooks/usePlatform';
import { PlatformBusiness, verifyUserEmail } from '../../api/platform';
import TenantInviteModal from './components/TenantInviteModal';
import { getBaseDomain } from '../../utils/domain';
import PlatformListing from './components/PlatformListing';
import PlatformTable from './components/PlatformTable';
import PlatformListRow from './components/PlatformListRow';
import EditPlatformEntityModal from './components/EditPlatformEntityModal';
import ConfirmationModal from '../../components/ConfirmationModal';
import { useQueryClient } from '@tanstack/react-query';

interface PlatformBusinessesProps {
  onMasquerade: (targetUser: { id: number; username?: string; name?: string; email?: string; role?: string }) => void;
}

const PlatformBusinesses: React.FC<PlatformBusinessesProps> = ({ onMasquerade }) => {
  const { t } = useTranslation();
  const queryClient = useQueryClient();
  const [searchTerm, setSearchTerm] = useState('');
  const { data: businesses, isLoading, error } = useBusinesses();

  // Modal states
  const [showInviteModal, setShowInviteModal] = useState(false);
  const [editingBusiness, setEditingBusiness] = useState<PlatformBusiness | null>(null);
  const [showInactiveBusinesses, setShowInactiveBusinesses] = useState(false);
  const [verifyEmailUser, setVerifyEmailUser] = useState<{ id: number; email: string; name: string } | null>(null);
  const [isVerifying, setIsVerifying] = useState(false);
  const [deletingBusiness, setDeletingBusiness] = useState<PlatformBusiness | null>(null);

  // Mutations
  const deleteBusinessMutation = useDeleteBusiness();

  // Filter and separate businesses
  const filteredBusinesses = (businesses || []).filter(b =>
    b.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    b.subdomain.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const activeBusinesses = filteredBusinesses.filter(b => b.is_active);
  const inactiveBusinesses = filteredBusinesses.filter(b => !b.is_active);

  const handleLoginAs = (business: PlatformBusiness) => {
    if (business.owner) {
      onMasquerade({
        id: business.owner.id,
        username: business.owner.username,
        name: business.owner.full_name,
        email: business.owner.email,
        role: business.owner.role,
      });
    }
  };

  const handleVerifyEmailClick = (userId: number, email: string, name: string) => {
    setVerifyEmailUser({ id: userId, email, name });
  };

  const handleVerifyEmailConfirm = async () => {
    if (!verifyEmailUser) return;

    setIsVerifying(true);
    try {
      await verifyUserEmail(verifyEmailUser.id);
      queryClient.invalidateQueries({ queryKey: ['platform', 'businesses'] });
      setVerifyEmailUser(null);
    } catch (error) {
      alert(t('errors.generic'));
    } finally {
      setIsVerifying(false);
    }
  };

  const handleDeleteConfirm = async () => {
    if (!deletingBusiness) return;

    try {
      await deleteBusinessMutation.mutateAsync(deletingBusiness.id);
      setDeletingBusiness(null);
    } catch (error) {
      alert(t('errors.generic'));
    }
  };

  // Helper to render business row
  const renderBusinessRow = (business: PlatformBusiness) => (
    <PlatformListRow
      key={business.id}
      avatarLetter={(business.owner?.username || business.name).charAt(0).toUpperCase()}
      primaryText={business.owner?.username || business.name}
      secondaryText={business.name}
      badgeText={business.tier || 'tenant owner'}
      badgeColor="bg-gray-100 text-gray-800"
      tertiaryText={business.owner?.email || '-'}
      actions={
        <>
          {business.owner && !business.owner.email_verified && (
            <button
              onClick={() => handleVerifyEmailClick(
                business.owner!.id,
                business.owner!.email,
                business.owner!.full_name || business.owner!.username || business.name
              )}
              className="text-green-600 hover:text-green-500 dark:text-green-400 dark:hover:text-green-300 font-medium text-xs inline-flex items-center gap-1 px-3 py-1 border border-green-200 dark:border-green-800 rounded-lg hover:bg-green-50 dark:hover:bg-green-900/30 transition-colors"
              title={t('platform.verifyEmail')}
            >
              <Check size={14} /> {t('platform.verify')}
            </button>
          )}
          {business.owner && (
            <button
              onClick={() => handleLoginAs(business)}
              className="text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-300 font-medium text-xs inline-flex items-center gap-1 px-3 py-1 border border-indigo-200 dark:border-indigo-800 rounded-lg hover:bg-indigo-50 dark:hover:bg-indigo-900/30 transition-colors"
              title={t('platform.masqueradeAs') + ' ' + business.owner.email}
            >
              <Eye size={14} />
              {t('common.masquerade')}
            </button>
          )}
          <button
            onClick={() => setEditingBusiness(business)}
            className="text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-300 font-medium text-xs inline-flex items-center gap-1 px-3 py-1 border border-indigo-200 dark:border-indigo-800 rounded-lg hover:bg-indigo-50 dark:hover:bg-indigo-900/30 transition-colors"
            title={t('common.edit')}
          >
            <Pencil size={14} /> {t('common.edit')}
          </button>
          <button
            onClick={() => setDeletingBusiness(business)}
            className="text-red-600 hover:text-red-500 dark:text-red-400 dark:hover:text-red-300 font-medium text-xs inline-flex items-center gap-1 px-3 py-1 border border-red-200 dark:border-red-800 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/30 transition-colors"
            title={t('common.delete')}
          >
            <Trash2 size={14} /> {t('common.delete')}
          </button>
        </>
      }
    />
  );

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-gray-500 dark:text-gray-400">{t('common.loading')}</div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-red-500">{t('errors.generic')}</div>
      </div>
    );
  }

  return (
    <div className="space-y-6">


      <PlatformListing
        title={t('platform.businesses')}
        description={t('platform.businessesDescription')}
        isLoading={isLoading}
        error={error}
        data={activeBusinesses}
        renderRow={renderBusinessRow}
        columns={[
          t('platform.businessName'), // Reusing label but mapping to Owner/Business Name column
          t('platform.tier'),
          t('platform.owner'), // Mapping to Email column
          t('common.actions')
        ]}
        searchPlaceholder={t('platform.searchBusinesses')}
        searchTerm={searchTerm}
        onSearchChange={setSearchTerm}
        actionButton={
          <button
            onClick={() => setShowInviteModal(true)}
            className="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 font-medium shadow-sm"
          >
            <Send size={18} />
            {t('platform.inviteTenant')}
          </button>
        }
        emptyMessage={searchTerm ? t('platform.noBusinessesFound') : t('platform.noBusinesses')}
        extraContent={
          inactiveBusinesses.length > 0 ? (
            <div className="bg-gray-100 dark:bg-gray-800/50 rounded-xl border border-gray-200 dark:border-gray-700">
              <button
                onClick={() => setShowInactiveBusinesses(!showInactiveBusinesses)}
                className="w-full px-4 py-3 flex items-center justify-between text-left hover:bg-gray-200 dark:hover:bg-gray-700/50 rounded-xl transition-colors"
              >
                <div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
                  {showInactiveBusinesses ? <ChevronDown size={18} /> : <ChevronRight size={18} />}
                  <Building2 size={18} />
                  <span className="font-medium">
                    {t('platform.inactiveBusinesses', { count: inactiveBusinesses.length })}
                  </span>
                </div>
              </button>

              {showInactiveBusinesses && (
                <div className="border-t border-gray-200 dark:border-gray-700">
                  <PlatformTable
                    data={inactiveBusinesses}
                    columns={[
                      t('platform.businessName'),
                      t('platform.tier'),
                      t('platform.owner'),
                      t('common.actions')
                    ]}
                    renderRow={renderBusinessRow}
                    className=""
                  />
                </div>
              )}
            </div>
          ) : null
        }
      />

      {/* Modals */}
      <TenantInviteModal
        isOpen={showInviteModal}
        onClose={() => setShowInviteModal(false)}
      />
      <EditPlatformEntityModal
        entity={editingBusiness}
        type="business"
        isOpen={!!editingBusiness}
        onClose={() => setEditingBusiness(null)}
      />
      <ConfirmationModal
        isOpen={!!verifyEmailUser}
        onClose={() => setVerifyEmailUser(null)}
        onConfirm={handleVerifyEmailConfirm}
        title={t('platform.verifyEmail')}
        message={
          <div className="space-y-3">
            <p>{t('platform.confirmVerifyEmailMessage')}</p>
            {verifyEmailUser && (
              <div className="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-3">
                <p className="font-medium text-gray-900 dark:text-white">{verifyEmailUser.name}</p>
                <p className="text-sm text-gray-500 dark:text-gray-400">{verifyEmailUser.email}</p>
              </div>
            )}
            <p className="text-sm text-gray-500 dark:text-gray-400">
              {t('platform.verifyEmailNote')}
            </p>
          </div>
        }
        confirmText={t('platform.verify')}
        cancelText={t('common.cancel')}
        variant="success"
        isLoading={isVerifying}
      />
      <ConfirmationModal
        isOpen={!!deletingBusiness}
        onClose={() => setDeletingBusiness(null)}
        onConfirm={handleDeleteConfirm}
        title={t('platform.deleteTenant')}
        message={
          <div className="space-y-3">
            <p>{t('platform.confirmDeleteTenantMessage')}</p>
            {deletingBusiness && (
              <div className="bg-red-50 dark:bg-red-900/20 rounded-lg p-3 border border-red-200 dark:border-red-800">
                <p className="font-medium text-gray-900 dark:text-white">{deletingBusiness.name}</p>
                <p className="text-sm text-gray-500 dark:text-gray-400">{deletingBusiness.subdomain}.smoothschedule.com</p>
                {deletingBusiness.owner && (
                  <p className="text-sm text-gray-500 dark:text-gray-400">{deletingBusiness.owner.email}</p>
                )}
              </div>
            )}
            <p className="text-sm text-red-600 dark:text-red-400 font-medium">
              {t('platform.deleteTenantWarning')}
            </p>
          </div>
        }
        confirmText={t('common.delete')}
        cancelText={t('common.cancel')}
        variant="danger"
        isLoading={deleteBusinessMutation.isPending}
      />
    </div>
  );
};

export default PlatformBusinesses;
