'use client';

import { useQuery } from '@tanstack/react-query';
import { useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useMemo, useState } from 'react';

import Link from '@/components/link/Link';

type Flag = {
  id: string;
  name?: string;
  idType?: string;
  description: string;
  lastModifierID: string | null;
  lastModifiedTime: number | null;
  lastModifierEmail: string | null;
  lastModifierName: string | null;
  creatorID?: string | null;
  createdTime: number;
  creatorName: string | null;
  creatorEmail?: string | null;
  tags: string[];
  targetApps: string | string[];
  holdoutIDs: string[];
  team: string | null;
  teamID?: string | null;
  version?: number;
  checksPerHour: number | null;
  status: 'In Progress' | 'Launched' | 'Disabled' | 'Archived';
  type: 'TEMPORARY' | 'PERMANENT' | 'STALE' | 'TEMPLATE';
  typeReason:
    | 'NONE'
    | 'STALE_PROBABLY_LAUNCHED'
    | 'STALE_PROBABLY_UNLAUNCHED'
    | 'STALE_PROBABLY_FORGOTTEN'
    | 'STALE_NO_RULES'
    | 'STALE_PROBABLY_DEAD_CHECK'
    | 'STALE_EMPTY_CHECKS'
    | 'STALE_ALL_TRUE'
    | 'STALE_ALL_FALSE';
  owner?: {
    ownerID: string;
    ownerType: string;
    ownerName?: string;
    ownerEmail?: string;
  };
  isTemplate?: boolean;
  isEnabled: boolean;
  rules: Array<{
    name: string;
    passPercentage: number;
    conditions: Array<{
      targetValue?: string[] | number[] | string | number;
      operator?: string;
      field?: string | null;
      customID?: string | null;
      type:
        | 'app_version'
        | 'browser_name'
        | 'browser_version'
        | 'country'
        | 'custom_field'
        | 'email'
        | 'environment_tier'
        | 'fails_gate'
        | 'fails_segment'
        | 'ip_address'
        | 'locale'
        | 'os_name'
        | 'os_version'
        | 'passes_gate'
        | 'passes_segment'
        | 'public'
        | 'time'
        | 'unit_id'
        | 'user_id'
        | 'url'
        | 'javascript'
        | 'device_model'
        | 'target_app';
    }>;
    environments: string[];
    id?: string;
    baseID?: string;
    returnValue?: Record<string, any>;
    completedAutomatedRollouts?: Array<{
      time: number;
      passPercent: number;
    }>;
    pendingAutomatedRollouts?: Array<{
      time: number;
      passPercent: number;
    }>;
  }>;
  measureMetricLifts?: boolean;
  monitoringMetrics?: Array<{
    name: string;
    type: string;
  }>;
  reviewSettings?: {
    requiredReview: boolean;
    allowedReviewers?: Array<{
      id: string;
      name: string;
      email: string;
    }>;
  };
  releasePipelineID?: string | null;
  activeReview?: {
    reviewID: string;
    reviewStatus: string;
    description: string;
  };
  // Legacy fields for backwards compatibility
  key?: string;
  is_enabled?: boolean;
  state?: string;
  updated_at?: string;
};

type OwnerGroup = {
  ownerId: string;
  ownerLabel: string;
  flags: Flag[];
};

type FeatureFlagsResponse = {
  owners: OwnerGroup[];
  count: number;
  maybeTruncated: boolean;
  limitUsed: number;
};

