import { ChevronUp, Plus } from 'lucide-react';

import { useState } from 'react';

import { Head, router, useForm } from '@inertiajs/react';

import InputError from '@/Components/InputError';
import PageHeader from '@/Components/layout/PageHeader';
import { Badge } from '@/Components/ui/badge';
import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/Components/ui/card';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/Components/ui/dialog';
import { EmptyState } from '@/Components/ui/empty-state';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { LoadingButton } from '@/Components/ui/loading-button';
import { Textarea } from '@/Components/ui/textarea';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { FEATURE_REQUEST_STATUS_LABELS as STATUS_LABELS, FEATURE_REQUEST_STATUS_VARIANTS as STATUS_VARIANTS } from '@/lib/status';

type FeatureRequestStatus =
  | 'open'
  | 'pending'
  | 'under_review'
  | 'planned'
  | 'in_progress'
  | 'building'
  | 'shipped'
  | 'declined';

interface FeatureRequest {
  id: number;
  title: string;
  description: string | null;
  vote_count: number;
  status: FeatureRequestStatus;
  user: { id: number; name: string };
  created_at: string;
}

interface PaginatedFeatureRequests {
  data: FeatureRequest[];
  current_page: number;
  last_page: number;
  total: number;
}

interface Props {
  feature_requests: PaginatedFeatureRequests;
  voted_ids: number[];
  status_filter: string;
  status_counts: Record<string, number>;
  my_request_ids: number[];
}

const ROADMAP_TABS: { value: string; label: string }[] = [
  { value: '', label: 'All' },
  { value: 'under_review', label: 'Under Review' },
  { value: 'planned', label: 'Planned' },
  { value: 'in_progress', label: 'In Progress' },
  { value: 'building', label: 'Building' },
  { value: 'shipped', label: 'Shipped' },
];

export default function FeatureRequestsIndex({
  feature_requests,
  voted_ids,
  status_filter,
  status_counts,
  my_request_ids,
}: Props) {
  const [open, setOpen] = useState(false);
  const votedSet = new Set(voted_ids);
  const myRequestSet = new Set(my_request_ids);

  const { data, setData, post, processing, errors, reset } = useForm({
    title: '',
    description: '',
  });

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    post(route('feature-requests.store'), {
      onSuccess: () => {
        reset();
        setOpen(false);
      },
    });
  }

  function handleVote(id: number) {
    router.post(
      route('feature-requests.vote', { featureRequest: id }),
      {},
      {
        preserveScroll: true,
      },
    );
  }

  function handleTabChange(status: string) {
    router.visit(route('feature-requests.index'), {
      data: status ? { status } : {},
      preserveScroll: false,
      replace: true,
    });
  }

  const totalCount = Object.values(status_counts).reduce((sum, n) => sum + n, 0);

  function tabCount(tab: { value: string }): number {
    if (tab.value === '') return totalCount;
    return status_counts[tab.value] ?? 0;
  }

  return (
    <DashboardLayout>
      <Head title="Feature Requests" />

      <PageHeader
        title="Feature Requests"
        subtitle="Vote on features you'd like to see, or suggest your own ideas."
        actions={
          <Dialog open={open} onOpenChange={setOpen}>
            <DialogTrigger asChild>
              <Button>
                <Plus className="mr-2 h-4 w-4" />
                Suggest Feature
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>Suggest a Feature</DialogTitle>
              </DialogHeader>
              <form onSubmit={handleSubmit} className="space-y-4">
                <div className="space-y-1">
                  <Label htmlFor="title">Title</Label>
                  <Input
                    id="title"
                    value={data.title}
                    onChange={(e) => setData('title', e.target.value)}
                    placeholder="Brief description of the feature"
                    maxLength={150}
                  />
                  <InputError message={errors.title} />
                </div>
                <div className="space-y-1">
                  <Label htmlFor="description">Description (optional)</Label>
                  <Textarea
                    id="description"
                    value={data.description}
                    onChange={(e) => setData('description', e.target.value)}
                    placeholder="Why would this feature be useful?"
                    rows={4}
                    maxLength={1000}
                  />
                  <InputError message={errors.description} />
                </div>
                <div className="flex justify-end gap-2">
                  <Button type="button" variant="outline" onClick={() => setOpen(false)}>
                    Cancel
                  </Button>
                  <LoadingButton type="submit" loading={processing}>
                    Submit Request
                  </LoadingButton>
                </div>
              </form>
            </DialogContent>
          </Dialog>
        }
      />

      {/* Roadmap status tabs */}
      <div className="mt-6 flex flex-wrap gap-2 border-b border-border pb-3">
        {ROADMAP_TABS.map((tab) => {
          const count = tabCount(tab);
          const isActive = status_filter === tab.value;
          return (
            <button
              key={tab.value}
              onClick={() => handleTabChange(tab.value)}
              className={`flex items-center gap-1.5 rounded-full px-3 py-1 text-sm font-medium transition-colors ${
                isActive
                  ? 'bg-primary text-primary-foreground'
                  : 'bg-muted text-muted-foreground hover:bg-muted/80 hover:text-foreground'
              }`}
            >
              {tab.label}
              {count > 0 && (
                <span
                  className={`rounded-full px-1.5 py-0.5 text-xs ${
                    isActive ? 'bg-primary-foreground/20 text-primary-foreground' : 'bg-background text-foreground'
                  }`}
                >
                  {count}
                </span>
              )}
            </button>
          );
        })}
      </div>

      <div className="mt-4 space-y-3">
        {feature_requests.data.length === 0 ? (
          <EmptyState
            title="No feature requests yet"
            description={
              status_filter
                ? `No requests with status "${STATUS_LABELS[status_filter] ?? status_filter}" found.`
                : 'Be the first to suggest a feature you\'d like to see.'
            }
          />
        ) : (
          feature_requests.data.map((request) => (
            <Card key={request.id} className="transition-shadow hover:shadow-sm">
              <CardHeader className="pb-2">
                <div className="flex items-start justify-between gap-4">
                  <div className="flex-1 space-y-1">
                    <div className="flex flex-wrap items-center gap-2">
                      <CardTitle className="text-base">{request.title}</CardTitle>
                      {myRequestSet.has(request.id) && (
                        <span className="rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">
                          Your request
                        </span>
                      )}
                    </div>
                    {request.description && (
                      <CardDescription>{request.description}</CardDescription>
                    )}
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge variant={STATUS_VARIANTS[request.status] ?? 'outline'}>
                      {STATUS_LABELS[request.status] ?? request.status}
                    </Badge>
                    <Button
                      variant={votedSet.has(request.id) ? 'default' : 'outline'}
                      size="sm"
                      className="flex h-14 w-14 flex-col gap-0.5"
                      onClick={() => handleVote(request.id)}
                      aria-label={`Upvote ${request.title}`}
                      aria-pressed={votedSet.has(request.id)}
                    >
                      <ChevronUp className="h-4 w-4" />
                      <span className="text-xs font-semibold">{request.vote_count}</span>
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <p className="text-muted-foreground text-xs">Suggested by {request.user.name}</p>
              </CardContent>
            </Card>
          ))
        )}
      </div>
    </DashboardLayout>
  );
}
