'use client';

import { useState, useMemo } from 'react';
import { useTranslations } from 'next-intl';
import { useSearchParams, useRouter } from 'next/navigation';
import {
  ArrowLeft,
  Calendar,
  ChevronLeft,
  ChevronRight,
  Loader2,
  Plus,
} from 'lucide-react';

import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { PageTransition } from '@/components/layout/page-transition';
import { useToast } from '@/hooks/use-toast';
import { useS3Plans, type S3StatusType } from '@/hooks/lean/use-s3-plans';
import { useUpdateStatus } from '@/hooks/lean/use-s3-status';
import { S3CategoryCard } from './s3-category-card';
import { S3ProgressChart } from './s3-progress-chart';

interface S3DepartmentViewProps {
  /** Department ID */
  departmentId: string;
  /** Current locale */
  locale: string;
}

/**
 * Get month name in German
 */
function getMonthName(month: number): string {
  const months = [
    'Januar', 'Februar', 'Maerz', 'April', 'Mai', 'Juni',
    'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember',
  ];
  return months[month - 1] || '';
}

/**
 * Get all weeks for a given year
 */
function getWeeksForYear(): number[] {
  return Array.from({ length: 52 }, (_, i) => i + 1);
}

/**
 * Get weeks for a specific month
 */
function getWeeksForMonth(year: number, month: number): number[] {
  const weeks: Set<number> = new Set();
  const firstDay = new Date(year, month - 1, 1);
  const lastDay = new Date(year, month, 0);

  for (let day = new Date(firstDay); day <= lastDay; day.setDate(day.getDate() + 1)) {
    weeks.add(getISOWeek(day));
  }

  return Array.from(weeks).sort((a, b) => a - b);
}

/**
 * Get ISO week number for a date
 */
