'use client';

import { useQuery } from '@tanstack/react-query';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeft, CreditCard, User, Pencil } from 'lucide-react';

import { subscriptionsApi } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';

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

export function SubscriptionDetailClient() {
  const params = useParams();
  const subscriptionId = Number(params.id);

  const { data: subscription, isLoading, error } = useQuery({
    queryKey: ['subscription', subscriptionId],
    queryFn: () => subscriptionsApi.get(subscriptionId),
    enabled: !!subscriptionId,
  });

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-muted-foreground">Loading...</div>
      </div>
    );
  }

  if (error || !subscription) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-red-500">Failed to load subscription</div>
      </div>
    );
  }

  const isExpired = subscription.expires_at && new Date(subscription.expires_at) < new Date();
  const isCancelled = !!subscription.cancelled_at;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon" asChild>
            <Link href="/subscriptions">
              <ArrowLeft className="h-4 w-4" />
            </Link>
          </Button>
          <div>
            <div className="flex items-center gap-2">
              <CreditCard className="h-5 w-5 text-muted-foreground" />
              <h1 className="text-2xl font-bold">{subscription.username}</h1>
              <Badge variant={tierColors[subscription.tier] || 'outline'} className="capitalize">
                {subscription.tier}
              </Badge>
            </div>
            <p className="text-muted-foreground">{subscription.user_email}</p>
          </div>
        </div>
        <Button variant="outline" asChild>
          <Link href={`/subscriptions/${subscriptionId}/edit`}>
            <Pencil className="mr-2 h-4 w-4" />
            Edit
          </Link>
        </Button>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        {/* Subscription Details */}
        <Card>
          <CardHeader>
            <CardTitle>Subscription Details</CardTitle>
            <CardDescription>Current subscription information</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center gap-2">
              <User className="h-4 w-4 text-muted-foreground" />
              <Link href={`/users/${subscription.user_id}`} className="text-blue-600 hover:underline">
                View User Profile
              </Link>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <div className="text-sm font-medium text-muted-foreground">Tier</div>
                <Badge variant={tierColors[subscription.tier] || 'outline'} className="capitalize">
                  {subscription.tier}
                </Badge>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Platform</div>
                <Badge variant="outline" className="capitalize">
                  {subscription.platform || 'N/A'}
                </Badge>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Auto Renew</div>
                <Badge variant={subscription.auto_renew ? 'default' : 'secondary'}>
                  {subscription.auto_renew ? 'Enabled' : 'Disabled'}
                </Badge>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Status</div>
                {isCancelled ? (
                  <Badge variant="destructive">Cancelled</Badge>
                ) : isExpired ? (
                  <Badge variant="destructive">Expired</Badge>
                ) : (
                  <Badge variant="default">Active</Badge>
                )}
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Dates */}
        <Card>
          <CardHeader>
            <CardTitle>Dates</CardTitle>
            <CardDescription>Subscription timeline</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <div className="text-sm font-medium text-muted-foreground">Created</div>
                <div>{new Date(subscription.created_at).toLocaleDateString()}</div>
              </div>
              {subscription.subscribed_at && (
                <div>
                  <div className="text-sm font-medium text-muted-foreground">Subscribed</div>
                  <div>{new Date(subscription.subscribed_at).toLocaleDateString()}</div>
                </div>
              )}
              {subscription.expires_at && (
                <div>
                  <div className="text-sm font-medium text-muted-foreground">Expires</div>
                  <div className={isExpired ? 'text-red-500 font-medium' : ''}>
                    {new Date(subscription.expires_at).toLocaleDateString()}
                    {isExpired && ' (Expired)'}
                  </div>
                </div>
              )}
              {subscription.cancelled_at && (
                <div>
                  <div className="text-sm font-medium text-muted-foreground">Cancelled</div>
                  <div className="text-red-500">
                    {new Date(subscription.cancelled_at).toLocaleDateString()}
                  </div>
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
