'use client';

import { useState, useMemo } from 'react';
import { useTranslations } from 'next-intl';
import { useRouter, useParams } from 'next/navigation';
import { Building2, Calendar, ChevronRight, Plus, TrendingUp } from 'lucide-react';

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Skeleton } from '@/components/ui/skeleton';
import { Badge } from '@/components/ui/badge';
import { PageTransition } from '@/components/layout/page-transition';
import { cn } from '@/lib/utils';
import { useS3Plans, type S3Plan, type QueryS3PlansParams } from '@/hooks/lean/use-s3-plans';
import { S3ProgressChart } from './s3-progress-chart';

interface S3PlanOverviewProps {
  /** 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] || '';
}

/**
 * Calculate status counts from plans
 */
function calculateStatusCounts(plans: S3Plan[]) {
  const counts = { green: 0, yellow: 0, red: 0, notApplicable: 0 };

  plans.forEach((plan) => {
    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 Plan Overview Component
 * Main overview page showing all department plans with filtering
 */
export function S3PlanOverview({ locale }: S3PlanOverviewProps) {
  const t = useTranslations('lean');
  const tS3 = useTranslations('lean.s3');
  const tNav = useTranslations('navigation');
  const router = useRouter();

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

  const [selectedYear, setSelectedYear] = useState<number>(currentYear);
  const [selectedMonth, setSelectedMonth] = useState<number | null>(null);

  // Build query params
  const queryParams: QueryS3PlansParams = {
    year: selectedYear,
    ...(selectedMonth && { month: selectedMonth }),
    limit: 100,
    sortBy: 'createdAt',
    sortOrder: 'desc',
  };

  const { data: plansData, isLoading, error } = useS3Plans(queryParams);
  const plans = plansData?.data ?? [];

  // Calculate overall stats
  const statusCounts = useMemo(() => calculateStatusCounts(plans), [plans]);
  const totalStatuses = statusCounts.green + statusCounts.yellow + statusCounts.red + statusCounts.notApplicable;
  const completionRate = totalStatuses > 0 ? Math.round((statusCounts.green / totalStatuses) * 100) : 0;

  // Year options for filter
  const yearOptions = Array.from({ length: 5 }, (_, i) => currentYear - 2 + i);

  // Month options for filter
  const monthOptions = Array.from({ length: 12 }, (_, i) => i + 1);

  const handlePlanClick = (plan: S3Plan) => {
    router.push(`/${locale}/lean/s3-planning/${plan.departmentId}?year=${plan.year}&month=${plan.month}`);
  };

  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>
            <h1 className="text-3xl font-bold tracking-tight">{t('s3Planning')}</h1>
            <p className="text-muted-foreground">
              Uebersicht aller Abteilungs-3S-Plaene
            </p>
          </div>
          <Button disabled>
            <Plus className="h-4 w-4 mr-2" />
            Neuer Plan
          </Button>
        </div>

        {/* Filters */}
        <div className="flex flex-wrap gap-4">
          <Select
            value={selectedYear.toString()}
            onValueChange={(value) => setSelectedYear(parseInt(value))}
          >
            <SelectTrigger className="w-32">
              <Calendar className="h-4 w-4 mr-2 text-muted-foreground" />
              <SelectValue placeholder="Jahr" />
            </SelectTrigger>
            <SelectContent>
              {yearOptions.map((year) => (
                <SelectItem key={year} value={year.toString()}>
                  {year}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>

          <Select
            value={selectedMonth?.toString() ?? 'all'}
            onValueChange={(value) =>
              setSelectedMonth(value === 'all' ? null : parseInt(value))
            }
          >
            <SelectTrigger className="w-40">
              <SelectValue placeholder="Alle Monate" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">Alle Monate</SelectItem>
              {monthOptions.map((month) => (
                <SelectItem key={month} value={month.toString()}>
                  {getMonthName(month)}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        {/* Stats Overview */}
        <div className="grid gap-4 md:grid-cols-4">
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                Gesamt-Abschlussrate
              </CardTitle>
            </CardHeader>
            <CardContent>
              {isLoading ? (
                <Skeleton className="h-8 w-16" />
              ) : (
                <>
                  <div className="text-2xl font-bold">{completionRate}%</div>
                  <div className="flex items-center text-xs text-muted-foreground">
                    <TrendingUp className="h-3 w-3 mr-1 text-green-500" />
                    {statusCounts.green} von {totalStatuses} Eintraegen
                  </div>
                </>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                Aktive Plaene
              </CardTitle>
            </CardHeader>
            <CardContent>
              {isLoading ? (
                <Skeleton className="h-8 w-16" />
              ) : (
                <>
                  <div className="text-2xl font-bold">{plans.length}</div>
                  <div className="text-xs text-muted-foreground">
                    in {selectedYear}
                    {selectedMonth ? ` / ${getMonthName(selectedMonth)}` : ''}
                  </div>
                </>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                In Bearbeitung
              </CardTitle>
            </CardHeader>
            <CardContent>
              {isLoading ? (
                <Skeleton className="h-8 w-16" />
              ) : (
                <>
                  <div className="text-2xl font-bold text-yellow-500">
                    {statusCounts.yellow}
                  </div>
                  <div className="text-xs text-muted-foreground">
                    Eintraege aktiv
                  </div>
                </>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                Probleme
              </CardTitle>
            </CardHeader>
            <CardContent>
              {isLoading ? (
                <Skeleton className="h-8 w-16" />
              ) : (
                <>
                  <div className="text-2xl font-bold text-red-500">
                    {statusCounts.red}
                  </div>
                  <div className="text-xs text-muted-foreground">
                    erfordern Massnahmen
                  </div>
                </>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Content */}
        <div className="grid gap-6 lg:grid-cols-3">
          {/* Plans List */}
          <div className="lg:col-span-2 space-y-4">
            <h2 className="text-lg font-semibold">Abteilungsplaene</h2>

            {isLoading ? (
              <div className="space-y-4">
                {Array.from({ length: 3 }).map((_, i) => (
                  <Card key={i}>
                    <CardHeader>
                      <Skeleton className="h-5 w-40" />
                      <Skeleton className="h-4 w-24" />
                    </CardHeader>
                    <CardContent>
                      <Skeleton className="h-4 w-full" />
                    </CardContent>
                  </Card>
                ))}
              </div>
            ) : error ? (
              <Card>
                <CardContent className="py-8 text-center text-muted-foreground">
                  {tS3('loadingError')}
                </CardContent>
              </Card>
            ) : plans.length === 0 ? (
              <Card>
                <CardContent className="py-8 text-center text-muted-foreground">
                  {tS3('noPlansFound')}
                </CardContent>
              </Card>
            ) : (
              <div className="space-y-3">
                {plans.map((plan) => (
                  <Card
                    key={plan.id}
                    className="cursor-pointer hover:shadow-md transition-shadow"
                    onClick={() => handlePlanClick(plan)}
                  >
                    <CardHeader className="pb-2">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <Building2 className="h-5 w-5 text-muted-foreground" />
                          <CardTitle className="text-base">
                            {plan.department.name}
                          </CardTitle>
                        </div>
                        <ChevronRight className="h-5 w-5 text-muted-foreground" />
                      </div>
                      <CardDescription>
                        {getMonthName(plan.month)} {plan.year}
                      </CardDescription>
                    </CardHeader>
                    <CardContent>
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-4">
                          <Badge
                            variant={
                              plan.progress >= 80
                                ? 'success'
                                : plan.progress >= 50
                                ? 'warning'
                                : 'secondary'
                            }
                          >
                            {plan.progress}% abgeschlossen
                          </Badge>
                          <span className="text-sm text-muted-foreground">
                            {plan._count?.categories ?? plan.categories?.length ?? 0} Kategorien
                          </span>
                        </div>
                        <div className="w-32 h-2 bg-muted rounded-full overflow-hidden">
                          <div
                            className={cn(
                              'h-full transition-all',
                              plan.progress >= 80
                                ? 'bg-green-500'
                                : plan.progress >= 50
                                ? 'bg-yellow-500'
                                : 'bg-gray-400'
                            )}
                            style={{ width: `${plan.progress}%` }}
                          />
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            )}
          </div>

          {/* Progress Chart */}
          <div>
            <S3ProgressChart
              data={statusCounts}
              isLoading={isLoading}
              height={250}
            />
          </div>
        </div>
      </div>
    </PageTransition>
  );
}
