'use client';

import { useRouter } from 'next/navigation';
import { useTranslations } from 'next-intl';
import Link from 'next/link';
import { ArrowLeft, History, Settings, RefreshCw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useToast } from '@/hooks/use-toast';
import { MeetingBoard } from '@/components/lean/morning-meeting';
import {
  useTodaysMeeting,
  useStartMeeting,
  useEndMeeting,
  useUpdateTopic,
  useAddAction,
  useUpdateAction,
  useCompleteAction,
} from '@/hooks/lean/use-meetings';
import type { CreateActionDto, UpdateActionDto, UpdateTopicDto } from '@/types/lean';

interface DepartmentMeetingContentProps {
  locale: string;
  departmentId: string;
}

/**
 * Department meeting content component
 */
export function DepartmentMeetingContent({
  locale,
  departmentId,
}: DepartmentMeetingContentProps) {
  const router = useRouter();
  const { toast } = useToast();
  const t = useTranslations('lean.morningMeeting.toast');
  const tNav = useTranslations('lean.morningMeeting');

  // Fetch today's meeting (create if not exists)
  const {
    data: meeting,
    isLoading,
    error,
    refetch,
  } = useTodaysMeeting(departmentId, true);

  // Mutations
  const startMeeting = useStartMeeting();
  const endMeeting = useEndMeeting();
  const updateTopic = useUpdateTopic();
  const addAction = useAddAction();
  const updateAction = useUpdateAction();
  const completeAction = useCompleteAction();

  const isMutating =
    startMeeting.isPending ||
    endMeeting.isPending ||
    updateTopic.isPending ||
    addAction.isPending ||
    updateAction.isPending ||
    completeAction.isPending;

  const handleStartMeeting = async () => {
    if (!meeting) return;

    try {
      await startMeeting.mutateAsync(meeting.id);
      toast({
        title: t('meetingStarted'),
        description: t('meetingStartedDesc'),
      });
    } catch (err) {
      toast({
        title: t('error'),
        description: t('errorStartMeeting'),
        variant: 'destructive',
      });
    }
  };

  const handleEndMeeting = async () => {
    if (!meeting) return;

    try {
      await endMeeting.mutateAsync(meeting.id);
      toast({
        title: t('meetingEnded'),
        description: t('meetingEndedDesc'),
      });
    } catch (err) {
      toast({
        title: t('error'),
        description: t('errorEndMeeting'),
        variant: 'destructive',
      });
    }
  };

  const handleUpdateTopic = async (id: string, dto: UpdateTopicDto) => {
    try {
      await updateTopic.mutateAsync({ id, dto });
      toast({
        title: t('kpiUpdated'),
        description: t('kpiUpdatedDesc'),
      });
    } catch (err) {
      toast({
        title: t('error'),
        description: t('errorUpdateKpi'),
        variant: 'destructive',
      });
    }
  };

  const handleAddAction = async (dto: CreateActionDto) => {
    if (!meeting) return;

    try {
      await addAction.mutateAsync({ meetingId: meeting.id, dto });
      toast({
        title: t('actionCreated'),
        description: t('actionCreatedDesc'),
      });
    } catch (err) {
      toast({
        title: t('error'),
        description: t('errorCreateAction'),
        variant: 'destructive',
      });
    }
  };

  const handleUpdateAction = async (id: string, dto: UpdateActionDto) => {
    try {
      await updateAction.mutateAsync({ id, dto });
      toast({
        title: t('actionUpdated'),
        description: t('actionUpdatedDesc'),
      });
    } catch (err) {
      toast({
        title: t('error'),
        description: t('errorUpdateAction'),
        variant: 'destructive',
      });
    }
  };

  const handleCompleteAction = async (id: string) => {
    try {
      await completeAction.mutateAsync(id);
      toast({
        title: t('actionCompleted'),
        description: t('actionCompletedDesc'),
      });
    } catch (err) {
      toast({
        title: t('error'),
        description: t('errorCompleteAction'),
        variant: 'destructive',
      });
    }
  };

  const handleRefresh = () => {
    refetch();
  };

  return (
    <div className="container mx-auto py-6 space-y-6">
      {/* Navigation */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Link href={`/${locale}/lean/morning-meeting`}>
            <Button variant="ghost" size="sm">
              <ArrowLeft className="h-4 w-4 mr-2" />
              {tNav('backToOverview')}
            </Button>
          </Link>
        </div>

        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm" onClick={handleRefresh}>
            <RefreshCw className="h-4 w-4 mr-2" />
            {tNav('refresh')}
          </Button>
          <Button variant="outline" size="sm" asChild>
            <Link href={`/${locale}/lean/morning-meeting/${departmentId}/history`}>
              <History className="h-4 w-4 mr-2" />
              {tNav('history')}
            </Link>
          </Button>
          <Button variant="outline" size="sm" asChild>
            <Link href={`/${locale}/lean/morning-meeting/${departmentId}/settings`}>
              <Settings className="h-4 w-4 mr-2" />
              {tNav('settings')}
            </Link>
          </Button>
        </div>
      </div>

      {/* Meeting Board */}
      <MeetingBoard
        meeting={meeting}
        isLoading={isLoading}
        error={error || null}
        editable={true}
        onStartMeeting={handleStartMeeting}
        onEndMeeting={handleEndMeeting}
        onUpdateTopic={handleUpdateTopic}
        onAddAction={handleAddAction}
        onUpdateAction={handleUpdateAction}
        onCompleteAction={handleCompleteAction}
        onRefresh={handleRefresh}
        isMutating={isMutating}
        locale={locale}
        targetDuration={15}
      />
    </div>
  );
}
