'use client';

import { useTranslations } from 'next-intl';
import { format } from 'date-fns';
import { de, enUS } from 'date-fns/locale';
import {
  Building2,
  Calendar,
  Users,
  User,
  AlertCircle,
  RefreshCw,
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { SqcdmColumn } from './sqcdm-column';
import { ActionList } from './action-list';
import { MeetingTimer } from './meeting-timer';
import { getInitials } from '@tos/shared';
import { cn } from '@/lib/utils';
import type {
  MorningMeeting,
  SQCDMCategory,
  UpdateTopicDto,
  CreateActionDto,
  UpdateActionDto,
} from '@/types/lean';

interface MeetingBoardProps {
  /** The meeting data */
  meeting: MorningMeeting | null | undefined;
  /** Whether the meeting is loading */
  isLoading?: boolean;
  /** Error loading the meeting */
  error?: Error | null;
  /** Whether editing is allowed */
  editable?: boolean;
  /** Callback to start the meeting */
  onStartMeeting?: () => void;
  /** Callback to end the meeting */
  onEndMeeting?: () => void;
  /** Callback when a topic is updated */
  onUpdateTopic?: (id: string, dto: UpdateTopicDto) => void;
  /** Callback when an action is added */
  onAddAction?: (dto: CreateActionDto) => void;
  /** Callback when an action is updated */
  onUpdateAction?: (id: string, dto: UpdateActionDto) => void;
  /** Callback when an action is completed */
  onCompleteAction?: (id: string) => void;
  /** Callback to refresh the meeting */
  onRefresh?: () => void;
  /** Loading state for mutations */
  isMutating?: boolean;
  /** Locale for translations */
  locale?: string;
  /** Target meeting duration in minutes */
  targetDuration?: number;
}

/** Order of SQCDM categories for display */
const SQCDM_ORDER: SQCDMCategory[] = [
  'SAFETY',
  'QUALITY',
  'COST',
  'DELIVERY',
  'MORALE',
];

/**
 * Meeting status badge
 */
function MeetingStatusBadge({ status }: { status: MorningMeeting['status'] }) {
  const t = useTranslations('lean.morningMeeting.status');
  const variants: Record<
    MorningMeeting['status'],
    { labelKey: 'scheduled' | 'inProgress' | 'completed' | 'cancelled'; className: string }
  > = {
    SCHEDULED: { labelKey: 'scheduled', className: 'bg-gray-100 text-gray-700' },
    IN_PROGRESS: {
      labelKey: 'inProgress',
      className: 'bg-blue-100 text-blue-700 animate-pulse',
    },
    COMPLETED: { labelKey: 'completed', className: 'bg-green-100 text-green-700' },
    CANCELLED: { labelKey: 'cancelled', className: 'bg-red-100 text-red-700' },
  };

  const variant = variants[status];
  return (
    <Badge variant="outline" className={cn('font-medium', variant.className)}>
      {t(variant.labelKey)}
    </Badge>
  );
}

/**
 * Loading skeleton for the meeting board
 */
function MeetingBoardSkeleton() {
  return (
    <div className="space-y-6">
      {/* Header skeleton */}
      <div className="flex items-start justify-between">
        <div className="space-y-2">
          <Skeleton className="h-8 w-64" />
          <Skeleton className="h-4 w-48" />
        </div>
        <Skeleton className="h-10 w-32" />
      </div>

      {/* Timer skeleton */}
      <Skeleton className="h-24 w-full" />

      {/* SQCDM columns skeleton */}
      <div className="grid grid-cols-5 gap-4">
        {[1, 2, 3, 4, 5].map((i) => (
          <div key={i} className="space-y-3">
            <Skeleton className="h-12 w-full" />
            <Skeleton className="h-24 w-full" />
            <Skeleton className="h-24 w-full" />
          </div>
        ))}
      </div>

      {/* Actions skeleton */}
      <Skeleton className="h-64 w-full" />
    </div>
  );
}

/**
 * Error state for the meeting board
 */
function MeetingBoardError({
  error,
  onRefresh,
}: {
  error: Error;
  onRefresh?: () => void;
}) {
  const t = useTranslations('lean.morningMeeting');
  const tCommon = useTranslations('common');
  return (
    <Card className="border-destructive">
      <CardContent className="flex flex-col items-center justify-center py-12">
        <AlertCircle className="h-12 w-12 text-destructive mb-4" />
        <h3 className="text-lg font-semibold mb-2">{t('loadingError')}</h3>
        <p className="text-muted-foreground text-center mb-4 max-w-md">
          {error.message || t('loadingErrorDesc')}
        </p>
        {onRefresh && (
          <Button onClick={onRefresh} variant="outline">
            <RefreshCw className="h-4 w-4 mr-2" />
            {tCommon('retry')}
          </Button>
        )}
      </CardContent>
    </Card>
  );
}

/**
 * Empty state when no meeting exists
 */
function MeetingBoardEmpty({ departmentName }: { departmentName?: string }) {
  const t = useTranslations('lean.morningMeeting');
  return (
    <Card>
      <CardContent className="flex flex-col items-center justify-center py-12">
        <Calendar className="h-12 w-12 text-muted-foreground mb-4" />
        <h3 className="text-lg font-semibold mb-2">{t('noMeetingToday')}</h3>
        <p className="text-muted-foreground text-center max-w-md">
          {t('noMeetingForDepartment', { department: departmentName || '' })}
        </p>
      </CardContent>
    </Card>
  );
}

/**
 * Main Meeting Board component displaying the SQCDM board
 */
export function MeetingBoard({
  meeting,
  isLoading = false,
  error = null,
  editable = false,
  onStartMeeting,
  onEndMeeting,
  onUpdateTopic,
  onAddAction,
  onUpdateAction,
  onCompleteAction,
  onRefresh,
  isMutating = false,
  locale = 'de',
  targetDuration = 15,
}: MeetingBoardProps) {
  const t = useTranslations('lean.morningMeeting');
  const dateLocale = locale === 'de' ? de : enUS;

  if (isLoading) {
    return <MeetingBoardSkeleton />;
  }

  if (error) {
    return <MeetingBoardError error={error} onRefresh={onRefresh} />;
  }

  if (!meeting) {
    return <MeetingBoardEmpty />;
  }

  // Group topics by category
  const topicsByCategory = SQCDM_ORDER.reduce(
    (acc, category) => {
      acc[category] = meeting.topics.filter((t) => t.category === category);
      return acc;
    },
    {} as Record<SQCDMCategory, typeof meeting.topics>
  );

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-4">
        <div>
          <div className="flex items-center gap-3 mb-2">
            <Building2 className="h-5 w-5 text-muted-foreground" />
            <h1 className="text-2xl font-bold">{meeting.department.name}</h1>
            <MeetingStatusBadge status={meeting.status} />
          </div>

          <div className="flex items-center gap-4 text-sm text-muted-foreground">
            <div className="flex items-center gap-1">
              <Calendar className="h-4 w-4" />
              <span>
                {format(new Date(meeting.date), 'EEEE, d. MMMM yyyy', {
                  locale: dateLocale,
                })}
              </span>
            </div>

            {meeting.conductor && (
              <div className="flex items-center gap-1">
                <Avatar className="h-5 w-5">
                  <AvatarImage src={meeting.conductor.avatar || undefined} />
                  <AvatarFallback className="text-[10px]">
                    {getInitials(
                      meeting.conductor.firstName,
                      meeting.conductor.lastName
                    )}
                  </AvatarFallback>
                </Avatar>
                <span>
                  {meeting.conductor.firstName} {meeting.conductor.lastName}
                </span>
              </div>
            )}

            {meeting.participants && meeting.participants.length > 0 && (
              <div className="flex items-center gap-1">
                <Users className="h-4 w-4" />
                <span>{t('participantCount', { count: meeting.participants.length })}</span>
              </div>
            )}
          </div>
        </div>

        {/* Timer */}
        <div className="flex-shrink-0">
          <MeetingTimer
            status={meeting.status}
            startTime={meeting.startTime}
            endTime={meeting.endTime}
            duration={meeting.duration}
            targetMinutes={targetDuration}
            onStart={onStartMeeting}
            onStop={onEndMeeting}
            isLoading={isMutating}
            compact={false}
          />
        </div>
      </div>

      {/* SQCDM Columns */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
        {SQCDM_ORDER.map((category) => (
          <SqcdmColumn
            key={category}
            category={category}
            topics={topicsByCategory[category]}
            editable={editable && meeting.status !== 'COMPLETED'}
            onUpdateTopic={onUpdateTopic}
            isUpdating={isMutating}
          />
        ))}
      </div>

      {/* Action Items */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        <div className="lg:col-span-2">
          <ActionList
            actions={meeting.actions}
            editable={editable && meeting.status !== 'COMPLETED'}
            onAddAction={onAddAction}
            onUpdateAction={onUpdateAction}
            onCompleteAction={onCompleteAction}
            isLoading={isMutating}
            locale={locale}
            maxHeight="350px"
          />
        </div>

        {/* Meeting Notes */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base">{t('notes')}</CardTitle>
          </CardHeader>
          <CardContent>
            {meeting.notes ? (
              <p className="text-sm text-muted-foreground whitespace-pre-wrap">
                {meeting.notes}
              </p>
            ) : (
              <p className="text-sm text-muted-foreground italic">
                {t('noNotes')}
              </p>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
