import { useState } from 'react';
import { useParams } from 'react-router-dom';
import { Plus, Tag, Trash2 } from 'lucide-react';

import { Pagination } from '@/components/repo/Pagination';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Spinner } from '@/components/ui/spinner';
import { useCreateRelease } from '@/hooks/repo/useCreateRelease';
import { useDeleteRelease } from '@/hooks/repo/useDeleteRelease';
import { useRepoReleases } from '@/hooks/repo/useRepoReleases';
import { timeAgo } from '@/lib/utils';

const LIMIT = 10;

export function RepoReleasesPage() {
  const { workspaceName = '', repoName = '' } = useParams();
  const [offset, setOffset] = useState(0);
  const [showCreate, setShowCreate] = useState(false);
  const [tagName, setTagName] = useState('');
  const [title, setTitle] = useState('');
  const [body, setBody] = useState('');
  const [draft, setDraft] = useState(false);
  const [prerelease, setPrerelease] = useState(false);

  const { data: releases, isLoading } = useRepoReleases(workspaceName, repoName, LIMIT, offset);
  const createRelease = useCreateRelease();
  const deleteRelease = useDeleteRelease();

  const handleCreate = () => {
    if (!tagName.trim() || !title.trim()) return;
    createRelease.mutate(
      {
        tag_name: tagName.trim(),
        title: title.trim(),
        body: body.trim() || undefined,
        draft,
        prerelease,
      },
      {
        onSuccess: () => {
          setTagName('');
          setTitle('');
          setBody('');
          setDraft(false);
          setPrerelease(false);
          setShowCreate(false);
        },
      },
    );
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <p className="text-[12px] text-muted-foreground">
          {(releases ?? []).length} release{(releases ?? []).length !== 1 ? 's' : ''}
        </p>
        <Button size="sm" onClick={() => setShowCreate(!showCreate)}>
          <Plus className="size-3.5" />
          New release
        </Button>
      </div>

      {showCreate && (
        <div className="space-y-3 rounded-lg border border-border p-4">
          <h3 className="text-[14px] font-semibold text-foreground">Create a new release</h3>
          <Input
            className="h-9 text-[13px]"
            placeholder="Tag name (e.g. v1.0.0)"
            value={tagName}
            onChange={(e) => setTagName(e.target.value)}
          />
          <Input
            className="h-9 text-[13px]"
            placeholder="Release title"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
          />
          <textarea
            className="w-full rounded-lg border border-border bg-background px-3 py-2 text-[13px] text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"
            rows={4}
            placeholder="Describe this release..."
            value={body}
            onChange={(e) => setBody(e.target.value)}
          />
          <div className="flex items-center gap-4">
            <label className="flex items-center gap-2 text-[13px]">
              <input
                type="checkbox"
                checked={draft}
                onChange={(e) => setDraft(e.target.checked)}
                className="rounded border-border"
              />
              Draft
            </label>
            <label className="flex items-center gap-2 text-[13px]">
              <input
                type="checkbox"
                checked={prerelease}
                onChange={(e) => setPrerelease(e.target.checked)}
                className="rounded border-border"
              />
              Pre-release
            </label>
          </div>
          <div className="flex gap-2">
            <Button
              size="sm"
              disabled={!tagName.trim() || !title.trim() || createRelease.isPending}
              onClick={handleCreate}
            >
              {createRelease.isPending ? 'Creating...' : 'Create release'}
            </Button>
            <Button size="sm" variant="outline" onClick={() => setShowCreate(false)}>
              Cancel
            </Button>
          </div>
        </div>
      )}

      <div className="space-y-4">
        {isLoading ? (
          <div className="flex items-center justify-center py-12">
            <Spinner />
          </div>
        ) : (releases ?? []).length > 0 ? (
          <>
            {(releases ?? []).map((release) => (
              <div
                key={release.id}
                className="rounded-xl border border-border bg-card p-5"
              >
                <div className="flex items-start justify-between">
                  <div>
                    <div className="flex items-center gap-2">
                      <Tag className="size-4 text-primary" />
                      <h3 className="text-[16px] font-bold text-foreground">{release.title}</h3>
                    </div>
                    <div className="mt-1 flex items-center gap-2 text-[12px] text-muted-foreground">
                      <code className="rounded bg-muted px-1.5 py-0.5 text-[11px]">
                        {release.tag_name}
                      </code>
                      {release.draft && (
                        <span className="rounded border border-border bg-muted/30 px-1.5 py-0.5 text-[10px]">
                          Draft
                        </span>
                      )}
                      {release.prerelease && (
                        <span className="rounded border border-amber-500/30 bg-amber-500/5 px-1.5 py-0.5 text-[10px] text-amber-600">
                          Pre-release
                        </span>
                      )}
                      <span>{timeAgo(release.published_at || release.created_at)}</span>
                    </div>
                  </div>
                  <Button
                    size="icon-sm"
                    variant="ghost"
                    className="text-muted-foreground hover:text-destructive"
                    onClick={() => {
                      if (confirm(`Delete release "${release.title}"?`))
                        deleteRelease.mutate(release.id);
                    }}
                  >
                    <Trash2 className="size-3.5" />
                  </Button>
                </div>
                {release.body && (
                  <pre className="mt-3 whitespace-pre-wrap text-[13px] text-foreground">
                    {release.body}
                  </pre>
                )}
              </div>
            ))}
            <Pagination
              offset={offset}
              limit={LIMIT}
              hasMore={(releases ?? []).length >= LIMIT}
              onPrev={() => setOffset(Math.max(0, offset - LIMIT))}
              onNext={() => setOffset(offset + LIMIT)}
            />
          </>
        ) : (
          <div className="flex flex-col items-center justify-center py-16 text-center">
            <Tag className="size-6 text-muted-foreground/30" />
            <p className="mt-3 text-[13px] text-muted-foreground">No releases yet</p>
            <Button size="sm" className="mt-3" onClick={() => setShowCreate(true)}>
              <Plus className="size-3.5" />
              Create first release
            </Button>
          </div>
        )}
      </div>
    </div>
  );
}
