'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import {
  Crown,
  CreditCard,
  AlertTriangle,
  ArrowRightLeft,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { ConfirmDialog } from '@/components/shared/ConfirmDialog';
import { PageLoader } from '@/components/shared/Loader';
import { useSubscription } from '@/hooks/useSubscription';
import { formatDate, getStatusLabel, getStatusBadgeClass } from '@/utils';
import { ROUTES } from '@/constants';

interface SubscriptionSectionProps {
  onChangePlan?: () => void;
}

export function SubscriptionSection({ onChangePlan }: SubscriptionSectionProps) {
  const {
    subscription,
    fetchSub,
    isLoading,
    cancel,
    isActive,
    isTrialing,
    hasScheduledPlanChange,
  } = useSubscription();

  const [cancelDialogOpen, setCancelDialogOpen] = useState(false);
  const [cancelLoading, setCancelLoading] = useState(false);

  useEffect(() => {
    fetchSub();
  }, [fetchSub]);

  const handleCancelSubscription = async () => {
    setCancelLoading(true);
    const success = await cancel();
    setCancelLoading(false);
    if (success) setCancelDialogOpen(false);
  };

  if (isLoading && !subscription) {
    return <PageLoader text="Loading subscription…" />;
  }

  const changePlanButton = !isTrialing && (
    <Button
      variant="gold-outline"
      size="sm"
      {...(onChangePlan
        ? { onClick: onChangePlan }
        : { asChild: true })}
    >
      {onChangePlan ? (
        <>
          <CreditCard className="h-4 w-4" /> Change Plan
        </>
      ) : (
        <Link href={ROUTES.PRICING}>
          <CreditCard className="h-4 w-4" /> Change Plan
        </Link>
      )}
    </Button>
  );

  const viewPlansButton = (
    <Button
      variant="gold"
      size="sm"
      {...(onChangePlan ? { onClick: onChangePlan } : { asChild: true })}
    >
      {onChangePlan ? 'View Plans' : <Link href={ROUTES.PRICING}>View Plans</Link>}
    </Button>
  );

  return (
    <>
      <Card>
        <CardHeader>
          <CardTitle className="text-base flex items-center gap-2">
            <Crown className="h-4 w-4 text-brand-500 dark:text-brand-300" /> Subscription
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {subscription ? (
            <>
              <div className="flex items-start justify-between gap-3">
                <div className="min-w-0">
                  <p className="font-medium">{subscription.plan_name || 'Free Trial'}</p>
                  <p className="text-sm text-muted-foreground">
                    {isTrialing
                      ? `Trial ends ${formatDate(subscription.trial_end!)}`
                      : `Renews ${formatDate(subscription.current_period_end!)}`}
                  </p>
                </div>
                <span
                  className={`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold shrink-0 ${getStatusBadgeClass(subscription.status)}`}
                >
                  {getStatusLabel(subscription.status)}
                </span>
              </div>

              {subscription.cancel_at_period_end && (
                <div className="rounded-lg border border-amber-500/20 bg-amber-50 dark:bg-amber-500/5 p-3 flex items-start gap-2">
                  <AlertTriangle className="h-4 w-4 text-amber-600 dark:text-amber-400 mt-0.5 shrink-0" />
                  <p className="text-sm text-amber-700 dark:text-amber-400">
                    Your subscription is cancelled and will end on{' '}
                    <strong>{formatDate(subscription.current_period_end!)}</strong>. You still
                    have full access until then.
                  </p>
                </div>
              )}

              {hasScheduledPlanChange && (
                <div className="rounded-lg border border-blue-500/20 bg-blue-50 dark:bg-blue-500/5 p-3 flex items-start gap-2">
                  <ArrowRightLeft className="h-4 w-4 text-blue-600 dark:text-blue-400 mt-0.5 shrink-0" />
                  <div className="text-sm text-blue-700 dark:text-blue-400">
                    <p className="font-medium">Plan change scheduled</p>
                    <p className="mt-0.5">
                      Your next plan <strong>{subscription.next_plan_name}</strong> will start on{' '}
                      <strong>{formatDate(subscription.next_plan_start_date!)}</strong>, after your
                      current plan ends.
                    </p>
                  </div>
                </div>
              )}

              <Separator />

              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <p className="text-muted-foreground">Current period start</p>
                  <p className="font-medium mt-0.5">
                    {formatDate(subscription.current_period_start!)}
                  </p>
                </div>
                <div>
                  <p className="text-muted-foreground">Current period end</p>
                  <p className="font-medium mt-0.5">
                    {formatDate(subscription.current_period_end!)}
                  </p>
                </div>
              </div>

              <div className="flex flex-wrap gap-3">
                {changePlanButton}
                {isActive &&
                  !!subscription.stripe_subscription_id &&
                  !subscription.cancel_at_period_end && (
                  <Button
                    variant="ghost"
                    size="sm"
                    className="text-destructive hover:text-destructive hover:bg-destructive/10"
                    onClick={() => setCancelDialogOpen(true)}
                  >
                    Cancel Subscription
                  </Button>
                )}
              </div>
            </>
          ) : (
            <div className="text-center py-6 space-y-3">
              <p className="text-muted-foreground text-sm">No active subscription</p>
              {viewPlansButton}
            </div>
          )}
        </CardContent>
      </Card>

      <ConfirmDialog
        open={cancelDialogOpen}
        onOpenChange={setCancelDialogOpen}
        title="Cancel Subscription?"
        description="Your subscription will be cancelled at the end of the current billing period. You'll keep full access until then. This action cannot be undone."
        confirmLabel="Yes, Cancel Subscription"
        cancelLabel="Keep Subscription"
        onConfirm={handleCancelSubscription}
        isLoading={cancelLoading}
        variant="danger"
      />
    </>
  );
}
