import React, { useEffect, useMemo, useState } from 'react';
import styled, { useTheme as useStyledTheme } from 'styled-components';
import { HiClock, HiCollection, HiUser, HiUserGroup, HiUsers } from 'react-icons/hi';
import { useLocale } from '@/app/providers/LocaleProvider';
import { useAuthStore } from '@/features/auth/store/authStore';
import { PERMISSIONS } from '@/features/auth/constants/permissions';
import { Button, Select, StatusBadge, UserAvatar } from '@/shared/components/ui';
import { CollaboratorsSection } from '@/features/tickets/components/CollaboratorsSection';
import { FormActions, FormSection, FormStack } from '@/shared/components/ui/FormStack';
import { AssigneePicker } from '@/features/tickets/components/AssigneePicker';
import { SidebarInfoCard } from '@/features/tickets/components/SidebarInfoCard';
import { SlaSummary } from '@/features/tickets/components/SlaSummary';
import type { TicketSlaTracking } from '@/features/tickets/types/sla.types';
import type { TicketDetail, TicketPriorityRef, TicketStatusRef } from '@/features/tickets/types/ticket.types';
import type {
  AssignableUser,
  TicketFormCategory,
} from '@/features/tickets/types/ticketForm.types';
import {
  formatDateTime,
  localizedName,
  priorityTone,
  statusTone,
} from '@/features/tickets/utils/ticketDisplay';
import {
  buildTicketParticipantContext,
  resolveTicketParticipantColor,
} from '@/features/tickets/utils/ticketParticipantContext';
import type { Theme } from '@/styles/theme';

const Sidebar = styled.aside`
  display: flex;
  flex-direction: column;
  gap: ${({ theme }) => theme.layout.sidebarGap};
  align-self: start;
  min-width: 0;
  height: auto;
  overflow: visible;
`;

const InfoRow = styled.div`
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: flex-start;
  gap: ${({ theme }) => theme.layout.sidebarRowGap};
  padding: ${({ theme }) => `${theme.spacing[2]} 0`};
  min-width: 0;
  text-align: start;

  &:not(:last-child) {
    border-bottom: 1px solid ${({ theme }) => theme.colors.borderSoft};
  }
`;

const InfoLabel = styled.span`
  flex: 1 1 40%;
  min-width: 6.5rem;
  font-size: ${({ theme }) => theme.typography.fontSize.xs};
  font-weight: ${({ theme }) => theme.typography.fontWeight.medium};
  color: ${({ theme }) => theme.colors.text.tertiary};
  letter-spacing: ${({ theme }) => theme.typography.letterSpacing.wide};
  line-height: ${({ theme }) => theme.typography.lineHeight.normal};
`;

const InfoValue = styled.span`
  flex: 1 1 50%;
  min-width: 0;
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  color: ${({ theme }) => theme.colors.text.primary};
  text-align: end;
  word-break: break-word;
  overflow-wrap: anywhere;
  line-height: ${({ theme }) => theme.typography.lineHeight.normal};
`;

const PersonRow = styled.div`
  display: flex;
  align-items: flex-start;
  gap: ${({ theme }) => theme.spacing[3]};
  min-width: 0;
  padding-bottom: ${({ theme }) => theme.spacing[2]};

  > div {
    min-width: 0;
    flex: 1;
  }
`;

const PersonName = styled(InfoValue)<{ $color?: string }>`
  text-align: start;
  display: block;
  margin-bottom: ${({ theme }) => theme.spacing[1]};
  color: ${({ $color, theme }) => $color ?? theme.colors.text.primary};
`;

const PersonMeta = styled(InfoLabel)`
  flex: none;
  min-width: 0;
`;

interface TicketDetailSidebarProps {
  ticket: TicketDetail;
  statuses: TicketStatusRef[];
  priorities: TicketPriorityRef[];
  categories: TicketFormCategory[];
  sla?: TicketSlaTracking | null;
  slaLoading?: boolean;
  slaError?: boolean;
  onStatusChange: (statusId: string) => void;
  onPriorityChange: (priorityId: string) => void;
  onCategoryChange: (categoryId: string | null, subcategoryId: string | null) => void;
  onAssign: (assigneeId: string) => void;
  onUnassign: () => void;
  onAddCollaborator?: (userId: string) => Promise<void>;
  onRemoveCollaborator?: (userId: string) => Promise<void>;
  isAddingCollaborator?: boolean;
  removingCollaboratorId?: string | null;
  isUpdating: boolean;
}

