'use client';
import React, { Fragment, useState } from 'react';
import { useForm, useFieldArray } from 'react-hook-form';
import { toast } from 'sonner';
import { Loader2 } from 'lucide-react';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { formatPlanName } from '@/lib/utils/format-plan';
import {
  Form,
  FormField,
  FormItem,
  FormLabel,
  FormControl,
  FormMessage
} from '@/components/ui/form';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import { BusinessOption } from '@/types/interfaces';
import { client } from '@/lib/auth/auth-client';
import { api } from '@/lib/trpc/client';

const STATUS_LABELS: Record<string, string> = {
  active: 'Aktiv',
  trialing: 'Prøveperiode',
  canceled: 'Afmeldt',
  incomplete: 'Ufuldstændig',
  past_due: 'Forfalden',
  unpaid: 'Ubetalt'
};

interface Props {
  organizationId: string;
  tariffPlans: (BusinessOption & { plan: string; seats: number })[];
  currentPlan: (BusinessOption & { plan: string; seats: number }) | undefined;
  memberCount: number;
}

const OrganizationSubscription: React.FC<Props> = (props) => {
  const { organizationId, tariffPlans, currentPlan, memberCount } = props;

  const [selectedPlan, setSelectedPlan] = useState<string | undefined>(
    currentPlan?.value
  );
  const [loading, setLoading] = useState(false);

  const { data: subscriptions = [] } = api.payment.subscription.list.useQuery({
    organizationId
  });

  const handlePlanChange = async (value: string | null) => {
    if (!value) {
      toast.error('Vælg venligst et abonnement');
      return;
    }

    setSelectedPlan(value);

    try {
      setLoading(true);
      const selectedPlan = tariffPlans.find((plan) => plan.value === value);
      console.log('selectedPlan; ', selectedPlan);

      if (!selectedPlan || !currentPlan) {
        toast.error('Kunne ikke finde abonnementet');
        return;
      }

      if (
        selectedPlan.plan === currentPlan.plan &&
        selectedPlan.seats < memberCount
      ) {
        toast.error(
          `Der er allerede ${currentPlan.seats} medlemmer. Du kan ikke sætte pladser lavere end dette. Fjern venligst medlemmer, før du fortsætter.`
        );
        return;
      }

      const { data, error } = await client.subscription.upgrade({
        plan: selectedPlan.plan,
        // annual: true,
        referenceId: organizationId,
        subscriptionId: subscriptions[0].id,
        seats: selectedPlan.seats,
        successUrl: `${window.location.origin}/profile/organization/${organizationId}?checkout=success`,
        cancelUrl: `${window.location.origin}/profile/organization/${organizationId}`,
        disableRedirect: true
      });

      if (error) {
        toast.error(error.message);
        return;
      }

      if (data?.url) {
        window.location.href = data.url;
      }
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <section className='mx-auto w-full max-w-[1362px] grow p-3 md:px-8 md:py-4 xl:border-x'>
      <div className='flex flex-col xl:flex-row'>
        <div className='shrink-0 xl:w-68'>
          <h2 className='mb-4 text-xl leading-none font-bold text-[#CBCBCB] md:text-3xl'>
            abonnement
          </h2>
        </div>

        <div>
          <Card className='w-full gap-3 rounded-none border-0 bg-neutral-50 font-serif shadow-none'>
            {subscriptions.map((subscription) => (
              <Fragment key={subscription.id}>
                <CardHeader className='flex flex-col gap-2 md:flex-row md:items-center md:justify-between'>
                  <CardTitle>{formatPlanName(subscription.plan)}</CardTitle>
                  <Badge
                    variant={
                      subscription.status === 'active' ? 'default' : 'secondary'
                    }
                  >
                    {STATUS_LABELS[subscription.status] || subscription.status}
                  </Badge>
                </CardHeader>
                <CardContent className='space-y-4'>
                  <div className='grid gap-4 md:grid-cols-2'>
                    <div className='space-y-1'>
                      <p className='text-muted-foreground text-sm'>
                        {subscription.seats} pladser
                      </p>
                    </div>
                  </div>
                  <Separator className='my-4' />
                  <div className='grid gap-2'>
                    {loading ? (
                      <Loader2 className='animate-spin' />
                    ) : (
                      <div className='flex items-end gap-4'>
                        <div>
                          <label className='text-sm font-medium text-neutral-900'>
                            Ændre dit abonnement:
                          </label>
                          <Select
                            value={selectedPlan}
                            onValueChange={handlePlanChange}
                          >
                            <SelectTrigger className='relative min-h-11 w-full truncate rounded-none bg-white [&>svg]:!text-neutral-900 [&>svg]:!opacity-100'>
                              <SelectValue placeholder='Vælg abonnement' />
                            </SelectTrigger>
                            <SelectContent className='rounded-none font-serif'>
                              {tariffPlans.map((o) => (
                                <SelectItem key={o.value} value={o.value}>
                                  {o.label}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                        {subscriptions[0].status !== 'active' && (
                          <Button
                            variant='default'
                            onClick={() =>
                              handlePlanChange(currentPlan?.value || null)
                            }
                          >
                            Betale
                          </Button>
                        )}
                      </div>
                    )}
                  </div>
                </CardContent>
              </Fragment>
            ))}
          </Card>
        </div>
      </div>

      <Separator className='mt-7' />
    </section>
  );
};

export default OrganizationSubscription;
