'use client';

import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { useRouter } from 'next/navigation';
import { format, startOfMonth, endOfMonth, eachDayOfInterval, isSameDay } from 'date-fns';
import { de, enUS } from 'date-fns/locale';
import {
  Calendar,
  Building2,
  ChevronLeft,
  ChevronRight,
  Clock,
  CheckCircle,
  AlertCircle,
  Plus,
  Search,
  Filter,
} 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 { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { cn } from '@/lib/utils';
import { useMeetings, useOpenActions } from '@/hooks/lean/use-meetings';
import type { MorningMeeting, MeetingStatus } from '@/types/lean';

interface MorningMeetingOverviewContentProps {
  locale: string;
}

// Mock departments - replace with actual data fetching
const MOCK_DEPARTMENTS = [
  { id: 'dept-1', name: 'Produktion', code: 'PROD' },
  { id: 'dept-2', name: 'Logistik', code: 'LOG' },
  { id: 'dept-3', name: 'Qualitaet', code: 'QM' },
  { id: 'dept-4', name: 'Instandhaltung', code: 'IH' },
];

/**
 * Meeting status indicator
 */
function StatusIndicator({ status }: { status: MeetingStatus }) {
  switch (status) {
    case 'COMPLETED':
      return <CheckCircle className="h-3 w-3 text-green-600" />;
    case 'IN_PROGRESS':
      return <Clock className="h-3 w-3 text-blue-600 animate-pulse" />;
    case 'CANCELLED':
      return <AlertCircle className="h-3 w-3 text-red-600" />;
    default:
      return <Clock className="h-3 w-3 text-gray-400" />;
  }
}

/**
 * Calendar view component
 */
function MeetingCalendar({
  meetings,
  currentMonth,
  onMonthChange,
  onDateClick,
  locale,
}: {
  meetings: MorningMeeting[];
  currentMonth: Date;
  onMonthChange: (date: Date) => void;
  onDateClick: (date: Date) => void;
  locale: string;
}) {
  const dateLocale = locale === 'de' ? de : enUS;
  const monthStart = startOfMonth(currentMonth);
  const monthEnd = endOfMonth(currentMonth);
  const days = eachDayOfInterval({ start: monthStart, end: monthEnd });

  // Get the day of week for the first day (0 = Sunday, 1 = Monday, etc.)
  // Adjust for Monday start
  const startDayOfWeek = (monthStart.getDay() + 6) % 7;
  const paddingDays = Array(startDayOfWeek).fill(null);

  const getMeetingsForDay = (date: Date) =>
    meetings.filter((m) => isSameDay(new Date(m.date), date));

  const weekDays = locale === 'de'
    ? ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So']
    : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

  return (
    <Card>
      <CardHeader className="pb-2">
        <div className="flex items-center justify-between">
          <CardTitle className="text-lg">
            {format(currentMonth, 'MMMM yyyy', { locale: dateLocale })}
          </CardTitle>
          <div className="flex gap-1">
            <Button
              variant="ghost"
              size="icon"
              onClick={() =>
                onMonthChange(
                  new Date(currentMonth.getFullYear(), currentMonth.getMonth() - 1)
                )
              }
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <Button
              variant="ghost"
              size="icon"
              onClick={() =>
                onMonthChange(
                  new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1)
                )
              }
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      </CardHeader>
      <CardContent>
        {/* Week day headers */}
        <div className="grid grid-cols-7 gap-1 mb-2">
          {weekDays.map((day) => (
            <div
              key={day}
              className="text-center text-xs font-medium text-muted-foreground py-2"
            >
              {day}
            </div>
          ))}
        </div>

        {/* Calendar grid */}
        <div className="grid grid-cols-7 gap-1">
          {/* Padding days */}
          {paddingDays.map((_, i) => (
            <div key={`pad-${i}`} className="aspect-square" />
          ))}

          {/* Actual days */}
          {days.map((day) => {
            const dayMeetings = getMeetingsForDay(day);
            const isToday = isSameDay(day, new Date());
            const hasMeetings = dayMeetings.length > 0;

            return (
              <button
                key={day.toISOString()}
                onClick={() => onDateClick(day)}
                className={cn(
                  'aspect-square p-1 rounded-lg text-sm transition-colors relative',
                  'hover:bg-muted',
                  isToday && 'bg-primary/10 font-bold',
                  hasMeetings && 'bg-blue-50'
                )}
              >
                <span className={cn(isToday && 'text-primary')}>
                  {format(day, 'd')}
                </span>
                {hasMeetings && (
                  <div className="absolute bottom-1 left-1/2 -translate-x-1/2 flex gap-0.5">
                    {dayMeetings.slice(0, 3).map((m) => (
                      <StatusIndicator key={m.id} status={m.status} />
                    ))}
                    {dayMeetings.length > 3 && (
                      <span className="text-[8px] text-muted-foreground">
                        +{dayMeetings.length - 3}
                      </span>
                    )}
                  </div>
                )}
              </button>
            );
          })}
        </div>
      </CardContent>
    </Card>
  );
}