export const TicketDetailSidebar: React.FC<TicketDetailSidebarProps> = ({
  ticket,
  statuses,
  priorities,
  categories,
  sla,
  slaLoading = false,
  slaError = false,
  onStatusChange,
  onPriorityChange,
  onCategoryChange,
  onAssign,
  onUnassign,
  onAddCollaborator,
  onRemoveCollaborator,
  isAddingCollaborator = false,
  removingCollaboratorId = null,
  isUpdating,
}) => {
  const { t, locale } = useLocale();
  const { mode } = useStyledTheme() as Theme;
  const user = useAuthStore((state) => state.user);
  const canManageCollaborators = Boolean(
    user?.is_super_admin ||
    user?.permissions.includes(PERMISSIONS.DEPARTMENT_TICKETS_COLLABORATORS_MANAGE) ||
    user?.permissions.includes(PERMISSIONS.COMPANY_USERS_MANAGE) ||
    user?.permissions.includes(PERMISSIONS.DEPARTMENT_TICKETS_ASSIGN),
  );
  const [statusId, setStatusId] = useState(ticket.status.id);
  const [priorityId, setPriorityId] = useState(ticket.priority.id);
  const [categoryId, setCategoryId] = useState(ticket.category?.id ?? '');
  const [subcategoryId, setSubcategoryId] = useState(ticket.subcategory?.id ?? '');
  const [selectedAssignee, setSelectedAssignee] = useState<AssignableUser | null>(
    ticket.assignee
      ? { id: ticket.assignee.id, name: ticket.assignee.name, email: ticket.assignee.email }
      : null,
  );

  useEffect(() => {
    setStatusId(ticket.status.id);
    setPriorityId(ticket.priority.id);
    setCategoryId(ticket.category?.id ?? '');
    setSubcategoryId(ticket.subcategory?.id ?? '');
    setSelectedAssignee(
      ticket.assignee
        ? { id: ticket.assignee.id, name: ticket.assignee.name, email: ticket.assignee.email }
        : null,
    );
  }, [ticket]);

  const subcategories = useMemo(() => {
    const category = categories.find((item) => item.id === categoryId);
    return category?.subcategories ?? [];
  }, [categories, categoryId]);

  const handleAssign = () => {
    if (selectedAssignee) {
      onAssign(selectedAssignee.id);
    }
  };

  const participantContext = buildTicketParticipantContext({
    requester: ticket.requester,
    assignee: ticket.assignee,
    collaborators: ticket.collaborators,
  });
  const assigneeColor = ticket.assignee
    ? resolveTicketParticipantColor(ticket.assignee.id, participantContext, mode)
    : null;
  const requesterColor = resolveTicketParticipantColor(
    ticket.requester.id,
    participantContext,
    mode,
  );

  return (
    <Sidebar data-tour="ticket-sidebar">
      <SidebarInfoCard surface="elevated" title={t('tickets:sections.assignment')} icon={<HiUserGroup />}>
        <PersonRow>
          <UserAvatar
            name={ticket.assignee?.name ?? t('tickets:unassigned')}
            size="md"
            ringColor={assigneeColor?.avatarBackground}
            avatarBackground={assigneeColor?.avatarBackground}
            avatarText={assigneeColor?.avatarText}
          />
          <div>
            <PersonName $color={assigneeColor?.text}>
              {ticket.assignee?.name ?? t('tickets:unassigned')}
            </PersonName>
            <PersonMeta>{t('tickets:fields.assignee')}</PersonMeta>
          </div>
        </PersonRow>
        <FormStack>
          <AssigneePicker
            departmentId={ticket.department.id}
            value={selectedAssignee}
            onChange={setSelectedAssignee}
          />
          <FormActions $compact>
            <Button
              data-testid="ticket-assign-button"
              variant="primary"
              fullWidth
              loading={isUpdating}
              disabled={!selectedAssignee}
              onClick={handleAssign}
            >
              {t('tickets:actions.assign')}
            </Button>
            {ticket.is_assigned && (
              <Button variant="ghost" fullWidth loading={isUpdating} onClick={onUnassign}>
                {t('tickets:actions.unassign')}
              </Button>
            )}
          </FormActions>
        </FormStack>
      </SidebarInfoCard>

      <SidebarInfoCard
        surface="elevated"
        title={t('tickets:sections.collaborators')}
        icon={<HiUsers />}
      >
        <CollaboratorsSection
          collaborators={ticket.collaborators ?? []}
          assignee={ticket.assignee}
          requester={ticket.requester}
          departmentId={ticket.department.id}
          ticketId={ticket.id}
          canManage={canManageCollaborators && Boolean(onAddCollaborator && onRemoveCollaborator)}
          onAdd={onAddCollaborator ?? (async () => undefined)}
          onRemove={onRemoveCollaborator ?? (async () => undefined)}
          isAdding={isAddingCollaborator}
          removingUserId={removingCollaboratorId}
        />
      </SidebarInfoCard>

      <SidebarInfoCard surface="elevated" title={t('tickets:sla.label')} icon={<HiClock />}>
        <SlaSummary sla={sla} isLoading={slaLoading} isError={slaError} />
      </SidebarInfoCard>

      <SidebarInfoCard
        surface="muted"
        compact
        title={t('tickets:sections.properties')}
        icon={<HiCollection />}
      >
        <InfoRow>
          <InfoLabel>{t('tickets:fields.status')}</InfoLabel>
          <StatusBadge tone={statusTone(ticket.status)} size="sm">
            {localizedName(ticket.status, locale)}
          </StatusBadge>
        </InfoRow>
        <InfoRow>
          <InfoLabel>{t('tickets:fields.priority')}</InfoLabel>
          <StatusBadge tone={priorityTone(ticket.priority)} size="sm">
            {localizedName(ticket.priority, locale)}
          </StatusBadge>
        </InfoRow>
        <FormSection>
          <Select
            data-testid="ticket-status-select"
            label={t('tickets:actions.changeStatus')}
            value={statusId}
            onChange={(event) => setStatusId(event.target.value)}
            options={statuses.map((status) => ({
              value: status.id,
              label: localizedName(status, locale),
            }))}
            fullWidth
          />
          <Button
            data-testid="ticket-status-update"
            variant="outline"
            fullWidth
            size="sm"
            loading={isUpdating}
            disabled={statusId === ticket.status.id}
            onClick={() => onStatusChange(statusId)}
          >
            {t('tickets:actions.updateStatus')}
          </Button>
          <Select
            label={t('tickets:actions.changePriority')}
            value={priorityId}
            onChange={(event) => setPriorityId(event.target.value)}
            options={priorities.map((priority) => ({
              value: priority.id,
              label: localizedName(priority, locale),
            }))}
            fullWidth
          />
          <Button
            variant="outline"
            fullWidth
            size="sm"
            loading={isUpdating}
            disabled={priorityId === ticket.priority.id}
            onClick={() => onPriorityChange(priorityId)}
          >
            {t('tickets:actions.updatePriority')}
          </Button>
          <Select
            label={t('tickets:fields.category')}
            value={categoryId}
            onChange={(event) => {
              setCategoryId(event.target.value);
              setSubcategoryId('');
            }}
            options={[
              { value: '', label: t('tickets:createForm.optional') },
              ...categories.map((category) => ({
                value: category.id,
                label: localizedName(category, locale),
              })),
            ]}
            fullWidth
          />
          <Select
            label={t('tickets:fields.subcategory')}
            value={subcategoryId}
            onChange={(event) => setSubcategoryId(event.target.value)}
            options={[
              { value: '', label: t('tickets:createForm.optional') },
              ...subcategories.map((subcategory) => ({
                value: subcategory.id,
                label: localizedName(subcategory, locale),
              })),
            ]}
            fullWidth
            disabled={!categoryId}
          />
          <Button
            variant="outline"
            fullWidth
            size="sm"
            loading={isUpdating}
            disabled={
              categoryId === (ticket.category?.id ?? '') &&
              subcategoryId === (ticket.subcategory?.id ?? '')
            }
            onClick={() => onCategoryChange(categoryId || null, subcategoryId || null)}
          >
            {t('tickets:actions.updateCategory')}
          </Button>
        </FormSection>
      </SidebarInfoCard>

      <SidebarInfoCard surface="elevated" title={t('tickets:sections.people')} icon={<HiUser />}>
        <PersonRow>
          <UserAvatar
            name={ticket.requester.name}
            size="sm"
            ringColor={requesterColor.avatarBackground}
            avatarBackground={requesterColor.avatarBackground}
            avatarText={requesterColor.avatarText}
          />
          <div>
            <PersonName $color={requesterColor.text}>{ticket.requester.name}</PersonName>
            <PersonMeta>{t('tickets:fields.requester')}</PersonMeta>
          </div>
        </PersonRow>
        <InfoRow>
          <InfoLabel>{t('tickets:fields.department')}</InfoLabel>
          <InfoValue>
            {ticket.department.name} ({ticket.department.code})
          </InfoValue>
        </InfoRow>
        <InfoRow>
          <InfoLabel>{t('tickets:fields.createdAt')}</InfoLabel>
          <InfoValue>{formatDateTime(ticket.created_at, locale)}</InfoValue>
        </InfoRow>
        <InfoRow>
          <InfoLabel>{t('tickets:fields.updatedAt')}</InfoLabel>
          <InfoValue>{formatDateTime(ticket.updated_at, locale)}</InfoValue>
        </InfoRow>
      </SidebarInfoCard>
    </Sidebar>
  );
};