function getISOWeek(date: Date): number {
  const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
  const dayNum = d.getUTCDay() || 7;
  d.setUTCDate(d.getUTCDate() + 4 - dayNum);
  const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
  return Math.ceil(((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);
}

/**
 * Calculate status counts from plan
 */
function calculateStatusCounts(plan: { categories: Array<{ statuses: Array<{ status: S3StatusType }> }> } | null) {
  const counts = { green: 0, yellow: 0, red: 0, notApplicable: 0 };

  if (!plan) return counts;

  plan.categories.forEach((category) => {
    category.statuses.forEach((status) => {
      switch (status.status) {
        case 'GREEN':
          counts.green++;
          break;
        case 'YELLOW':
          counts.yellow++;
          break;
        case 'RED':
          counts.red++;
          break;
        case 'NOT_APPLICABLE':
          counts.notApplicable++;
          break;
      }
    });
  });

  return counts;
}

/**
 * S3 Department View Component
 * Detailed view of a department's 3S plan with week grid
 */
export function S3DepartmentView({ departmentId, locale }: S3DepartmentViewProps) {
  const t = useTranslations('lean');
  const tS3 = useTranslations('lean.s3');
  const tCommon = useTranslations('common');
  const router = useRouter();
  const searchParams = useSearchParams();
  const { toast } = useToast();

  const currentYear = new Date().getFullYear();
  const currentMonth = new Date().getMonth() + 1;

  // Get initial values from URL params
  const initialYear = searchParams.get('year')
    ? parseInt(searchParams.get('year')!)
    : currentYear;
  const initialMonth = searchParams.get('month')
    ? parseInt(searchParams.get('month')!)
    : currentMonth;

  const [selectedYear, setSelectedYear] = useState<number>(initialYear);
  const [selectedMonth, setSelectedMonth] = useState<number>(initialMonth);
  const [viewMode, setViewMode] = useState<'month' | 'year'>('month');
  const [updatingStatusId, setUpdatingStatusId] = useState<string | null>(null);

  // Fetch plan for selected month
  const { data: plansData, isLoading, error } = useS3Plans({
    departmentId,
    year: selectedYear,
    month: selectedMonth,
    limit: 1,
  });

  const plan = plansData?.data?.[0] ?? null;
  const updateStatusMutation = useUpdateStatus();

  // Calculate weeks to display based on view mode
  const weeksToDisplay = useMemo(() => {
    if (viewMode === 'year') {
      return getWeeksForYear();
    }
    return getWeeksForMonth(selectedYear, selectedMonth);
  }, [viewMode, selectedYear, selectedMonth]);

  // Calculate stats
  const statusCounts = useMemo(() => calculateStatusCounts(plan), [plan]);

  // Year and month options
  const yearOptions = Array.from({ length: 5 }, (_, i) => currentYear - 2 + i);
  const monthOptions = Array.from({ length: 12 }, (_, i) => i + 1);

  // Navigation handlers
  const handlePreviousMonth = () => {
    if (selectedMonth === 1) {
      setSelectedMonth(12);
      setSelectedYear(selectedYear - 1);
    } else {
      setSelectedMonth(selectedMonth - 1);
    }
  };

  const handleNextMonth = () => {
    if (selectedMonth === 12) {
      setSelectedMonth(1);
      setSelectedYear(selectedYear + 1);
    } else {
      setSelectedMonth(selectedMonth + 1);
    }
  };

  const handleBack = () => {
    router.push(`/${locale}/lean/s3-planning`);
  };

  // Status update handler
  const handleStatusUpdate = async (
    statusId: string,
    data: { status: S3StatusType; note?: string }
  ) => {
    setUpdatingStatusId(statusId);
    try {
      await updateStatusMutation.mutateAsync({ id: statusId, dto: data });
      toast({
        title: tS3('statusUpdated'),
        description: tS3('statusUpdatedDesc'),
      });
    } catch (err) {
      toast({
        title: tCommon('loadingError'),
        description: tS3('statusUpdateError'),
        variant: 'destructive',
      });
    } finally {
      setUpdatingStatusId(null);
    }
  };

  return (
    <PageTransition>
      <div className="space-y-6">
        {/* Header */}
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div className="flex items-center gap-4">
            <Button variant="ghost" size="icon" onClick={handleBack}>
              <ArrowLeft className="h-5 w-5" />
            </Button>
            <div>
              <h1 className="text-2xl font-bold tracking-tight">
                {plan?.department?.name ?? (
                  <Skeleton className="h-7 w-48 inline-block" />
                )}
              </h1>
              <p className="text-muted-foreground">
                3S-Plan {getMonthName(selectedMonth)} {selectedYear}
              </p>
            </div>
          </div>
          <Button disabled>
            <Plus className="h-4 w-4 mr-2" />
            {tS3('addCategory')}
          </Button>
        </div>

        {/* Controls */}
        <div className="flex flex-wrap items-center gap-4">
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="icon"
              onClick={handlePreviousMonth}
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>

            <Select
              value={selectedMonth.toString()}
              onValueChange={(value) => setSelectedMonth(parseInt(value))}
            >
              <SelectTrigger className="w-36">
                <Calendar className="h-4 w-4 mr-2 text-muted-foreground" />
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {monthOptions.map((month) => (
                  <SelectItem key={month} value={month.toString()}>
                    {getMonthName(month)}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            <Select
              value={selectedYear.toString()}
              onValueChange={(value) => setSelectedYear(parseInt(value))}
            >
              <SelectTrigger className="w-24">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {yearOptions.map((year) => (
                  <SelectItem key={year} value={year.toString()}>
                    {year}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            <Button
              variant="outline"
              size="icon"
              onClick={handleNextMonth}
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>

          <div className="flex items-center gap-2 ml-auto">
            <Button
              variant={viewMode === 'month' ? 'default' : 'outline'}
              size="sm"
              onClick={() => setViewMode('month')}
            >
              {tS3('monthView')}
            </Button>
            <Button
              variant={viewMode === 'year' ? 'default' : 'outline'}
              size="sm"
              onClick={() => setViewMode('year')}
            >
              {tS3('yearView')}
            </Button>
          </div>
        </div>

        {/* Content */}
        {isLoading ? (
          <div className="space-y-4">
            {Array.from({ length: 3 }).map((_, i) => (
              <Card key={i}>
                <CardHeader>
                  <Skeleton className="h-6 w-48" />
                </CardHeader>
                <CardContent>
                  <div className="flex gap-1">
                    {Array.from({ length: 10 }).map((_, j) => (
                      <Skeleton key={j} className="w-8 h-8 rounded" />
                    ))}
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        ) : error ? (
          <Card>
            <CardContent className="py-8 text-center text-muted-foreground">
              {tS3('loadingPlanError')}
            </CardContent>
          </Card>
        ) : !plan ? (
          <Card>
            <CardContent className="py-12 text-center">
              <p className="text-muted-foreground mb-4">
                Kein Plan fuer {getMonthName(selectedMonth)} {selectedYear} vorhanden
              </p>
              <Button disabled>
                <Plus className="h-4 w-4 mr-2" />
                Plan erstellen
              </Button>
            </CardContent>
          </Card>
        ) : (
          <div className="grid gap-6 lg:grid-cols-3">
            {/* Categories Grid */}
            <div className="lg:col-span-2 space-y-4">
              {/* Week Legend */}
              <Card className="bg-muted/50">
                <CardContent className="py-3">
                  <div className="flex items-center gap-4 text-sm">
                    <span className="text-muted-foreground">{tS3('legend')}:</span>
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 rounded-sm bg-gray-300 dark:bg-gray-600" />
                      <span>{tS3('status.not_started')}</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 rounded-sm bg-yellow-400" />
                      <span>{tS3('status.in_progress')}</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 rounded-sm bg-green-500" />
                      <span>{tS3('status.completed')}</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 rounded-sm bg-red-500" />
                      <span>{tS3('status.issue')}</span>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* Category Cards */}
              {plan.categories.length === 0 ? (
                <Card>
                  <CardContent className="py-8 text-center text-muted-foreground">
                    {tS3('noCategories')}
                  </CardContent>
                </Card>
              ) : (
                plan.categories.map((category) => (
                  <S3CategoryCard
                    key={category.id}
                    category={category}
                    weeks={weeksToDisplay}
                    onStatusUpdate={handleStatusUpdate}
                    updatingStatusId={updatingStatusId}
                    canEdit={true}
                  />
                ))
              )}
            </div>

            {/* Sidebar with Progress */}
            <div className="space-y-4">
              <S3ProgressChart data={statusCounts} height={250} />

              {/* Plan Info */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-base">Plan-Details</CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">Erstellt von</span>
                    <span>
                      {plan.createdBy.firstName} {plan.createdBy.lastName}
                    </span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">Erstellt am</span>
                    <span>
                      {new Date(plan.createdAt).toLocaleDateString('de-DE')}
                    </span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">Kategorien</span>
                    <span>{plan.categories.length}</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">Status</span>
                    <span
                      className={
                        plan.isActive ? 'text-green-600' : 'text-muted-foreground'
                      }
                    >
                      {plan.isActive ? 'Aktiv' : 'Inaktiv'}
                    </span>
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        )}
      </div>
    </PageTransition>
  );
}
