import { useQuery } from '@tanstack/react-query';
import { useParams, useNavigate } from 'react-router-dom';
import { adminApi } from '../../api/admin';
import { AppLayout } from '../../components/layout/AppLayout';
import { PageLoader } from '../../components/ui/LoadingSpinner';
import {
  ArrowLeft,
  Building2,
  MapPin,
  Globe,
  Phone,
  Users,
  TrendingUp,
  DollarSign,
  Briefcase,
  Factory,
  Link as LinkIcon,
  Tag,
  Calendar,
  Mail,
  UserIcon,
} from 'lucide-react';
import type { Organization, ApiUser } from '../../types';

export function AdminOrganizationDetail() {
  const { orgId } = useParams<{ orgId: string }>();
  const navigate = useNavigate();

  const { data: orgData, isLoading: loadingOrgs } = useQuery({
    queryKey: ['admin-organizations'],
    queryFn: () => adminApi.getOrganizations(),
  });

  const { data: userData, isLoading: loadingUsers } = useQuery({
    queryKey: ['admin-users'],
    queryFn: () => adminApi.getUsers(),
  });

  const organization = orgData?.items.find(
    (org) => String(org.id) === orgId
  );

  const allUsers = userData?.items ?? [];

  // Try to find users related to this organization by matching company name or slug
  const relatedUsers = organization
    ? allUsers.filter(
        (u) =>
          u.fullName.toLowerCase().includes(organization.name.toLowerCase()) ||
          u.email.toLowerCase().includes(organization.name.toLowerCase()) ||
          u.email.toLowerCase().includes((organization.slug || '').toLowerCase())
      )
    : [];

  const isLoading = loadingOrgs || loadingUsers;

  if (isLoading) {
    return (
      <AppLayout title="Organization">
        <PageLoader />
      </AppLayout>
    );
  }

  if (!organization) {
    return (
      <AppLayout title="Organization">
        <div className="flex flex-col items-center justify-center py-16">
          <Building2 className="h-12 w-12 text-surface-300" />
          <p className="mt-4 text-sm font-medium text-surface-700">
            Organization not found
          </p>
          <button
            onClick={() => navigate('/admin/organizations')}
            className="mt-4 inline-flex items-center gap-2 text-sm text-brand-600 hover:text-brand-700"
          >
            <ArrowLeft className="h-4 w-4" />
            Back to Organizations
          </button>
        </div>
      </AppLayout>
    );
  }

  return (
    <AppLayout title={organization.name}>
      {/* Back link */}
      <button
        onClick={() => navigate('/admin/organizations')}
        className="mb-4 inline-flex items-center gap-1 text-sm text-brand-600 hover:text-brand-700"
      >
        <ArrowLeft className="h-4 w-4" />
        Back to Organizations
      </button>

      {/* Header */}
      <div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
        <div className="flex items-start gap-4">
          <div className="flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-lg bg-brand-50 text-brand-600">
            <Building2 className="h-6 w-6" />
          </div>
          <div>
            <div className="flex items-center gap-3">
              <h1 className="text-xl sm:text-2xl font-bold text-surface-900">
                {organization.name}
              </h1>
              <StatusBadge status={organization.status} />
            </div>
            <p className="mt-1 text-sm text-surface-500">
              {organization.industry || 'No industry set'}
              {organization.location
                ? ` · ${organization.location}`
                : ''}
            </p>
          </div>
        </div>
      </div>

      {/* Stats row */}
      <div className="mb-6 grid grid-cols-2 gap-4 sm:grid-cols-4">
        <StatCard
          icon={<DollarSign className="h-5 w-5" />}
          label="Annual Revenue"
          value={`$${organization.annual_revenue.toLocaleString()}`}
        />
        <StatCard
          icon={<TrendingUp className="h-5 w-5" />}
          label="Revenue Growth"
          value={`${organization.revenue_growth >= 0 ? '+' : ''}${organization.revenue_growth.toFixed(1)}%`}
          positive={organization.revenue_growth >= 0}
        />
        <StatCard
          icon={<Briefcase className="h-5 w-5" />}
          label="Active Projects"
          value={String(organization.active_projects)}
        />
        <StatCard
          icon={<Users className="h-5 w-5" />}
          label="Commission Rate"
          value={`${organization.commission_rate}%`}
        />
      </div>

      {/* Details card */}
      <div className="mb-6 rounded-xl border border-surface-200 bg-white p-6">
        <h2 className="mb-4 text-sm font-semibold text-surface-700">
          Organization Details
        </h2>
        <dl className="grid grid-cols-1 gap-x-6 gap-y-4 sm:grid-cols-2 lg:grid-cols-3">
          <DetailItem icon={<Building2 className="h-4 w-4" />} label="Name">
            {organization.name}
          </DetailItem>
          <DetailItem icon={<Factory className="h-4 w-4" />} label="Industry">
            {organization.industry || '—'}
          </DetailItem>
          <DetailItem icon={<Tag className="h-4 w-4" />} label="Tier">
            {organization.tier || '—'}
          </DetailItem>
          <DetailItem icon={<Tag className="h-4 w-4" />} label="Size">
            {organization.size || '—'}
          </DetailItem>
          <DetailItem icon={<Tag className="h-4 w-4" />} label="Slug">
            {organization.slug || '—'}
          </DetailItem>
          <DetailItem icon={<MapPin className="h-4 w-4" />} label="Location">
            {organization.location || '—'}
          </DetailItem>
          <DetailItem icon={<Globe className="h-4 w-4" />} label="Website">
            {organization.website ? (
              <a
                href={
                  organization.website.startsWith('http')
                    ? organization.website
                    : `https://${organization.website}`
                }
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center gap-1 text-brand-600 hover:text-brand-700"
              >
                {organization.website}
                <LinkIcon className="h-3 w-3" />
              </a>
            ) : (
              '—'
            )}
          </DetailItem>
          <DetailItem icon={<Calendar className="h-4 w-4" />} label="Last Updated">
            {organization.last_updated
              ? new Date(organization.last_updated).toLocaleDateString('en-US', {
                  year: 'numeric',
                  month: 'long',
                  day: 'numeric',
                })
              : '—'}
          </DetailItem>
        </dl>
      </div>

      {/* Related Users */}
      <div className="rounded-xl border border-surface-200 bg-white">
        <div className="border-b border-surface-200 p-6">
          <div className="flex items-center gap-2">
            <Users className="h-5 w-5 text-surface-500" />
            <h2 className="text-sm font-semibold text-surface-700">
              Related Users ({relatedUsers.length})
            </h2>
          </div>
          <p className="mt-1 text-xs text-surface-400">
            Users associated with this organization
          </p>
        </div>
        {relatedUsers.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-12">
            <UserIcon className="h-10 w-10 text-surface-300" />
            <p className="mt-3 text-sm font-medium text-surface-500">
              No related users found
            </p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-t border-surface-200">
                  <th className="pb-3 pl-6 text-left font-medium text-surface-500">
                    User
                  </th>
                  <th className="pb-3 text-left font-medium text-surface-500">
                    Role
                  </th>
                  <th className="pb-3 text-left font-medium text-surface-500">
                    Status
                  </th>
                  <th className="pb-3 text-right font-medium text-surface-500 pr-6">
                    Last Login
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-surface-100">
                {relatedUsers.map((user) => (
                  <tr key={user.id} className="hover:bg-surface-50">
                    <td className="py-3 pl-6">
                      <div className="flex items-center gap-3">
                        <div className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-brand-100 text-xs font-semibold text-brand-700">
                          {user.fullName.charAt(0).toUpperCase()}
                        </div>
                        <div className="min-w-0">
                          <p className="font-medium text-surface-900 truncate">
                            {user.fullName}
                          </p>
                          <p className="text-xs text-surface-500 truncate">
                            {user.email}
                          </p>
                        </div>
                      </div>
                    </td>
                    <td className="py-3">
                      <span className="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium bg-brand-50 text-brand-700">
                        {user.role}
                      </span>
                      {user.companyRole && (
                        <span className="ml-2 inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium bg-surface-100 text-surface-600">
                          {user.companyRole}
                        </span>
                      )}
                    </td>
                    <td className="py-3">
                      <span
                        className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${
                          user.status === 'active'
                            ? 'bg-success/10 text-success'
                            : 'bg-surface-200 text-surface-600'
                        }`}
                      >
                        {user.status}
                      </span>
                    </td>
                    <td className="py-3 text-right text-surface-500 pr-6">
                      {user.lastLogin
                        ? new Date(user.lastLogin).toLocaleDateString()
                        : 'Never'}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </AppLayout>
  );
}

function StatusBadge({ status }: { status: string }) {
  const isActive = status === 'active';
  return (
    <span
      className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${
        isActive
          ? 'bg-success/10 text-success'
          : 'bg-surface-200 text-surface-600'
      }`}
    >
      {status}
    </span>
  );
}

function StatCard({
  icon,
  label,
  value,
  positive,
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
  positive?: boolean;
}) {
  return (
    <div className="rounded-xl border border-surface-200 bg-white p-4">
      <div className="flex items-center gap-2 text-surface-400">
        {icon}
        <span className="text-xs font-medium">{label}</span>
      </div>
      <p
        className={`mt-2 text-lg font-bold ${
          positive === true
            ? 'text-success'
            : positive === false
              ? 'text-error'
              : 'text-surface-900'
        }`}
      >
        {value}
      </p>
    </div>
  );
}

function DetailItem({
  icon,
  label,
  children,
}: {
  icon: React.ReactNode;
  label: string;
  children: React.ReactNode;
}) {
  return (
    <div>
      <dt className="mb-1 flex items-center gap-1.5 text-xs font-medium text-surface-400">
        {icon}
        {label}
      </dt>
      <dd className="text-sm text-surface-700">{children}</dd>
    </div>
  );
}