'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { ColumnDef } from '@tanstack/react-table';
import Link from 'next/link';
import { MoreHorizontal } from 'lucide-react';

import { subscriptionsApi } from '@/lib/api';
import type { Subscription } from '@/types/models';
import { DataTable } from '@/components/data-table';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';

const tierColors: Record<string, 'default' | 'secondary' | 'outline'> = {
  free: 'secondary',
  premium: 'default',
  pro: 'default',
};

const columns: ColumnDef<Subscription>[] = [
  {
    accessorKey: 'id',
    header: 'ID',
    cell: ({ row }) => (
      <span className="font-mono text-sm text-muted-foreground">
        {row.original.id}
      </span>
    ),
  },
  {
    accessorKey: 'username',
    header: 'User',
    cell: ({ row }) => (
      <Link
        href={`/subscriptions/${row.original.id}`}
        className="font-medium text-blue-600 hover:underline"
      >
        <div>{row.original.username}</div>
        <div className="text-sm text-muted-foreground">{row.original.user_email}</div>
      </Link>
    ),
  },
  {
    accessorKey: 'tier',
    header: 'Tier',
    cell: ({ row }) => (
      <Badge variant={tierColors[row.original.tier] || 'outline'} className="capitalize">
        {row.original.tier}
      </Badge>
    ),
  },
  {
    accessorKey: 'platform',
    header: 'Platform',
    cell: ({ row }) => (
      <Badge variant="outline" className="capitalize">
        {row.original.platform || 'N/A'}
      </Badge>
    ),
  },
  {
    accessorKey: 'auto_renew',
    header: 'Auto Renew',
    cell: ({ row }) => (
      <Badge variant={row.original.auto_renew ? 'default' : 'secondary'}>
        {row.original.auto_renew ? 'Yes' : 'No'}
      </Badge>
    ),
  },
  {
    accessorKey: 'expires_at',
    header: 'Expires',
    cell: ({ row }) => {
      if (!row.original.expires_at) return '-';
      const date = new Date(row.original.expires_at);
      const isExpired = date < new Date();
      return (
        <span className={isExpired ? 'text-red-500' : ''}>
          {date.toLocaleDateString()}
          {isExpired && ' (Expired)'}
        </span>
      );
    },
  },
  {
    accessorKey: 'created_at',
    header: 'Created',
    cell: ({ row }) => {
      const date = new Date(row.original.created_at);
      return date.toLocaleDateString();
    },
  },
  {
    id: 'actions',
    cell: ({ row }) => {
      const subscription = row.original;
      return (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" className="h-8 w-8 p-0">
              <span className="sr-only">Open menu</span>
              <MoreHorizontal className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuLabel>Actions</DropdownMenuLabel>
            <DropdownMenuItem asChild>
              <Link href={`/subscriptions/${subscription.id}`}>View details</Link>
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      );
    },
  },
];

export default function SubscriptionsPage() {
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [search, setSearch] = useState('');

  const { data, isLoading } = useQuery({
    queryKey: ['subscriptions', { page, per_page: pageSize, search }],
    queryFn: () => subscriptionsApi.list({ page, per_page: pageSize, search: search || undefined }),
  });

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Subscriptions</h1>
          <p className="text-muted-foreground">
            Manage user subscriptions and billing
          </p>
        </div>
      </div>

      <DataTable
        columns={columns}
        data={data?.data ?? []}
        totalCount={data?.total ?? 0}
        page={page}
        pageSize={pageSize}
        onPageChange={setPage}
        onPageSizeChange={(size) => {
          setPageSize(size);
          setPage(1);
        }}
        searchValue={search}
        onSearchChange={(value) => {
          setSearch(value);
          setPage(1);
        }}
        searchPlaceholder="Search by user..."
        isLoading={isLoading}
      />
    </div>
  );
}
