'use client';

import { ReactElement, useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { apiClient } from '@/lib/api';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableRow } from '@/components/ui/table';

interface IAboutTable {
  status: string;
  info: ReactElement | string;
}
type IAboutTables = Array<IAboutTable>;

interface ProfileData {
  id: number;
  name: string;
  email: string;
  phone: string;
  contractor_company: string;
}

interface BackendResponse<T> {
  success: boolean;
  data: T;
  message: string;
}

const About = () => {
  const { t } = useTranslation();

  const { data: profileResponse, isLoading } = useQuery({
    queryKey: ['contractor-profile'],
    queryFn: async () => {
      const response = await apiClient.get<BackendResponse<ProfileData>>(
        '/contractor/profile',
        { requireAuth: true },
      );
      return response.data;
    },
  });

  const profile = profileResponse?.data;

  const tables: IAboutTables = useMemo(() => {
    if (!profile) return [];
    return [
      { status: `${t('profile.name')}:`, info: profile.name },
      { status: `${t('profile.company')}:`, info: profile.contractor_company },
      { status: `${t('profile.email')}:`, info: profile.email },
      { status: `${t('profile.phone')}:`, info: profile.phone },
    ];
  }, [profile, t]);

  const renderTable = (table: IAboutTable, index: number) => {
    return (
      <TableRow key={index} className="border-0">
        <TableCell className="text-sm text-secondary-foreground py-2">
          {table.status}
        </TableCell>
        <TableCell className="text-sm text-mono py-2">{table.info}</TableCell>
      </TableRow>
    );
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t('profile.about')}</CardTitle>
      </CardHeader>
      <CardContent>
        {isLoading ? (
          <div className="p-4 text-center text-sm text-muted-foreground">
            {t('common.messages.loading')}
          </div>
        ) : (
          <Table>
            <TableBody>
              {tables.map((table, index) => {
                return renderTable(table, index);
              })}
            </TableBody>
          </Table>
        )}
      </CardContent>
    </Card>
  );
};

export { About, type IAboutTable, type IAboutTables };