/**
 * Status badge for department card
 */
function DepartmentCardStatusBadge({ status }: { status: MeetingStatus }) {
  const t = useTranslations('lean.morningMeeting.status');
  const statusKeyMap: Record<MeetingStatus, 'scheduled' | 'inProgress' | 'completed' | 'cancelled'> = {
    SCHEDULED: 'scheduled',
    IN_PROGRESS: 'inProgress',
    COMPLETED: 'completed',
    CANCELLED: 'cancelled',
  };
  return (
    <Badge variant="outline" className="text-xs">
      <StatusIndicator status={status} />
      <span className="ml-1">{t(statusKeyMap[status])}</span>
    </Badge>
  );
}

/**
 * Department quick access card
 */
function DepartmentCard({
  department,
  lastMeeting,
  onClick,
}: {
  department: (typeof MOCK_DEPARTMENTS)[0];
  lastMeeting?: MorningMeeting;
  onClick: () => void;
}) {
  return (
    <Card
      className="cursor-pointer transition-shadow hover:shadow-md"
      onClick={onClick}
    >
      <CardContent className="p-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-primary/10 rounded-lg">
              <Building2 className="h-5 w-5 text-primary" />
            </div>
            <div>
              <h3 className="font-medium">{department.name}</h3>
              <p className="text-xs text-muted-foreground">{department.code}</p>
            </div>
          </div>
          {lastMeeting && (
            <DepartmentCardStatusBadge status={lastMeeting.status} />
          )}
        </div>
      </CardContent>
    </Card>
  );
}

/**
 * Recent meetings list
 */
function RecentMeetingsList({
  meetings,
  isLoading,
  onMeetingClick,
  locale,
}: {
  meetings: MorningMeeting[];
  isLoading: boolean;
  onMeetingClick: (meeting: MorningMeeting) => void;
  locale: string;
}) {
  const dateLocale = locale === 'de' ? de : enUS;
  const tMeeting = useTranslations('lean.morningMeeting');

  if (isLoading) {
    return (
      <div className="space-y-3">
        {[1, 2, 3, 4, 5].map((i) => (
          <Skeleton key={i} className="h-16 w-full" />
        ))}
      </div>
    );
  }

  if (meetings.length === 0) {
    return (
      <div className="text-center py-8 text-muted-foreground">
        <Calendar className="h-8 w-8 mx-auto mb-2 opacity-50" />
        <p>{tMeeting('noMeetingsFound')}</p>
      </div>
    );
  }

  return (
    <div className="space-y-2">
      {meetings.map((meeting) => (
        <button
          key={meeting.id}
          onClick={() => onMeetingClick(meeting)}
          className="w-full p-3 rounded-lg border bg-card hover:bg-muted/50 transition-colors text-left"
        >
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <StatusIndicator status={meeting.status} />
              <div>
                <p className="font-medium text-sm">{meeting.department.name}</p>
                <p className="text-xs text-muted-foreground">
                  {format(new Date(meeting.date), 'EEEE, d. MMM', {
                    locale: dateLocale,
                  })}
                </p>
              </div>
            </div>
            {meeting.duration && (
              <span className="text-xs text-muted-foreground">
                {meeting.duration} Min.
              </span>
            )}
          </div>
        </button>
      ))}
    </div>
  );
}

/**
 * Main overview content component
 */
