'use client';

import { useState } from 'react';

import { redirect } from 'next/navigation';

import type {
  Account,
  AccountParams,
  BmiThresholds,
} from '@/packages/features/accounts/src/types/accounts';
import { Database } from '@/packages/supabase/src/database.types';
import { format } from 'date-fns';
import { enGB, et } from 'date-fns/locale';
import { CalendarIcon, ChevronRight, Euro, User } from 'lucide-react';
import { useTranslation } from 'react-i18next';

import { createPath, pathsConfig } from '@kit/shared/config';
import { Card } from '@kit/ui/card';
import { Trans } from '@kit/ui/makerkit/trans';
import { Button } from '@kit/ui/shadcn/button';
import { DateRange } from '@kit/ui/shadcn/calendar';

import { TeamAccountBenefitExpensesOverview } from '../_lib/server/load-team-account-benefit-expenses-overview';
import { AccountBenefitStatistics } from '../_lib/server/load-team-account-benefit-statistics';
import TeamAccountBenefitStatistics from './team-account-benefit-statistics';
import TeamAccountHealthDetails from './team-account-health-details';

export interface TeamAccountStatisticsProps {
  teamAccount: Account;
  memberParams: Pick<AccountParams, 'weight' | 'height'>[];
  bmiThresholds: Omit<BmiThresholds, 'id'>[];
  members: Database['medreport']['Functions']['get_account_members']['Returns'];
  accountBenefitStatistics: AccountBenefitStatistics;
  expensesOverview: TeamAccountBenefitExpensesOverview;
}

export default function TeamAccountStatistics({
  teamAccount,
  memberParams,
  bmiThresholds,
  members,
  accountBenefitStatistics,
  expensesOverview,
}: TeamAccountStatisticsProps) {
  const currentDate = new Date();
  const [date, setDate] = useState<DateRange | undefined>({
    from: new Date(currentDate.getFullYear(), currentDate.getMonth(), 1),
    to: new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0),
  });
  const {
    i18n: { language },
  } = useTranslation();
  const dateFormatOptions = {
    locale: language === 'et' ? et : enGB,
  };

  return (
    <>
      <div className="mt-4 flex flex-col items-center justify-between gap-4 sm:flex-row sm:gap-0">
        <h4 className="font-bold">
          <Trans
            i18nKey={'teams:home.headerTitle'}
            values={{ companyName: teamAccount.name }}
          />
        </h4>

        <Button variant="outline" data-empty={!date}>
          <CalendarIcon />
          {date?.from && date?.to ? (
            `${format(date.from, 'd MMMM yyyy', dateFormatOptions)} - ${format(date.to, 'd MMMM yyyy', dateFormatOptions)}`
          ) : (
            <span>
              <Trans i18nKey="common:formField.selectDate" />
            </span>
          )}
        </Button>
      </div>

      <div
        className={
          'animate-in fade-in flex flex-col space-y-4 pb-36 duration-500'
        }
      >
        <TeamAccountBenefitStatistics
          accountBenefitStatistics={accountBenefitStatistics}
          expensesOverview={expensesOverview}
        />

        <h5 className="mt-4 mb-2">
          <Trans i18nKey="teams:home.healthDetails" />
        </h5>

        <div className="flex flex-col gap-2 sm:flex-row">
          <TeamAccountHealthDetails
            memberParams={memberParams}
            bmiThresholds={bmiThresholds}
            members={members}
          />

          <div className="flex flex-col gap-2">
            <Card
              variant="gradient-success"
              className="border-success/50 hover:bg-success/20 relative flex h-full cursor-pointer flex-col justify-center px-6 py-4 transition-colors"
              onClick={() =>
                redirect(
                  createPath(
                    pathsConfig.app.accountMembers,
                    teamAccount.slug || '',
                  ),
                )
              }
            >
              <div className="flex flex-col">
                <div className="border-input absolute top-2 right-2 rounded-md border bg-white p-3">
                  <ChevronRight className="stroke-2" />
                </div>
                <div className="bg-primary/10 w-fit rounded-2xl p-2">
                  <User color="green" className="stroke-2" />
                </div>
                <span className="mt-4 mb-2 text-lg font-semibold">
                  <Trans i18nKey="teams:home.membersSettingsButtonTitle" />
                </span>
                <p className="text-muted-foreground text-sm">
                  <Trans i18nKey="teams:home.membersSettingsButtonDescription" />
                </p>
              </div>
            </Card>

            <Card
              variant="gradient-warning"
              className="border-warning/40 hover:bg-warning/20 relative flex h-full cursor-pointer flex-col justify-center px-6 py-4 transition-colors"
              onClick={() =>
                redirect(
                  createPath(pathsConfig.app.accountBilling, teamAccount.slug!),
                )
              }
            >
              <div className="border-input absolute top-2 right-2 rounded-md border bg-white p-3">
                <ChevronRight className="stroke-2" />
              </div>
              <div className="bg-warning/10 w-fit rounded-2xl p-2">
                <Euro color="orange" className="stroke-2" />
              </div>
              <span className="mt-4 mb-2 text-lg font-semibold">
                <Trans i18nKey="teams:home.membersBillingButtonTitle" />
              </span>
              <p className="text-muted-foreground text-sm">
                <Trans i18nKey="teams:home.membersBillingButtonDescription" />
              </p>
            </Card>
          </div>
        </div>
      </div>
    </>
  );
}
