'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { apiClient } from '@/infrastructure/api/api-client';
import { queryKeys } from '@/infrastructure/api/query-keys';
import { format } from 'date-fns';

/* ------------------------------------------------------------------ */
/*  Types                                                              */
/* ------------------------------------------------------------------ */

interface TenantQuota {
  maxServers: number;
  maxUsers: number;
  maxStandingOrders: number;
  maxAgentTokensPerMonth: number;
}

interface Tenant {
  id: string;
  name: string;
  slug: string;
  plan: 'free' | 'pro' | 'enterprise';
  status: 'active' | 'suspended';
  userCount: number;
  quota: TenantQuota;
  createdAt: string;
}

interface CreateTenantPayload {
  name: string;
  slug: string;
  plan: 'free' | 'pro' | 'enterprise';
  adminEmail: string;
}

/* ------------------------------------------------------------------ */
/*  Helpers                                                            */
/* ------------------------------------------------------------------ */

const PLANS: Tenant['plan'][] = ['free', 'pro', 'enterprise'];

const planBadge: Record<Tenant['plan'], string> = {
  free: 'bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300',
  pro: 'bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300',
  enterprise: 'bg-purple-100 text-purple-700 dark:bg-purple-900 dark:text-purple-300',
};

const statusBadge: Record<Tenant['status'], string> = {
  active: 'bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300',
  suspended: 'bg-red-100 text-red-700 dark:bg-red-900 dark:text-red-300',
};

function slugify(value: string) {
  return value
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/(^-|-$)/g, '');
}

/* ------------------------------------------------------------------ */
/*  Page                                                               */
/* ------------------------------------------------------------------ */

