'use client';
import { updateRole } from './lib/actions';
import { getProfile, updateProfile } from '@/actions/profile';
import { CheckboxWithText } from '@/components/profile/checkbox-with-text';
import { ProfileField } from '@/components/profile/profile-field';
import { Avatar, AvatarFallback, AvatarImage } from '@repo/ui/components/ui/avatar';
import { Button } from '@repo/ui/components/ui/button';
import { Card } from '@repo/ui/components/ui/card';
import { useQuery } from '@tanstack/react-query';
import Link from 'next/link';

type ProfileProps = {
  readonly telegramId?: string;
};

export function ProfileCard(props: ProfileProps) {
  return (
    <div className="space-y-4">
      <Person {...props} />
      <ProfileFields {...props} />
    </div>
  );
}

export function ProfileFields({ telegramId }: ProfileProps) {
  const { data: customer } = useQuery({
    queryFn: () => getProfile({ telegramId }),
    queryKey: telegramId ? ['profile', 'telegramId', telegramId] : ['profile'],
  });

  if (!customer) return null;

  return (
    <Card className="p-4">
      <div className="flex flex-col gap-4">
        {telegramId ? false : <ProfileFieldsHeader />}
        {telegramId ? (
          false
        ) : (
          <ProfileField
            fieldName="name"
            id="name"
            label="Имя"
            onChange={updateProfile}
            value={customer?.name ?? ''}
          />
        )}
        <Link href={telegramId && customer?.phone ? `tel:${customer?.phone}` : ''}>
          <ProfileField
            disabled={!telegramId}
            id="phone"
            label="Телефон"
            readOnly={Boolean(telegramId)}
            value={customer?.phone ?? ''}
          />
        </Link>
        {telegramId ? (
          false
        ) : (
          <CheckboxWithText
            checked={customer.role !== 'client'}
            description="Разрешить другим пользователям записываться к вам"
            onChange={updateRole}
            text="Быть мастером"
          />
        )}
        {telegramId ? (
          <Button asChild className="w-full bg-foreground">
            <Link
              href={`https://t.me/${customer?.phone}`}
              rel="noopener noreferrer"
              target="_blank"
            >
              Написать в Telegram
            </Link>
          </Button>
        ) : (
          false
        )}
      </div>
    </Card>
  );
}

function Person({ telegramId }: ProfileProps) {
  const { data: customer } = useQuery({
    queryFn: () => getProfile({ telegramId }),
    queryKey: telegramId ? ['profile', 'telegramId', telegramId] : ['profile'],
  });

  if (!customer) return null;

  return (
    <Card className="p-4">
      <div className="flex flex-col items-center space-y-2">
        <Avatar className="size-20">
          <AvatarImage alt={customer?.name} src={customer.photoUrl || ''} />
          <AvatarFallback>{customer?.name.charAt(0)}</AvatarFallback>
        </Avatar>
        <h2 className="text-2xl font-bold">{customer?.name}</h2>
      </div>
    </Card>
  );
}

function ProfileFieldsHeader() {
  return (
    <div className="flex flex-row justify-between">
      <h1 className="text-lg font-bold text-muted-foreground">Ваши данные</h1>
      <div />
    </div>
  );
}
