'use client';

import { useState, useCallback } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useRouter, useParams } from 'next/navigation';
import { useTranslation } from 'react-i18next';
import { apiClient } from '@/infrastructure/api/api-client';
import { queryKeys } from '@/infrastructure/api/query-keys';
import { cn } from '@/lib/utils';

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

interface TenantDetail {
  id: string;
  name: string;
  slug: string;
  schemaName: string;
  plan: 'free' | 'pro' | 'enterprise';
  status: 'active' | 'suspended';
  memberCount: number;
  createdAt: string;
  updatedAt: string;
}

interface TenantMember {
  id: string;
  email: string;
  name: string;
  role: 'owner' | 'admin' | 'member' | 'viewer';
  joinedAt: string;
}

type TenantMembersResponse = TenantMember[];

interface TenantInvite {
  id: string;
  email: string;
  role: string;
  status: 'pending' | 'accepted' | 'expired' | 'revoked';
  expiresAt: string;
  invitedBy: string | null;
  createdAt: string;
}

interface TenantFormData {
  name: string;
  plan: TenantDetail['plan'];
  status: TenantDetail['status'];
}

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

const PLAN_STYLES: Record<TenantDetail['plan'], string> = {
  free: 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300',
  pro: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
  enterprise: 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400',
};

const STATUS_STYLES: Record<TenantDetail['status'], string> = {
  active: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
  suspended: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
};

const ROLE_STYLES: Record<TenantMember['role'], string> = {
  owner: 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400',
  admin: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
  member: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
  viewer: 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300',
};

// ---------------------------------------------------------------------------
// Badge components
// ---------------------------------------------------------------------------

function PlanBadge({ plan }: { plan: TenantDetail['plan'] }) {
  return (
    <span
      className={cn(
        'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium capitalize',
        PLAN_STYLES[plan],
      )}
    >
      {plan}
    </span>
  );
}

function StatusBadge({ status }: { status: TenantDetail['status'] }) {
  return (
    <span
      className={cn(
        'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium capitalize',
        STATUS_STYLES[status],
      )}
    >
      {status}
    </span>
  );
}

function RoleBadge({ role }: { role: TenantMember['role'] }) {
  return (
    <span
      className={cn(
        'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium capitalize',
        ROLE_STYLES[role],
      )}
    >
      {role}
    </span>
  );
}

// ---------------------------------------------------------------------------
// Delete confirmation dialog
// ---------------------------------------------------------------------------