export default function TenantsPage() {
  const { t } = useTranslation('tenants');
  const { t: tc } = useTranslation('common');
  const queryClient = useQueryClient();

  /* ---- local state ---- */
  const [showCreate, setShowCreate] = useState(false);
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [editPlan, setEditPlan] = useState<Tenant['plan']>('free');
  const [editQuota, setEditQuota] = useState<TenantQuota>({
    maxServers: 0,
    maxUsers: 0,
    maxStandingOrders: 0,
    maxAgentTokensPerMonth: 0,
  });

  /* ---- create form state ---- */
  const [formName, setFormName] = useState('');
  const [formSlug, setFormSlug] = useState('');
  const [formPlan, setFormPlan] = useState<Tenant['plan']>('free');
  const [formEmail, setFormEmail] = useState('');
  const [slugTouched, setSlugTouched] = useState(false);

  /* ---- queries ---- */
  const { data: tenants = [], isLoading, error } = useQuery<Tenant[]>({
    queryKey: queryKeys.tenants.list(),
    queryFn: () => apiClient<Tenant[]>('/api/v1/admin/tenants'),
  });

  /* ---- mutations ---- */
  const invalidate = () => queryClient.invalidateQueries({ queryKey: queryKeys.tenants.all });

  const createMutation = useMutation({
    mutationFn: (payload: CreateTenantPayload) =>
      apiClient('/api/v1/admin/tenants', { method: 'POST', body: payload }),
    onSuccess: () => { invalidate(); resetCreateForm(); },
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, body }: { id: string; body: Partial<Tenant> }) =>
      apiClient(`/api/v1/admin/tenants/${id}`, { method: 'PATCH', body }),
    onSuccess: () => { invalidate(); setEditingId(null); },
  });

  const toggleStatusMutation = useMutation({
    mutationFn: ({ id, status }: { id: string; status: Tenant['status'] }) =>
      apiClient(`/api/v1/admin/tenants/${id}`, { method: 'PATCH', body: { status } }),
    onSuccess: invalidate,
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) =>
      apiClient(`/api/v1/admin/tenants/${id}`, { method: 'DELETE' }),
    onSuccess: () => { invalidate(); setDeletingId(null); },
  });

  /* ---- helpers ---- */
  function resetCreateForm() {
    setShowCreate(false);
    setFormName('');
    setFormSlug('');
    setFormPlan('free');
    setFormEmail('');
    setSlugTouched(false);
  }

  function handleNameChange(value: string) {
    setFormName(value);
    if (!slugTouched) setFormSlug(slugify(value));
  }

  function startEdit(tenant: Tenant) {
    setEditingId(tenant.id);
    setEditPlan(tenant.plan);
    setEditQuota({ ...tenant.quota });
  }

  function saveEdit(id: string) {
    updateMutation.mutate({ id, body: { plan: editPlan, quota: editQuota } });
  }

  /* ---------------------------------------------------------------- */
  /*  Render                                                           */
  /* ---------------------------------------------------------------- */

  return (
    <div>
      {/* Header */}
      <div className="flex justify-between items-center mb-6">
        <div>
          <h1 className="text-2xl font-bold">{t('title')}</h1>
          <p className="text-sm text-muted-foreground mt-1">
            {t('subtitle')}
          </p>
        </div>
        <button
          onClick={() => setShowCreate(true)}
          className="px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm font-medium hover:opacity-90"
        >
          {t('newTenant')}
        </button>
      </div>

      {/* ---- Create Dialog ---- */}
      {showCreate && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
          <div className="bg-card border rounded-lg shadow-lg w-full max-w-md p-6">
            <h2 className="text-lg font-semibold mb-4">{t('createTenant')}</h2>

            <label className="block text-sm font-medium mb-1">{t('form.name')} *</label>
            <input
              className="w-full border rounded-md px-3 py-2 mb-3 bg-background text-sm"
              value={formName}
              onChange={(e) => handleNameChange(e.target.value)}
              placeholder="Acme Corp"
            />

            <label className="block text-sm font-medium mb-1">{t('form.slug')}</label>
            <input
              className="w-full border rounded-md px-3 py-2 mb-3 bg-background text-sm"
              value={formSlug}
              onChange={(e) => { setSlugTouched(true); setFormSlug(e.target.value); }}
              placeholder="acme-corp"
            />

            <label className="block text-sm font-medium mb-1">{t('form.plan')}</label>
            <select
              className="w-full border rounded-md px-3 py-2 mb-3 bg-background text-sm"
              value={formPlan}
              onChange={(e) => setFormPlan(e.target.value as Tenant['plan'])}
            >
              {PLANS.map((p) => (
                <option key={p} value={p}>{t(`plans.${p}`)}</option>
              ))}
            </select>

            <label className="block text-sm font-medium mb-1">{t('form.adminEmail')} *</label>
            <input
              className="w-full border rounded-md px-3 py-2 mb-4 bg-background text-sm"
              type="email"
              value={formEmail}
              onChange={(e) => setFormEmail(e.target.value)}
              placeholder="admin@acme.com"
            />

            <div className="flex justify-end gap-2">
              <button
                onClick={resetCreateForm}
                className="px-4 py-2 text-sm border rounded-md hover:bg-muted"
              >
                {tc('cancel')}
              </button>
              <button
                disabled={!formName || !formEmail || createMutation.isPending}
                onClick={() =>
                  createMutation.mutate({
                    name: formName,
                    slug: formSlug || slugify(formName),
                    plan: formPlan,
                    adminEmail: formEmail,
                  })
                }
                className="px-4 py-2 text-sm bg-primary text-primary-foreground rounded-md hover:opacity-90 disabled:opacity-50"
              >
                {createMutation.isPending ? t('createDialog.creating') : t('createDialog.create')}
              </button>
            </div>

            {createMutation.isError && (
              <p className="text-sm text-red-500 mt-2">
                {(createMutation.error as Error).message}
              </p>
            )}
          </div>
        </div>
      )}

      {/* ---- Loading / Error ---- */}
      {isLoading && <p className="text-muted-foreground">{t('loading')}</p>}
      {error && <p className="text-red-500">{t('loadError')} {(error as Error).message}</p>}

      {/* ---- Tenant Table ---- */}
      {!isLoading && !error && (
        <div className="border rounded-lg overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-muted/50">
              <tr className="text-left">
                <th className="px-4 py-3 font-medium">{t('table.name')}</th>
                <th className="px-4 py-3 font-medium">{t('table.slug')}</th>
                <th className="px-4 py-3 font-medium">{t('table.plan')}</th>
                <th className="px-4 py-3 font-medium">{t('table.status')}</th>
                <th className="px-4 py-3 font-medium text-right">{t('table.users')}</th>
                <th className="px-4 py-3 font-medium">{t('table.created')}</th>
                <th className="px-4 py-3 font-medium text-right">{t('table.actions')}</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {tenants.map((tenant) => (
                <>
                  {/* Main row */}
                  <tr key={tenant.id} className="hover:bg-muted/30">
                    <td className="px-4 py-3 font-medium">
                      <Link href={`/tenants/${tenant.id}`} className="hover:underline text-primary">
                        {tenant.name}
                      </Link>
                    </td>
                    <td className="px-4 py-3 text-muted-foreground">{tenant.slug}</td>
                    <td className="px-4 py-3">
                      {editingId === tenant.id ? (
                        <select
                          className="border rounded px-2 py-1 text-xs bg-background"
                          value={editPlan}
                          onChange={(e) => setEditPlan(e.target.value as Tenant['plan'])}
                        >
                          {PLANS.map((p) => (
                            <option key={p} value={p}>{t(`plans.${p}`)}</option>
                          ))}
                        </select>
                      ) : (
                        <span className={`inline-block px-2 py-0.5 rounded-full text-xs font-medium ${planBadge[tenant.plan]}`}>
                          {tenant.plan}
                        </span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <span className={`inline-block px-2 py-0.5 rounded-full text-xs font-medium ${statusBadge[tenant.status]}`}>
                        {tenant.status}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-right">{tenant.userCount}</td>
                    <td className="px-4 py-3 text-muted-foreground">
                      {format(new Date(tenant.createdAt), 'MMM d, yyyy')}
                    </td>
                    <td className="px-4 py-3 text-right">
                      <div className="flex justify-end gap-1">
                        {editingId === tenant.id ? (
                          <>
                            <button
                              onClick={() => saveEdit(tenant.id)}
                              disabled={updateMutation.isPending}
                              className="px-2 py-1 text-xs bg-primary text-primary-foreground rounded hover:opacity-90 disabled:opacity-50"
                            >
                              {tc('save')}
                            </button>
                            <button
                              onClick={() => setEditingId(null)}
                              className="px-2 py-1 text-xs border rounded hover:bg-muted"
                            >
                              {tc('cancel')}
                            </button>
                          </>
                        ) : (
                          <>
                            <button
                              onClick={() => startEdit(tenant)}
                              className="px-2 py-1 text-xs border rounded hover:bg-muted"
                            >
                              {tc('edit')}
                            </button>
                            <button
                              onClick={() =>
                                toggleStatusMutation.mutate({
                                  id: tenant.id,
                                  status: tenant.status === 'active' ? 'suspended' : 'active',
                                })
                              }
                              className={`px-2 py-1 text-xs rounded ${
                                tenant.status === 'active'
                                  ? 'bg-red-100 text-red-700 hover:bg-red-200 dark:bg-red-900 dark:text-red-300'
                                  : 'bg-green-100 text-green-700 hover:bg-green-200 dark:bg-green-900 dark:text-green-300'
                              }`}
                            >
                              {tenant.status === 'active' ? t('actions.suspend') : t('actions.activate')}
                            </button>
                            <button
                              onClick={() => setExpandedId(expandedId === tenant.id ? null : tenant.id)}
                              className="px-2 py-1 text-xs border rounded hover:bg-muted"
                            >
                              {expandedId === tenant.id ? t('actions.hideQuotas') : t('actions.quotas')}
                            </button>
                            <button
                              onClick={() => setDeletingId(tenant.id)}
                              className="px-2 py-1 text-xs rounded bg-red-100 text-red-700 hover:bg-red-200 dark:bg-red-900 dark:text-red-300"
                            >
                              {tc('delete')}
                            </button>
                          </>
                        )}
                      </div>
                    </td>
                  </tr>

                  {/* Expanded quota row */}
                  {expandedId === tenant.id && (
                    <tr key={`${tenant.id}-quota`} className="bg-muted/20">
                      <td colSpan={7} className="px-4 py-4">
                        <QuotaEditor
                          quota={editingId === tenant.id ? editQuota : tenant.quota}
                          editable={editingId === tenant.id}
                          onChange={setEditQuota}
                        />
                      </td>
                    </tr>
                  )}
                </>
              ))}

              {tenants.length === 0 && (
                <tr>
                  <td colSpan={7} className="px-4 py-8 text-center text-muted-foreground">
                    {t('empty')}
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      )}

      {/* Delete confirmation dialog */}
      {deletingId && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-card border rounded-lg p-6 max-w-sm w-full mx-4 space-y-4">
            <h2 className="text-lg font-semibold">{t('deleteDialog.title')}</h2>
            <p className="text-sm text-muted-foreground">{t('deleteDialog.message')}</p>
            <div className="flex gap-3 justify-end">
              <button
                onClick={() => setDeletingId(null)}
                disabled={deleteMutation.isPending}
                className="px-4 py-2 text-sm border rounded-md hover:bg-muted"
              >
                {tc('cancel')}
              </button>
              <button
                onClick={() => deleteMutation.mutate(deletingId)}
                disabled={deleteMutation.isPending}
                className="px-4 py-2 text-sm bg-destructive text-destructive-foreground rounded-md hover:opacity-90 disabled:opacity-50"
              >
                {deleteMutation.isPending ? tc('deleting') : tc('delete')}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Quota Editor (inline sub-component)                                */
/* ------------------------------------------------------------------ */

function QuotaEditor({
  quota,
  editable,
  onChange,
}: {
  quota: TenantQuota;
  editable: boolean;
  onChange: (q: TenantQuota) => void;
}) {
  const { t } = useTranslation('tenants');

  const fields: { key: keyof TenantQuota; label: string }[] = [
    { key: 'maxServers', label: t('quotas.maxServers') },
    { key: 'maxUsers', label: t('quotas.maxUsers') },
    { key: 'maxStandingOrders', label: t('quotas.maxStandingOrders') },
    { key: 'maxAgentTokensPerMonth', label: t('quotas.maxAgentTokens') },
  ];

  return (
    <div>
      <h3 className="text-sm font-semibold mb-3">{t('quotas.title')}</h3>
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {fields.map(({ key, label }) => (
          <div key={key}>
            <label className="block text-xs text-muted-foreground mb-1">{label}</label>
            {editable ? (
              <input
                type="number"
                min={0}
                className="w-full border rounded px-2 py-1 text-sm bg-background"
                value={quota[key]}
                onChange={(e) => onChange({ ...quota, [key]: Number(e.target.value) })}
              />
            ) : (
              <p className="text-sm font-medium">{quota[key].toLocaleString()}</p>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}
