
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Search, Filter, MoreHorizontal, Eye, ShieldCheck, Ban } from 'lucide-react';
import { User } from '../../types';
import { useBusinesses } from '../../hooks/usePlatform';

interface PlatformBusinessesProps {
  onMasquerade: (targetUser: User) => void;
}

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

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

  const handleLoginAs = (business: any) => {
    // Use the owner data from the API response
    if (business.owner) {
      const targetOwner: User = {
        id: business.owner.id.toString(),
        username: business.owner.username,
        name: business.owner.name,
        email: business.owner.email,
        role: business.owner.role,
        business_id: business.id.toString(),
        business_subdomain: business.subdomain,
        is_active: true,
        is_staff: false,
        is_superuser: false,
      };
      onMasquerade(targetOwner);
    }
  };

  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">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white">{t('platform.businesses')}</h2>
          <p className="text-gray-500 dark:text-gray-400">{t('platform.businessesDescription')}</p>
        </div>
        <button className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 font-medium shadow-sm">
          {t('platform.addNewTenant')}
        </button>
      </div>

      <div className="flex items-center gap-4 bg-white dark:bg-gray-800 p-4 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={18} />
          <input
            type="text"
            placeholder={t('platform.searchBusinesses')}
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2 bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
          />
        </div>
        <button className="flex items-center gap-2 px-4 py-2 text-gray-700 dark:text-gray-200 bg-gray-50 dark:bg-gray-700 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-600 border border-gray-200 dark:border-gray-600">
          <Filter size={16} /> {t('common.filter')}
        </button>
      </div>

      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm overflow-hidden">
        <table className="w-full text-sm text-left">
          <thead className="text-xs text-gray-500 dark:text-gray-400 uppercase bg-gray-50 dark:bg-gray-900/50 border-b border-gray-200 dark:border-gray-700">
            <tr>
              <th className="px-6 py-4 font-medium">{t('platform.businessName')}</th>
              <th className="px-6 py-4 font-medium">{t('platform.subdomain')}</th>
              <th className="px-6 py-4 font-medium">{t('platform.plan')}</th>
              <th className="px-6 py-4 font-medium">{t('platform.status')}</th>
              <th className="px-6 py-4 font-medium">{t('platform.joined')}</th>
              <th className="px-6 py-4 font-medium text-right">{t('common.actions')}</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100 dark:divide-gray-700">
            {filteredBusinesses.map((biz) => {
              const tierDisplay = biz.tier.charAt(0).toUpperCase() + biz.tier.slice(1).toLowerCase();
              const statusDisplay = biz.is_active ? 'Active' : 'Inactive';

              return (
                <tr key={biz.id} className="hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors">
                  <td className="px-6 py-4 font-medium text-gray-900 dark:text-white">
                    <div className="flex items-center gap-3">
                      <div className="w-8 h-8 rounded bg-gray-100 dark:bg-gray-700 flex items-center justify-center font-bold text-xs text-indigo-600">
                          {biz.name.substring(0, 2).toUpperCase()}
                      </div>
                      {biz.name}
                    </div>
                  </td>
                  <td className="px-6 py-4 text-gray-500 dark:text-gray-400 font-mono text-xs">
                    {biz.subdomain}.smoothschedule.com
                  </td>
                  <td className="px-6 py-4">
                    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
                      ${biz.tier === 'ENTERPRISE' ? 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300' :
                        biz.tier === 'BUSINESS' ? 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300' :
                        biz.tier === 'PROFESSIONAL' ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300' :
                        'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'}
                    `}>
                      {tierDisplay}
                    </span>
                  </td>
                  <td className="px-6 py-4">
                     <div className="flex items-center gap-2">
                      {biz.is_active && <ShieldCheck size={16} className="text-green-500" />}
                      {!biz.is_active && <Ban size={16} className="text-red-500" />}
                      <span className="text-gray-700 dark:text-gray-300">{statusDisplay}</span>
                     </div>
                  </td>
                  <td className="px-6 py-4 text-gray-500 dark:text-gray-400">
                    {new Date(biz.created_at).toLocaleDateString()}
                  </td>
                  <td className="px-6 py-4 text-right">
                    <button
                      onClick={() => handleLoginAs(biz)}
                      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 mr-2"
                      disabled={!biz.owner}
                      title={!biz.owner ? 'No owner assigned' : `Masquerade as ${biz.owner.name}`}
                    >
                      <Eye size={14} /> {t('platform.masquerade')}
                    </button>
                    <button className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200">
                      <MoreHorizontal size={18} />
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default PlatformBusinesses;