export function MorningMeetingOverviewContent({
  locale,
}: MorningMeetingOverviewContentProps) {
  const router = useRouter();
  const t = useTranslations('lean.morningMeeting');
  const tStatus = useTranslations('lean.morningMeeting.status');
  const tCommon = useTranslations('common');
  const [currentMonth, setCurrentMonth] = useState(new Date());
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<MeetingStatus | 'ALL'>('ALL');

  // Fetch meetings for the current month
  const { data: meetingsData, isLoading: meetingsLoading } = useMeetings({
    dateFrom: format(startOfMonth(currentMonth), 'yyyy-MM-dd'),
    dateTo: format(endOfMonth(currentMonth), 'yyyy-MM-dd'),
    limit: 100,
    sortBy: 'date',
    sortOrder: 'desc',
    status: statusFilter === 'ALL' ? undefined : statusFilter,
  });

  // Fetch open actions
  const { data: openActions, isLoading: actionsLoading } = useOpenActions();

  const meetings = meetingsData?.data || [];

  const handleDepartmentClick = (departmentId: string) => {
    router.push(`/${locale}/lean/morning-meeting/${departmentId}`);
  };

  const handleMeetingClick = (meeting: MorningMeeting) => {
    router.push(`/${locale}/lean/morning-meeting/${meeting.department.id}`);
  };

  const handleDateClick = (date: Date) => {
    // Find meetings for this date
    const dayMeetings = meetings.filter((m) =>
      isSameDay(new Date(m.date), date)
    );
    if (dayMeetings.length === 1) {
      handleMeetingClick(dayMeetings[0]);
    }
    // If multiple meetings, could show a modal or filter the list
  };

  return (
    <div className="container mx-auto py-6 space-y-6">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold">{t('title')}</h1>
          <p className="text-muted-foreground">
            {t('overview')}
          </p>
        </div>

        <div className="flex items-center gap-2">
          <div className="relative">
            <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
            <Input
              placeholder={tCommon('search') + '...'}
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-9 w-[200px]"
            />
          </div>
          <Select
            value={statusFilter}
            onValueChange={(v) => setStatusFilter(v as MeetingStatus | 'ALL')}
          >
            <SelectTrigger className="w-[150px]">
              <Filter className="h-4 w-4 mr-2" />
              <SelectValue placeholder="Status" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="ALL">{t('allStatuses')}</SelectItem>
              <SelectItem value="SCHEDULED">{tStatus('scheduled')}</SelectItem>
              <SelectItem value="IN_PROGRESS">{tStatus('inProgress')}</SelectItem>
              <SelectItem value="COMPLETED">{tStatus('completed')}</SelectItem>
              <SelectItem value="CANCELLED">{tStatus('cancelled')}</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* Quick access - Departments */}
      <div>
        <h2 className="text-lg font-semibold mb-3">{t('departmentsTitle')}</h2>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          {MOCK_DEPARTMENTS.map((dept) => {
            const lastMeeting = meetings.find(
              (m) => m.department.id === dept.id
            );
            return (
              <DepartmentCard
                key={dept.id}
                department={dept}
                lastMeeting={lastMeeting}
                onClick={() => handleDepartmentClick(dept.id)}
              />
            );
          })}
        </div>
      </div>

      {/* Main content grid */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Calendar */}
        <div className="lg:col-span-2">
          <MeetingCalendar
            meetings={meetings}
            currentMonth={currentMonth}
            onMonthChange={setCurrentMonth}
            onDateClick={handleDateClick}
            locale={locale}
          />
        </div>

        {/* Recent meetings */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base">{t('currentMeetingsTitle')}</CardTitle>
          </CardHeader>
          <CardContent>
            <ScrollArea className="h-[350px]">
              <RecentMeetingsList
                meetings={meetings.slice(0, 10)}
                isLoading={meetingsLoading}
                onMeetingClick={handleMeetingClick}
                locale={locale}
              />
            </ScrollArea>
          </CardContent>
        </Card>
      </div>

      {/* Open actions summary */}
      <Card>
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <CardTitle className="text-base">{t('openActionsTitle')}</CardTitle>
            <Badge variant="secondary">
              {actionsLoading ? '...' : t('openCount', { count: openActions?.length || 0 })}
            </Badge>
          </div>
        </CardHeader>
        <CardContent>
          {actionsLoading ? (
            <div className="space-y-2">
              {[1, 2, 3].map((i) => (
                <Skeleton key={i} className="h-12 w-full" />
              ))}
            </div>
          ) : openActions && openActions.length > 0 ? (
            <ScrollArea className="h-[200px]">
              <div className="space-y-2">
                {openActions.slice(0, 10).map((action) => (
                  <div
                    key={action.id}
                    className="flex items-center justify-between p-2 rounded-lg border"
                  >
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium truncate">{action.title}</p>
                      <p className="text-xs text-muted-foreground">
                        {(action as { meeting?: { department?: { name: string } } }).meeting?.department?.name}
                      </p>
                    </div>
                    {action.assignee && (
                      <span className="text-xs text-muted-foreground ml-2">
                        {action.assignee.firstName} {action.assignee.lastName}
                      </span>
                    )}
                  </div>
                ))}
              </div>
            </ScrollArea>
          ) : (
            <div className="text-center py-8 text-muted-foreground">
              <CheckCircle className="h-8 w-8 mx-auto mb-2 opacity-50" />
              <p>{t('noOpenActions')}</p>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
