import { AlertCircle, Circle, CircleCheck, Filter, Plus, Search } from 'lucide-react';
import { useState } from 'react';
import { Link, useParams } from 'react-router-dom';

import { useIssueList } from '@/hooks/issue/useIssueList';
import { cn, timeAgo } from '@/lib/utils';

const STATE_FILTERS = [
  { value: null, label: 'All' },
  { value: 'Open', label: 'Open' },
  { value: 'Closed', label: 'Closed' },
] as const;

const PRIORITY_FILTERS = [
  { value: null, label: 'Any' },
  { value: 'Critical', label: 'Critical' },
  { value: 'High', label: 'High' },
  { value: 'Medium', label: 'Medium' },
  { value: 'Low', label: 'Low' },
  { value: 'None', label: 'None' },
] as const;

export function WorkspaceIssuesPage() {
  const { workspaceName = '' } = useParams();

  const [stateFilter, setStateFilter] = useState<string | null>(null);
  const [priorityFilter, setPriorityFilter] = useState<string | null>(null);
  const [offset, setOffset] = useState(0);
  const limit = 25;

  const { data: issuesData, isLoading } = useIssueList(workspaceName, {
    state: stateFilter,
    priority: priorityFilter,
    limit,
    offset,
  });

  const issues = issuesData ?? [];

  return (
    <div className="px-6 pt-6 pb-10">
      <div className="mb-6 flex items-center justify-between">
        <h1 className="text-xl font-semibold text-foreground">Issues</h1>
        <Link
          to={`/${workspaceName}/issues/new`}
          className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-[5px] text-[13px] font-medium text-primary-foreground transition-colors hover:bg-primary/85"
        >
          <Plus className="size-3.5" />
          New issue
        </Link>
      </div>

      <div className="mb-4 flex flex-wrap items-center gap-3">
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground" />
          <input
            type="text"
            placeholder="Search issues..."
            className="w-full rounded-lg border border-border bg-card pl-8 pr-3 py-[5px] text-[13px] text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"
          />
        </div>

        <div className="flex items-center gap-2">
          <Filter className="size-3.5 text-muted-foreground" />
          <select
            value={stateFilter ?? ''}
            onChange={(e) => {
              setOffset(0);
              setStateFilter(e.target.value || null);
            }}
            className="rounded-lg border border-border bg-card px-3 py-[5px] text-[13px] text-foreground focus:outline-none focus:ring-2 focus:ring-ring"
          >
            {STATE_FILTERS.map((f) => (
              <option key={f.label} value={f.value ?? ''}>
                {f.label}
              </option>
            ))}
          </select>

          <select
            value={priorityFilter ?? ''}
            onChange={(e) => {
              setOffset(0);
              setPriorityFilter(e.target.value || null);
            }}
            className="rounded-lg border border-border bg-card px-3 py-[5px] text-[13px] text-foreground focus:outline-none focus:ring-2 focus:ring-ring"
          >
            {PRIORITY_FILTERS.map((f) => (
              <option key={f.label} value={f.value ?? ''}>
                {f.label}
              </option>
            ))}
          </select>
        </div>
      </div>

      {isLoading ? (
        <div className="flex items-center gap-2 py-12 text-[14px] text-muted-foreground">
          <span className="inline-block size-4 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
          Loading issues…
        </div>
      ) : issues.length === 0 ? (
        <div className="flex flex-col items-center justify-center rounded-xl border border-dashed border-border py-16 text-center">
          <AlertCircle className="size-8 text-muted-foreground/40" />
          <p className="mt-3 text-[14px] text-muted-foreground">
            {stateFilter || priorityFilter ? 'No issues match your filters' : 'No issues yet'}
          </p>
        </div>
      ) : (
        <div className="overflow-hidden rounded-xl border border-border">
          {issues.map((issue) => (
            <Link
              key={issue.id}
              to={`/${workspaceName}/issues/${issue.number}`}
              className="flex items-start gap-3 px-4 py-3 border-b border-border last:border-b-0 hover:bg-muted/50 transition-colors"
            >
              <StatusIcon state={issue.state} priority={issue.priority} />
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-2">
                  <span className="text-[14px] font-medium text-foreground hover:text-primary truncate">
                    {issue.title}
                  </span>
                </div>
                <div className="mt-1 flex items-center gap-3 text-[12px] text-muted-foreground">
                  <span>#{issue.number}</span>
                  <span>
                    {issue.author.display_name ?? issue.author.username} opened{' '}
                    {timeAgo(issue.created_at)}
                  </span>
                  {issue.priority && issue.priority !== 'None' && (
                    <PriorityBadge priority={issue.priority} />
                  )}
                </div>
              </div>
            </Link>
          ))}
        </div>
      )}

      <div className="mt-4 flex items-center justify-between">
        <span className="text-[13px] text-muted-foreground">
          Showing {issues.length} issue{issues.length !== 1 ? 's' : ''}
        </span>
        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={() => setOffset(Math.max(0, offset - limit))}
            disabled={offset === 0}
            className="rounded-lg border border-border px-3 py-1 text-[13px] font-medium text-foreground transition-colors hover:bg-muted disabled:opacity-50"
          >
            Previous
          </button>
          <button
            type="button"
            onClick={() => setOffset(offset + limit)}
            disabled={issues.length < limit}
            className="rounded-lg border border-border px-3 py-1 text-[13px] font-medium text-foreground transition-colors hover:bg-muted disabled:opacity-50"
          >
            Next
          </button>
        </div>
      </div>
    </div>
  );
}

function StatusIcon({ state, priority }: { state: string; priority?: string | null }) {
  const isClosed = state === 'Closed';
  const isCritical = priority === 'Critical';
  const isHigh = priority === 'High';

  return (
    <div className="mt-0.5 shrink-0">
      {isClosed ? (
        <CircleCheck className="size-5 text-purple-500" />
      ) : isCritical ? (
        <AlertCircle className="size-5 text-destructive" />
      ) : isHigh ? (
        <AlertCircle className="size-5 text-amber-500" />
      ) : (
        <Circle className="size-5 text-green-500" />
      )}
    </div>
  );
}

function PriorityBadge({ priority }: { priority: string }) {
  return (
    <span
      className={cn(
        'inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium capitalize',
        priority === 'Critical'
          ? 'bg-destructive/10 text-destructive'
          : priority === 'High'
            ? 'bg-amber-500/10 text-amber-600'
            : priority === 'Medium'
              ? 'bg-blue-500/10 text-blue-600'
              : 'bg-muted text-muted-foreground',
      )}
    >
      {priority}
    </span>
  );
}
