'use client';

import { useState } from 'react';

import { redirect } from 'next/navigation';

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 { Card } from '@kit/ui/card';
import { Trans } from '@kit/ui/makerkit/trans';
import { Button } from '@kit/ui/shadcn/button';
import { Calendar, DateRange } from '@kit/ui/shadcn/calendar';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@kit/ui/shadcn/popover';

import pathsConfig from '~/config/paths.config';
import { createPath } from '~/config/team-account-navigation.config';

import TeamAccountBenefitStatistics from './team-account-benefit-statistics';
import TeamAccountHealthDetails from './team-account-health-details';

export interface TeamAccountStatisticsProps {
  teamAccount: Database['medreport']['Tables']['accounts']['Row'];
  memberParams: Pick<
    Database['medreport']['Tables']['account_params']['Row'],
    'weight' | 'height'
  >[];
  bmiThresholds: Omit<
    Database['medreport']['Tables']['bmi_thresholds']['Row'],
    'id'
  >[];
  members: Database['medreport']['Functions']['get_account_members']['Returns'];
  companyParams: Database['medreport']['Tables']['company_params']['Row'];
}

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

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

        <Popover>
          <PopoverTrigger asChild>
            <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.date" />
                </span>
              )}
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-auto p-0">
            <Calendar
              mode="range"
              selected={date}
              onSelect={setDate}
              locale={language === 'et' ? et : enGB}
            />
          </PopoverContent>
        </Popover>
      </div>

      <div
        className={
          'animate-in fade-in flex flex-col space-y-4 pb-36 duration-500'
        }
      >
        <TeamAccountBenefitStatistics
          employeeCount={members.length}
          accountSlug={teamAccount.slug || ''}
          companyParams={companyParams}
        />

        <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>
    </>
  );
}