export default function FlagsByOwnerPage() {
  const router = useRouter();
  const searchParams = useSearchParams();

  const [viewMode, setViewMode] = useState<'grouped' | 'list'>('grouped');
  const [ownerFilter, setOwnerFilter] = useState<string>('all');
  const [ownerQuery, setOwnerQuery] = useState<string>('');
  const [rolledOutFilter, setRolledOutFilter] = useState<string>('all');
  const [stalenessFilter, setStalenessFilter] = useState<string>('all');
  const [collapsedOwners, setCollapsedOwners] = useState<Set<string>>(
    () => new Set()
  );
  const limit = 1000; // single big page

  // Initialize state from URL parameters
  useEffect(() => {
    const ownerParam = searchParams.get('owner');
    const viewParam = searchParams.get('view');
    const queryParam = searchParams.get('query');
    const rolledOutParam = searchParams.get('rolledOut');
    const stalenessParam = searchParams.get('staleness');

    if (ownerParam) {
      setOwnerFilter(ownerParam);
    }
    if (viewParam === 'list' || viewParam === 'grouped') {
      setViewMode(viewParam);
    }
    if (queryParam) {
      setOwnerQuery(queryParam);
    }
    if (rolledOutParam === 'true' || rolledOutParam === 'false') {
      setRolledOutFilter(rolledOutParam);
    }
    if (stalenessParam === 'stale' || stalenessParam === 'active') {
      setStalenessFilter(stalenessParam);
    }
  }, [searchParams]);

  // Update URL when filters change
  const updateUrl = (
    newOwnerFilter?: string,
    newViewMode?: string,
    newQuery?: string,
    newRolledOutFilter?: string,
    newStalenessFilter?: string
  ) => {
    const params = new URLSearchParams(searchParams);

    const ownerValue = newOwnerFilter ?? ownerFilter;
    const viewValue = newViewMode ?? viewMode;
    const queryValue = newQuery ?? ownerQuery;
    const rolledOutValue = newRolledOutFilter ?? rolledOutFilter;
    const stalenessValue = newStalenessFilter ?? stalenessFilter;

    if (ownerValue && ownerValue !== 'all') {
      params.set('owner', ownerValue);
    } else {
      params.delete('owner');
    }

    if (viewValue && viewValue !== 'grouped') {
      params.set('view', viewValue);
    } else {
      params.delete('view');
    }

    if (queryValue && queryValue.trim()) {
      params.set('query', queryValue);
    } else {
      params.delete('query');
    }

    if (rolledOutValue && rolledOutValue !== 'all') {
      params.set('rolledOut', rolledOutValue);
    } else {
      params.delete('rolledOut');
    }

    if (stalenessValue && stalenessValue !== 'all') {
      params.set('staleness', stalenessValue);
    } else {
      params.delete('staleness');
    }

    const newUrl = params.toString() ? `?${params.toString()}` : '';
    router.replace(`/b-side/feature-flags${newUrl}`, { scroll: false });
  };

  const { data, isLoading, isError, error } = useQuery<
    FeatureFlagsResponse,
    Error
  >({
    queryKey: ['feature-flags', { limit }],
    queryFn: async () => {
      const q = new URLSearchParams();
      q.set('limit', String(limit));
      const res = await fetch(`/api/feature-flags?${q}`);
      if (!res.ok)
        throw new Error(`Failed to load feature flags: ${res.status}`);
      return (await res.json()) as FeatureFlagsResponse;
    },
    staleTime: 30_000,
  });

  const ownerOptions = useMemo(() => {
    if (!data?.owners) return [];

    return data.owners.map((g) => {
      // Apply the same filtering logic as filteredOwners but for each individual owner
      let flags = g.flags;

      // Apply rolled out filter
      if (rolledOutFilter !== 'all') {
        const isRolledOutFilter = rolledOutFilter === 'true';
        flags = flags.filter((flag) => {
          const isRolledOut =
            flag.rules?.some((rule) => {
              const isProductionRule =
                rule.environments?.includes('production') ||
                rule.name === 'Everyone';
              const isFullRollout = rule.passPercentage === 100;

              const hasPublicConditions =
                rule.conditions?.some(
                  (condition) =>
                    condition.type === 'public' ||
                    condition.type === 'passes_gate' ||
                    (condition.type === 'passes_segment' &&
                      condition.targetValue === 'everyone')
                ) ?? false;

              const isLaunched = flag.status === 'Launched';
              const isDisabled = flag.status === 'Disabled';
              const hasNoRestrictiveConditions = !rule.conditions?.some(
                (condition) =>
                  condition.type === 'email' ||
                  condition.type === 'user_id' ||
                  (condition.type === 'passes_segment' &&
                    condition.targetValue !== 'everyone')
              );

              return (
                isProductionRule &&
                isFullRollout &&
                (isLaunched ||
                  isDisabled ||
                  hasPublicConditions ||
                  hasNoRestrictiveConditions)
              );
            }) ?? false;

          return isRolledOut === isRolledOutFilter;
        });
      }

      // Apply staleness filter
      if (stalenessFilter !== 'all') {
        const isStaleFilter = stalenessFilter === 'stale';
        flags = flags.filter((flag) => {
          const isStale = flag.type === 'STALE' || flag.type === 'TEMPLATE';
          return isStale === isStaleFilter;
        });
      }

      return {
        ownerId: g.ownerId,
        ownerLabel: g.ownerLabel,
        count: flags.length,
      };
    });
  }, [data, rolledOutFilter, stalenessFilter]);

  const filteredOwners = useMemo(() => {
    let groups = data?.owners ?? [];
    if (ownerFilter !== 'all') {
      groups = groups.filter((g) => g.ownerLabel === ownerFilter);
    }
    const q = ownerQuery.trim().toLowerCase();
    if (q) {
      groups = groups.filter((g) => g.ownerLabel.toLowerCase().includes(q));
    }

    // Apply rolled out filter
    if (rolledOutFilter !== 'all') {
      const isRolledOutFilter = rolledOutFilter === 'true';
      groups = groups
        .map((group) => ({
          ...group,
          flags: group.flags.filter((flag) => {
            // A flag is considered "rolled out" if it has a production rule with 100% pass percentage
            // and conditions that indicate public access (not restricted to specific users/segments)
            // or is launched or disabled
            const isRolledOut =
              flag.rules?.some((rule) => {
                const isProductionRule =
                  rule.environments?.includes('production') ||
                  rule.name === 'Everyone';
                const isFullRollout = rule.passPercentage === 100;

                // Check if conditions indicate public access
                // Public conditions are typically those without specific user/email restrictions
                const hasPublicConditions =
                  rule.conditions?.some(
                    (condition) =>
                      condition.type === 'public' ||
                      condition.type === 'passes_gate' ||
                      (condition.type === 'passes_segment' &&
                        condition.targetValue === 'everyone')
                  ) ?? false;

                const isLaunched = flag.status === 'Launched';
                const isDisabled = flag.status === 'Disabled';
                // Alternative: if there are no restrictive conditions, it might be considered public
                const hasNoRestrictiveConditions = !rule.conditions?.some(
                  (condition) =>
                    condition.type === 'email' ||
                    condition.type === 'user_id' ||
                    (condition.type === 'passes_segment' &&
                      condition.targetValue !== 'everyone')
                );

                return (
                  isProductionRule &&
                  isFullRollout &&
                  (isLaunched ||
                    isDisabled ||
                    hasPublicConditions ||
                    hasNoRestrictiveConditions)
                );
              }) ?? false;

            return isRolledOut === isRolledOutFilter;
          }),
        }))
        .filter((group) => group.flags.length > 0); // Remove groups with no flags after filtering
    }

    // Apply staleness filter
    if (stalenessFilter !== 'all') {
      const isStaleFilter = stalenessFilter === 'stale';
      groups = groups
        .map((group) => ({
          ...group,
          flags: group.flags.filter((flag) => {
            // A flag is considered "stale" based on its type
            // Stale flag types from schema: "STALE" and "TEMPLATE"
            // Active flag types: "PERMANENT", "TEMPORARY" (actively in use)
            const isStale = flag.type === 'STALE' || flag.type === 'TEMPLATE';

            return isStale === isStaleFilter;
          }),
        }))
        .filter((group) => group.flags.length > 0); // Remove groups with no flags after filtering
    }

    return groups;
  }, [data, ownerFilter, ownerQuery, rolledOutFilter, stalenessFilter]);

  const flagsList = useMemo(
    () =>
      filteredOwners.flatMap((group) =>
        group.flags.map((f) => ({
          ...f,
          ownerId: group.ownerId,
          ownerLabel: group.ownerLabel,
        }))
      ),
    [filteredOwners]
  );

  const emojiForCount = (count: number) => {
    if (count <= 0) return '🎉';
    if (count <= 20) return '🙂';
    if (count <= 50) return '😅';
    if (count <= 150) return '💀';
    return '☠️';
  };

  if (isLoading) return <div className='p-6'>Loading…</div>;
  if (isError)
    return (
      <div className='p-6 text-red-600'>
        {(error && error.message) || 'Failed to load feature flags'}
      </div>
    );
  return (
    <div className='flex h-screen flex-col p-6'>
      <div className='mb-4 rounded-md border-border-secondary bg-background-primary p-3'>
        <div className='text-sm text-foreground-secondary'>
          📖 <strong>Cleanup Guide:</strong> Follow the{' '}
          <Link
            href='https://docs.statsig.com/feature-flags/feature-flags-lifecycle/'
            className='text-blue-500 underline hover:text-blue-700'
            target='_blank'
            rel='noopener noreferrer'
          >
            Statsig Feature Flag Lifecycle documentation
          </Link>{' '}
          for best practices on managing and cleaning up feature flags.
        </div>
      </div>
      <div className='mb-4 flex flex-wrap items-center gap-3'>
        <div className='flex items-center gap-2'>
          <label
            htmlFor='ownerSelect'
            className='text-sm text-foreground-secondary'
          >
            Owner
          </label>
          <select
            id='ownerSelect'
            value={ownerFilter}
            onChange={(e) => {
              const newValue = e.target.value;
              setOwnerFilter(newValue);
              updateUrl(newValue);
            }}
            className='rounded border border-gray-300 bg-background-primary px-2 py-1 text-sm text-foreground-primary'
          >
            <option value='all'>All owners</option>
            {ownerOptions.map((o) => (
              <option key={o.ownerId} value={o.ownerLabel}>
                {o.ownerLabel} ({o.count})
              </option>
            ))}
          </select>
        </div>

        <div className='flex items-center gap-2'>
          <label
            htmlFor='rolledOutSelect'
            className='text-sm text-foreground-secondary'
          >
            Status
          </label>
          <select
            id='rolledOutSelect'
            value={rolledOutFilter}
            onChange={(e) => {
              const newValue = e.target.value;
              setRolledOutFilter(newValue);
              updateUrl(undefined, undefined, undefined, newValue);
            }}
            className='rounded border border-gray-300 bg-background-primary px-2 py-1 text-sm text-foreground-primary'
          >
            <option value='all'>All flags</option>
            <option value='true'>Rolled out</option>
            <option value='false'>Not rolled out</option>
          </select>
        </div>

        <div className='flex items-center gap-2'>
          <label
            htmlFor='stalenessSelect'
            className='text-sm text-foreground-secondary'
          >
            Type
          </label>
          <select
            id='stalenessSelect'
            value={stalenessFilter}
            onChange={(e) => {
              const newValue = e.target.value;
              setStalenessFilter(newValue);
              updateUrl(undefined, undefined, undefined, undefined, newValue);
            }}
            className='rounded border border-gray-300 bg-background-primary px-2 py-1 text-sm text-foreground-primary'
          >
            <option value='all'>All types</option>
            <option value='stale'>Stale flags</option>
            <option value='active'>Active flags</option>
          </select>
        </div>
        <input
          className='rounded border border-gray-300 bg-background-primary px-3 py-2 text-foreground-primary placeholder:text-foreground-secondary'
          placeholder='Search owner…'
          value={ownerQuery}
          onChange={(e) => {
            const newValue = e.target.value;
            setOwnerQuery(newValue);
            updateUrl(undefined, undefined, newValue);
          }}
        />
        <div className='ml-auto flex items-center gap-2'>
          <button
            type='button'
            onClick={() => {
              setViewMode('grouped');
              updateUrl(undefined, 'grouped');
            }}
            className={`rounded-md border-border-secondary px-3 py-1 text-sm transition-colors ${
              viewMode === 'grouped'
                ? 'bg-background-secondary text-foreground-primary'
                : 'bg-background-primary text-foreground-secondary hover:bg-background-secondary hover:text-foreground-primary'
            }`}
          >
            Grouped
          </button>
          <button
            type='button'
            onClick={() => {
              setViewMode('list');
              updateUrl(undefined, 'list');
            }}
            className={`rounded-md border-border-secondary px-3 py-1 text-sm transition-colors ${
              viewMode === 'list'
                ? 'bg-background-secondary text-foreground-primary'
                : 'bg-background-primary text-foreground-secondary hover:bg-background-secondary hover:text-foreground-primary'
            }`}
          >
            List
          </button>
        </div>
      </div>

      <div className='mb-3 rounded-md border-border-secondary bg-background-secondary p-3 text-2xl text-foreground-primary'>
        <div className='flex flex-wrap items-center gap-4'>
          <div>
            <span className='mr-2 font-semibold'>Rolled out:</span>
            <span className='mr-2 font-medium'>
              {data?.owners?.reduce((acc, owner) => {
                return (
                  acc +
                  owner.flags.filter((flag) => {
                    return (
                      flag.rules?.some((rule) => {
                        const isProductionRule =
                          rule.environments?.includes('production') ||
                          rule.name === 'Everyone';
                        const isFullRollout = rule.passPercentage === 100;

                        const hasPublicConditions =
                          rule.conditions?.some(
                            (condition) =>
                              condition.type === 'public' ||
                              condition.type === 'passes_gate' ||
                              (condition.type === 'passes_segment' &&
                                condition.targetValue === 'everyone')
                          ) ?? false;

                        const isLaunched = flag.status === 'Launched';
                        const isDisabled = flag.status === 'Disabled';
                        const hasNoRestrictiveConditions =
                          !rule.conditions?.some(
                            (condition) =>
                              condition.type === 'email' ||
                              condition.type === 'user_id' ||
                              (condition.type === 'passes_segment' &&
                                condition.targetValue !== 'everyone')
                          );

                        return (
                          isProductionRule &&
                          isFullRollout &&
                          (isLaunched ||
                            isDisabled ||
                            hasPublicConditions ||
                            hasNoRestrictiveConditions)
                        );
                      }) ?? false
                    );
                  }).length
                );
              }, 0) ?? 0}
            </span>
            <span>🚀</span>
          </div>
          <div>
            <span className='mr-2 font-semibold'>Stale:</span>
            <span className='mr-2 font-medium'>
              {data?.owners?.reduce((acc, owner) => {
                return (
                  acc +
                  owner.flags.filter((flag) => {
                    return flag.type === 'STALE' || flag.type === 'TEMPLATE';
                  }).length
                );
              }, 0) ?? 0}
            </span>
            <span>🗑️</span>
          </div>
          <div>
            <span className='mr-2 font-semibold'>Total:</span>
            <span className='mr-2 font-medium'>{data?.count ?? 0}</span>
            <span>{emojiForCount(data?.count ?? 0)}</span>
          </div>
        </div>
      </div>

      <div className='mb-3 rounded-md border-border-secondary bg-background-primary p-3 text-lg text-foreground-primary'>
        <span className='mr-2 font-medium'>Showing:</span>
        <span className='mr-2 font-semibold'>{flagsList.length}</span>
        <span>flag{flagsList.length === 1 ? '' : 's'}</span>
        {(ownerFilter !== 'all' ||
          ownerQuery.trim() ||
          rolledOutFilter !== 'all' ||
          stalenessFilter !== 'all') && (
          <span className='ml-2 text-foreground-secondary'>(filtered)</span>
        )}
      </div>

      {data?.maybeTruncated && (
        <div className='mb-3 rounded-md border border-yellow-300 bg-yellow-50 p-3 text-sm text-yellow-900'>
          Returned {data.count} flags with limit={data.limitUsed}. You likely
          have more; bump the limit or enable server paging.
        </div>
      )}

      <div className='min-h-0 flex-1 overflow-y-auto'>
        {viewMode === 'grouped' ? (
          <div className='space-y-6'>
            {filteredOwners.map((group) => {
              const isCollapsed = collapsedOwners.has(group.ownerId);
              return (
                <div
                  key={group.ownerId}
                  className='rounded-lg border-border-secondary bg-background-primary p-4'
                >
                  <div className='mb-3 flex items-center justify-between'>
                    <div className='flex items-center gap-3'>
                      <button
                        type='button'
                        aria-label={isCollapsed ? 'Expand' : 'Collapse'}
                        className='rounded border-border-secondary bg-background-secondary px-1 py-0.5 text-xs text-foreground-primary transition-colors hover:bg-background-primary'
                        onClick={() =>
                          setCollapsedOwners((prev) => {
                            const next = new Set(prev);
                            if (next.has(group.ownerId))
                              next.delete(group.ownerId);
                            else next.add(group.ownerId);
                            return next;
                          })
                        }
                      >
                        {isCollapsed ? '▶' : '▼'}
                      </button>
                      <div className='text-lg font-semibold text-foreground-primary'>
                        {group.ownerLabel}
                      </div>
                    </div>
                    <div className='text-xs text-foreground-secondary'>
                      {group.flags.length} flag
                      {group.flags.length === 1 ? '' : 's'}
                      {' 🏴‍☠️'}
                    </div>
                  </div>
                  {!isCollapsed && (
                    <ul className='space-y-2'>
                      {group.flags.map((f) => (
                        <li
                          key={f.id}
                          className='flex items-start justify-between gap-4 rounded-lg border-border-secondary bg-background-secondary p-3'
                        >
                          <div>
                            <Link
                              href={`https://console.statsig.com/64RBMXCoSmsTc9oTU9ghAk/gates/${f.id}`}
                              className='font-medium text-blue-500 hover:text-blue-700'
                            >
                              {f.name || f.key}
                            </Link>
                            <div className='text-xs text-foreground-secondary'>
                              {f.type
                                ? `${f.type}  • ${f.typeReason}`
                                : f.isEnabled || f.is_enabled
                                  ? 'enabled'
                                  : 'disabled'}
                            </div>
                            <div className='text-xs text-foreground-secondary'>
                              {f.lastModifiedTime
                                ? `Updated ${new Date(f.lastModifiedTime).toLocaleString()} by ${f.lastModifierName || 'Unknown'}`
                                : f.updated_at
                                  ? `Updated ${new Date(f.updated_at).toLocaleString()} by ${f.lastModifierName || 'Unknown'}`
                                  : ''}
                            </div>
                            {f.description && (
                              <div className='text-sm text-foreground-tertiary'>
                                {f.description}
                              </div>
                            )}
                          </div>
                          {f.tags && f.tags.length > 0 && (
                            <div className='flex flex-wrap gap-2'>
                              {f.tags.map((t) => (
                                <span
                                  key={t}
                                  className='rounded border-border-secondary bg-background-primary px-2 py-1 text-xs text-foreground-secondary'
                                >
                                  {t}
                                </span>
                              ))}
                            </div>
                          )}
                        </li>
                      ))}
                    </ul>
                  )}
                </div>
              );
            })}
          </div>
        ) : (
          <ul className='space-y-2'>
            {flagsList.map((f) => (
              <li
                key={`${f.id}-${f.ownerId}`}
                className='flex items-start justify-between gap-4 rounded-lg border-border-secondary bg-background-primary p-3'
              >
                <div>
                  <Link
                    href={`https://console.statsig.com/64RBMXCoSmsTc9oTU9ghAk/gates/${f.id}`}
                    className='font-medium text-blue-500 hover:text-blue-700'
                  >
                    {f.name || f.key}
                  </Link>
                  <div className='text-xs text-foreground-secondary'>
                    Owner: {f.ownerLabel}
                  </div>
                  {f.description && (
                    <div className='text-sm text-foreground-primary'>
                      {f.description}
                    </div>
                  )}
                  <div className='text-xs text-foreground-secondary'>
                    {f.status ||
                      f.state ||
                      (f.isEnabled || f.is_enabled ? 'enabled' : 'disabled')}
                    {f.lastModifiedTime
                      ? ` • updated ${new Date(f.lastModifiedTime).toLocaleString()}`
                      : f.updated_at
                        ? ` • updated ${new Date(f.updated_at).toLocaleString()}`
                        : ''}
                  </div>
                </div>
                {f.tags && f.tags.length > 0 && (
                  <div className='flex flex-wrap gap-2'>
                    {f.tags.map((t) => (
                      <span
                        key={t}
                        className='rounded border-border-secondary bg-background-secondary px-2 py-1 text-xs text-foreground-secondary'
                      >
                        {t}
                      </span>
                    ))}
                  </div>
                )}
              </li>
            ))}
          </ul>
        )}
      </div>
    </div>
  );
}