function DeleteDialog({
  open,
  name,
  deleting,
  onClose,
  onConfirm,
}: {
  open: boolean;
  name: string;
  deleting: boolean;
  onClose: () => void;
  onConfirm: () => void;
}) {
  const { t } = useTranslation('tenants');
  const { t: tc } = useTranslation('common');

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      <div className="relative z-10 w-full max-w-sm bg-card border rounded-lg shadow-lg p-6 mx-4">
        <h2 className="text-lg font-semibold mb-2">{t('detail.deleteDialog.title')}</h2>
        <p className="text-sm text-muted-foreground mb-6">
          {t('detail.deleteDialog.message')}
        </p>
        <div className="flex justify-end gap-3">
          <button
            onClick={onClose}
            className="px-4 py-2 text-sm rounded-md border border-input hover:bg-accent"
            disabled={deleting}
          >
            {tc('cancel')}
          </button>
          <button
            onClick={onConfirm}
            disabled={deleting}
            className="px-4 py-2 text-sm rounded-md bg-destructive text-destructive-foreground hover:bg-destructive/90 disabled:opacity-50"
          >
            {deleting ? tc('deleting') : tc('delete')}
          </button>
        </div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Helper: format date
// ---------------------------------------------------------------------------

function formatDate(dateStr: string): string {
  try {
    return new Date(dateStr).toLocaleString();
  } catch {
    return dateStr;
  }
}

function formatRelative(dateStr: string): string {
  try {
    const diff = Date.now() - new Date(dateStr).getTime();
    const seconds = Math.floor(diff / 1000);
    if (seconds < 60) return `${seconds}s ago`;
    const minutes = Math.floor(seconds / 60);
    if (minutes < 60) return `${minutes}m ago`;
    const hours = Math.floor(minutes / 60);
    if (hours < 24) return `${hours}h ago`;
    const days = Math.floor(hours / 24);
    return `${days}d ago`;
  } catch {
    return dateStr;
  }
}

// ---------------------------------------------------------------------------
// Info row component
// ---------------------------------------------------------------------------

function InfoRow({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <div className="flex flex-col sm:flex-row sm:items-start gap-1 sm:gap-4 py-2">
      <dt className="text-sm text-muted-foreground sm:w-36 shrink-0">{label}</dt>
      <dd className="text-sm font-medium">{value || '--'}</dd>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Main page component
// ---------------------------------------------------------------------------

export default function TenantDetailPage() {
  const { t } = useTranslation('tenants');
  const { t: tc } = useTranslation('common');
  const router = useRouter();
  const params = useParams();
  const queryClient = useQueryClient();
  const id = params.id as string;

  // State ----------------------------------------------------------------
  const [isEditing, setIsEditing] = useState(false);
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [showInviteForm, setShowInviteForm] = useState(false);
  const [inviteEmail, setInviteEmail] = useState('');
  const [inviteRole, setInviteRole] = useState('viewer');
  const [inviteLink, setInviteLink] = useState<string | null>(null);
  const [linkCopied, setLinkCopied] = useState(false);
  const [form, setForm] = useState<TenantFormData>({
    name: '',
    plan: 'free',
    status: 'active',
  });
  const [errors, setErrors] = useState<Partial<Record<keyof TenantFormData, string>>>({});

  // Queries --------------------------------------------------------------
  const {
    data: tenant,
    isLoading,
    error,
  } = useQuery({
    queryKey: queryKeys.tenants.detail(id),
    queryFn: () => apiClient<TenantDetail>(`/api/v1/admin/tenants/${id}`),
    enabled: !!id,
  });

  const { data: membersData } = useQuery({
    queryKey: [...queryKeys.tenants.detail(id), 'members'],
    queryFn: () =>
      apiClient<TenantMembersResponse>(
        `/api/v1/admin/tenants/${id}/members`,
      ),
    enabled: !!id,
  });

  const members = Array.isArray(membersData) ? membersData : [];

  const { data: invites = [] } = useQuery({
    queryKey: queryKeys.tenants.invites(id),
    queryFn: () => apiClient<TenantInvite[]>(`/api/v1/admin/tenants/${id}/invites`),
    enabled: !!id,
  });

  // Mutations ------------------------------------------------------------
  const updateMutation = useMutation({
    mutationFn: (body: Record<string, unknown>) =>
      apiClient<TenantDetail>(`/api/v1/admin/tenants/${id}`, {
        method: 'PUT',
        body,
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.tenants.detail(id) });
      queryClient.invalidateQueries({ queryKey: queryKeys.tenants.all });
      setIsEditing(false);
    },
  });

  const deleteMutation = useMutation({
    mutationFn: () =>
      apiClient<void>(`/api/v1/admin/tenants/${id}`, { method: 'DELETE' }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.tenants.all });
      router.push('/tenants');
    },
  });

  const suspendMutation = useMutation({
    mutationFn: (status: TenantDetail['status']) =>
      apiClient<TenantDetail>(`/api/v1/admin/tenants/${id}`, {
        method: 'PATCH',
        body: { status },
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.tenants.detail(id) });
      queryClient.invalidateQueries({ queryKey: queryKeys.tenants.all });
    },
  });

  const sendInviteMutation = useMutation({
    mutationFn: (body: { email: string; role: string }) =>
      apiClient<{ token: string }>(`/api/v1/admin/tenants/${id}/invites`, { method: 'POST', body }),
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: queryKeys.tenants.invites(id) });
      setShowInviteForm(false);
      setInviteEmail('');
      setInviteRole('viewer');
      const baseUrl = typeof window !== 'undefined' ? window.location.origin : '';
      setInviteLink(`${baseUrl}/invite/${data.token}`);
      setLinkCopied(false);
    },
  });

  const revokeInviteMutation = useMutation({
    mutationFn: (inviteId: string) =>
      apiClient(`/api/v1/admin/tenants/${id}/invites/${inviteId}`, { method: 'DELETE' }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.tenants.invites(id) });
    },
  });

  const updateMemberMutation = useMutation({
    mutationFn: ({ memberId, ...body }: { memberId: string; role?: string; status?: string }) =>
      apiClient(`/api/v1/admin/tenants/${id}/members/${memberId}`, {
        method: 'PATCH',
        body,
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [...queryKeys.tenants.detail(id), 'members'] });
    },
  });

  const removeMemberMutation = useMutation({
    mutationFn: (memberId: string) =>
      apiClient(`/api/v1/admin/tenants/${id}/members/${memberId}`, { method: 'DELETE' }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [...queryKeys.tenants.detail(id), 'members'] });
      queryClient.invalidateQueries({ queryKey: queryKeys.tenants.detail(id) });
    },
  });

  // Helpers --------------------------------------------------------------
  const startEditing = useCallback(() => {
    if (!tenant) return;
    setForm({
      name: tenant.name,
      plan: tenant.plan,
      status: tenant.status,
    });
    setErrors({});
    setIsEditing(true);
  }, [tenant]);

  const cancelEditing = useCallback(() => {
    setIsEditing(false);
    setErrors({});
  }, []);

  const handleChange = useCallback(
    (field: keyof TenantFormData, value: string) => {
      setForm((prev) => ({ ...prev, [field]: value }));
      setErrors((prev) => {
        const next = { ...prev };
        delete next[field];
        return next;
      });
    },
    [],
  );

  const validate = useCallback((): boolean => {
    const next: Partial<Record<keyof TenantFormData, string>> = {};
    if (!form.name.trim()) next.name = t('detail.validation.nameRequired');
    setErrors(next);
    return Object.keys(next).length === 0;
  }, [form, t]);

  const handleSave = useCallback(() => {
    if (!validate()) return;
    const body: Record<string, unknown> = {
      name: form.name.trim(),
      plan: form.plan,
      status: form.status,
    };
    updateMutation.mutate(body);
  }, [form, validate, updateMutation]);

  const handleToggleStatus = useCallback(() => {
    if (!tenant) return;
    suspendMutation.mutate(tenant.status === 'active' ? 'suspended' : 'active');
  }, [tenant, suspendMutation]);

  // Render ---------------------------------------------------------------

  // Loading state
  if (isLoading) {
    return (
      <div>
        <button
          onClick={() => router.push('/tenants')}
          className="text-sm text-muted-foreground hover:text-foreground flex items-center gap-1 mb-4"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path d="M19 12H5" />
            <path d="m12 19-7-7 7-7" />
          </svg>
          {t('detail.backToTenants')}
        </button>
        <div className="text-sm text-muted-foreground py-12 text-center">
          {t('detail.loading')}
        </div>
      </div>
    );
  }

  // Error state
  if (error) {
    return (
      <div>
        <button
          onClick={() => router.push('/tenants')}
          className="text-sm text-muted-foreground hover:text-foreground flex items-center gap-1 mb-4"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path d="M19 12H5" />
            <path d="m12 19-7-7 7-7" />
          </svg>
          {t('detail.backToTenants')}
        </button>
        <div className="p-4 rounded-md border border-destructive/50 bg-destructive/10 text-destructive text-sm">
          {t('detail.loadError')} {(error as Error).message}
        </div>
      </div>
    );
  }

  if (!tenant) return null;

  return (
    <div>
      {/* Back link */}
      <button
        onClick={() => router.push('/tenants')}
        className="text-sm text-muted-foreground hover:text-foreground flex items-center gap-1 mb-4"
      >
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="16"
          height="16"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
        >
          <path d="M19 12H5" />
          <path d="m12 19-7-7 7-7" />
        </svg>
        {t('detail.backToTenants')}
      </button>

      {/* Page header */}
      <div className="flex items-center gap-3 mb-6">
        <h1 className="text-2xl font-bold">{tenant.name}</h1>
        <StatusBadge status={tenant.status} />
        <PlanBadge plan={tenant.plan} />
      </div>

      {/* Two-column layout */}
      <div className="grid gap-6 lg:grid-cols-3">
        {/* Left column */}
        <div className="lg:col-span-2 space-y-6">
          {/* Tenant Information Card */}
          <div className="bg-card border rounded-lg p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold">{t('detail.tenantInformation')}</h2>
              {!isEditing && (
                <button
                  onClick={startEditing}
                  className="px-3 py-1 text-xs rounded-md border border-input hover:bg-accent transition-colors"
                >
                  {tc('edit')}
                </button>
              )}
            </div>

            {isEditing ? (
              /* ---------- Edit form ---------- */
              <div className="space-y-4">
                {/* name */}
                <div>
                  <label className="block text-sm font-medium mb-1">
                    {tc('name')} <span className="text-destructive">*</span>
                  </label>
                  <input
                    type="text"
                    value={form.name}
                    onChange={(e) => handleChange('name', e.target.value)}
                    className={cn(
                      'w-full px-3 py-2 rounded-md border bg-background text-sm',
                      errors.name ? 'border-destructive' : 'border-input',
                    )}
                    placeholder="My Organization"
                  />
                  {errors.name && (
                    <p className="text-xs text-destructive mt-1">{errors.name}</p>
                  )}
                </div>

                {/* plan */}
                <div>
                  <label className="block text-sm font-medium mb-1">{t('form.plan')}</label>
                  <select
                    value={form.plan}
                    onChange={(e) => handleChange('plan', e.target.value)}
                    className="w-full px-3 py-2 rounded-md border border-input bg-background text-sm"
                  >
                    <option value="free">{t('plans.free')}</option>
                    <option value="pro">{t('plans.pro')}</option>
                    <option value="enterprise">{t('plans.enterprise')}</option>
                  </select>
                </div>

                {/* status */}
                <div>
                  <label className="block text-sm font-medium mb-1">{t('form.status')}</label>
                  <select
                    value={form.status}
                    onChange={(e) => handleChange('status', e.target.value)}
                    className="w-full px-3 py-2 rounded-md border border-input bg-background text-sm"
                  >
                    <option value="active">{t('statuses.active')}</option>
                    <option value="suspended">{t('statuses.suspended')}</option>
                  </select>
                </div>

                {/* Update error */}
                {updateMutation.isError && (
                  <div className="p-3 rounded-md border border-destructive/50 bg-destructive/10 text-destructive text-sm">
                    {t('detail.failedToUpdate')} {(updateMutation.error as Error).message}
                  </div>
                )}

                {/* Save / Cancel */}
                <div className="flex justify-end gap-3 pt-2">
                  <button
                    type="button"
                    onClick={cancelEditing}
                    className="px-4 py-2 text-sm rounded-md border border-input hover:bg-accent"
                    disabled={updateMutation.isPending}
                  >
                    {tc('cancel')}
                  </button>
                  <button
                    type="button"
                    onClick={handleSave}
                    disabled={updateMutation.isPending}
                    className="px-4 py-2 text-sm rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50"
                  >
                    {updateMutation.isPending ? tc('saving') : tc('save')}
                  </button>
                </div>
              </div>
            ) : (
              /* ---------- Read-only info display ---------- */
              <dl className="divide-y">
                <InfoRow label={tc('name')} value={tenant.name} />
                <InfoRow
                  label={t('detail.slug')}
                  value={
                    <span className="font-mono text-xs">{tenant.slug}</span>
                  }
                />
                <InfoRow
                  label={t('detail.schemaName')}
                  value={
                    <code className="font-mono text-xs bg-muted px-1.5 py-0.5 rounded">
                      {tenant.schemaName}
                    </code>
                  }
                />
                <InfoRow
                  label={t('form.plan')}
                  value={<PlanBadge plan={tenant.plan} />}
                />
                <InfoRow
                  label={tc('status')}
                  value={<StatusBadge status={tenant.status} />}
                />
                <InfoRow label={t('detail.memberCount')} value={String(tenant.memberCount)} />
                <InfoRow label={tc('created')} value={formatDate(tenant.createdAt)} />
                <InfoRow label={tc('updated')} value={formatDate(tenant.updatedAt)} />
              </dl>
            )}
          </div>

          {/* Member List */}
          <div className="bg-card border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">{t('detail.members')}</h2>

            {members.length === 0 ? (
              <p className="text-sm text-muted-foreground py-4 text-center">
                {t('detail.noMembers')}
              </p>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b bg-muted/50">
                      <th className="text-left px-3 py-2 font-medium">{t('detail.membersTable.name')}</th>
                      <th className="text-left px-3 py-2 font-medium">{t('detail.membersTable.email')}</th>
                      <th className="text-left px-3 py-2 font-medium">{t('detail.membersTable.role')}</th>
                      <th className="text-left px-3 py-2 font-medium">{t('detail.membersTable.joined')}</th>
                      <th className="text-right px-3 py-2 font-medium">{t('detail.invitesTable.actions')}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {members.map((member) => (
                      <tr
                        key={member.id}
                        className="border-b last:border-b-0 hover:bg-muted/30 transition-colors"
                      >
                        <td className="px-3 py-2 font-medium">{member.name}</td>
                        <td className="px-3 py-2 text-muted-foreground">
                          {member.email}
                        </td>
                        <td className="px-3 py-2">
                          <select
                            value={member.role}
                            onChange={(e) =>
                              updateMemberMutation.mutate({
                                memberId: member.id,
                                role: e.target.value,
                              })
                            }
                            disabled={updateMemberMutation.isPending}
                            className="px-2 py-1 text-xs rounded-md border border-input bg-background"
                          >
                            <option value="admin">admin</option>
                            <option value="operator">operator</option>
                            <option value="viewer">viewer</option>
                          </select>
                        </td>
                        <td className="px-3 py-2 text-muted-foreground text-xs">
                          {formatRelative(member.joinedAt)}
                        </td>
                        <td className="px-3 py-2 text-right">
                          <button
                            onClick={() => {
                              if (window.confirm(`Remove ${member.name} from this tenant?`)) {
                                removeMemberMutation.mutate(member.id);
                              }
                            }}
                            disabled={removeMemberMutation.isPending}
                            className="px-2 py-1 text-xs text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded disabled:opacity-50"
                          >
                            {tc('remove')}
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>

          {/* Invitations */}
          <div className="bg-card border rounded-lg p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold">{t('detail.invitations')}</h2>
              <button
                onClick={() => { setShowInviteForm(!showInviteForm); setInviteLink(null); }}
                className="px-3 py-1 text-xs rounded-md bg-primary text-primary-foreground hover:opacity-90"
              >
                {t('detail.inviteUser')}
              </button>
            </div>

            {inviteLink && (
              <div className="mb-4 p-4 border border-green-500/50 rounded-md bg-green-500/10 space-y-2">
                <p className="text-sm font-medium text-green-700 dark:text-green-400">
                  {t('detail.inviteLinkReady')}
                </p>
                <div className="flex gap-2 items-center">
                  <input
                    readOnly
                    value={inviteLink}
                    className="flex-1 px-2 py-1 text-xs font-mono bg-background border rounded-md"
                  />
                  <button
                    onClick={() => {
                      navigator.clipboard.writeText(inviteLink);
                      setLinkCopied(true);
                      setTimeout(() => setLinkCopied(false), 2000);
                    }}
                    className="px-3 py-1 text-xs rounded-md bg-primary text-primary-foreground hover:opacity-90 shrink-0"
                  >
                    {linkCopied ? t('detail.copied') : t('detail.copy')}
                  </button>
                </div>
                <p className="text-xs text-muted-foreground">{t('detail.inviteLinkHint')}</p>
              </div>
            )}

            {showInviteForm && (
              <div className="mb-4 p-4 border rounded-md bg-muted/30 space-y-3">
                <div>
                  <label className="block text-sm font-medium mb-1">{t('detail.inviteForm.email')}</label>
                  <input
                    type="email"
                    value={inviteEmail}
                    onChange={(e) => setInviteEmail(e.target.value)}
                    className="w-full px-3 py-2 bg-background border rounded-md text-sm"
                    placeholder={t('detail.inviteForm.emailPlaceholder')}
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium mb-1">{t('detail.inviteForm.role')}</label>
                  <select
                    value={inviteRole}
                    onChange={(e) => setInviteRole(e.target.value)}
                    className="w-full px-3 py-2 bg-background border rounded-md text-sm"
                  >
                    <option value="viewer">{t('detail.inviteForm.roles.viewer')}</option>
                    <option value="operator">{t('detail.inviteForm.roles.operator')}</option>
                    <option value="admin">{t('detail.inviteForm.roles.admin')}</option>
                  </select>
                </div>
                {sendInviteMutation.isError && (
                  <p className="text-xs text-red-500">
                    {(sendInviteMutation.error as Error).message}
                  </p>
                )}
                <div className="flex gap-2">
                  <button
                    onClick={() => sendInviteMutation.mutate({ email: inviteEmail, role: inviteRole })}
                    disabled={!inviteEmail || sendInviteMutation.isPending}
                    className="px-3 py-1.5 text-xs bg-primary text-primary-foreground rounded-md hover:opacity-90 disabled:opacity-50"
                  >
                    {sendInviteMutation.isPending ? t('detail.sending') : t('detail.sendInvite')}
                  </button>
                  <button
                    onClick={() => { setShowInviteForm(false); setInviteEmail(''); }}
                    className="px-3 py-1.5 text-xs border rounded-md hover:bg-muted"
                  >
                    {tc('cancel')}
                  </button>
                </div>
              </div>
            )}

            {invites.length === 0 ? (
              <p className="text-sm text-muted-foreground py-4 text-center">
                {t('detail.noInvitations')}
              </p>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b bg-muted/50">
                      <th className="text-left px-3 py-2 font-medium">{t('detail.invitesTable.email')}</th>
                      <th className="text-left px-3 py-2 font-medium">{t('detail.invitesTable.role')}</th>
                      <th className="text-left px-3 py-2 font-medium">{t('detail.invitesTable.status')}</th>
                      <th className="text-right px-3 py-2 font-medium">{t('detail.invitesTable.actions')}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {invites.map((inv) => (
                      <tr key={inv.id} className="border-b last:border-b-0 hover:bg-muted/30">
                        <td className="px-3 py-2">{inv.email}</td>
                        <td className="px-3 py-2 capitalize">{inv.role}</td>
                        <td className="px-3 py-2">
                          <span className={cn(
                            'inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium',
                            inv.status === 'pending' && 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400',
                            inv.status === 'accepted' && 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
                            inv.status === 'expired' && 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300',
                            inv.status === 'revoked' && 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
                          )}>
                            {inv.status}
                          </span>
                        </td>
                        <td className="px-3 py-2 text-right">
                          {inv.status === 'pending' && (
                            <button
                              onClick={() => revokeInviteMutation.mutate(inv.id)}
                              disabled={revokeInviteMutation.isPending}
                              className="px-2 py-1 text-xs text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded"
                            >
                              {t('detail.revoke')}
                            </button>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>

        {/* Right column */}
        <div className="space-y-6">
          {/* Quick Actions */}
          <div className="bg-card border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">{t('detail.quickActions')}</h2>
            <div className="space-y-2">
              <button
                onClick={handleToggleStatus}
                disabled={suspendMutation.isPending}
                className={cn(
                  'w-full px-4 py-2 text-sm rounded-md font-medium transition-colors text-left flex items-center gap-2 disabled:opacity-50',
                  tenant.status === 'active'
                    ? 'border border-yellow-500/50 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/10'
                    : 'border border-green-500/50 text-green-700 dark:text-green-400 hover:bg-green-500/10',
                )}
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  {tenant.status === 'active' ? (
                    <>
                      <rect x="6" y="4" width="4" height="16" />
                      <rect x="14" y="4" width="4" height="16" />
                    </>
                  ) : (
                    <polygon points="5 3 19 12 5 21 5 3" />
                  )}
                </svg>
                {suspendMutation.isPending
                  ? 'Updating...'
                  : tenant.status === 'active'
                    ? t('detail.suspendTenant')
                    : t('detail.activateTenant')}
              </button>

              {suspendMutation.isError && (
                <p className="text-xs text-destructive">
                  {(suspendMutation.error as Error).message}
                </p>
              )}

              <button
                onClick={() => router.push(`/audit/logs?tenantId=${tenant.id}`)}
                className="w-full px-4 py-2 text-sm rounded-md border hover:bg-accent transition-colors text-left flex items-center gap-2"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
                  <polyline points="14 2 14 8 20 8" />
                  <line x1="16" x2="8" y1="13" y2="13" />
                  <line x1="16" x2="8" y1="17" y2="17" />
                  <polyline points="10 9 9 9 8 9" />
                </svg>
                {t('detail.viewAuditLog')}
              </button>

              <button
                onClick={startEditing}
                className="w-full px-4 py-2 text-sm rounded-md border hover:bg-accent transition-colors text-left flex items-center gap-2"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z" />
                  <path d="m15 5 4 4" />
                </svg>
                {t('detail.editTenant')}
              </button>

              <button
                onClick={() => setDeleteOpen(true)}
                className="w-full px-4 py-2 text-sm rounded-md border border-destructive/50 text-destructive hover:bg-destructive/10 transition-colors text-left flex items-center gap-2"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <path d="M3 6h18" />
                  <path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6" />
                  <path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2" />
                  <line x1="10" x2="10" y1="11" y2="17" />
                  <line x1="14" x2="14" y1="11" y2="17" />
                </svg>
                {t('detail.deleteTenant')}
              </button>
            </div>
          </div>

          {/* Tenant Metadata */}
          <div className="bg-card border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">{t('detail.metadata')}</h2>
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{t('detail.tenantId')}</span>
                <code className="text-xs font-mono text-muted-foreground bg-muted px-1.5 py-0.5 rounded">
                  {tenant.id}
                </code>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{t('detail.slug')}</span>
                <span className="text-sm font-mono">{tenant.slug}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{t('detail.schema')}</span>
                <code className="text-xs font-mono text-muted-foreground bg-muted px-1.5 py-0.5 rounded">
                  {tenant.schemaName}
                </code>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{tc('created')}</span>
                <span className="text-xs text-muted-foreground">
                  {formatDate(tenant.createdAt)}
                </span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{tc('updated')}</span>
                <span className="text-xs text-muted-foreground">
                  {formatDate(tenant.updatedAt)}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Delete confirmation dialog */}
      <DeleteDialog
        open={deleteOpen}
        name={tenant.name}
        deleting={deleteMutation.isPending}
        onClose={() => setDeleteOpen(false)}
        onConfirm={() => deleteMutation.mutate()}
      />
    </div>
  );
}
