'use client';

import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import { cn } from '@/lib/utils';
import type { S3Category, S3Status, S3StatusType, S3Type } from '@/hooks/lean/use-s3-plans';
import { S3StatusCell } from './s3-status-cell';
import { S3StatusModal } from './s3-status-modal';

interface S3CategoryCardProps {
  /** Category data */
  category: S3Category;
  /** Week numbers to display */
  weeks: number[];
  /** Callback when status is updated */
  onStatusUpdate: (statusId: string, data: { status: S3StatusType; note?: string }) => void;
  /** Status ID being updated */
  updatingStatusId?: string | null;
  /** Whether user can edit */
  canEdit?: boolean;
  /** Additional CSS classes */
  className?: string;
}

/**
 * S3 Type badge colors and labels
 */
const S3_TYPE_CONFIG: Record<S3Type, { label: string; variant: 'default' | 'secondary' | 'outline' }> = {
  SEIRI: { label: 'Seiri', variant: 'default' },
  SEITON: { label: 'Seiton', variant: 'secondary' },
  SEISO: { label: 'Seiso', variant: 'outline' },
};

/**
 * Calculate progress percentage for a category
 */
function calculateProgress(statuses: S3Status[]): number {
  if (statuses.length === 0) return 0;
  const completed = statuses.filter((s) => s.status === 'GREEN').length;
  return Math.round((completed / statuses.length) * 100);
}

/**
 * S3 Category Card Component
 * Displays a category with its weekly status grid
 */
export function S3CategoryCard({
  category,
  weeks,
  onStatusUpdate,
  updatingStatusId,
  canEdit = true,
  className,
}: S3CategoryCardProps) {
  const t = useTranslations('lean');

  const [selectedStatus, setSelectedStatus] = useState<S3Status | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);

  const typeConfig = S3_TYPE_CONFIG[category.s3Type];
  const progress = calculateProgress(category.statuses);

  // Create a map of week -> status for easy lookup
  const statusByWeek = new Map<number, S3Status>();
  category.statuses.forEach((status) => {
    statusByWeek.set(status.week, status);
  });

  const handleCellClick = (status: S3Status) => {
    if (!canEdit) return;
    setSelectedStatus(status);
    setIsModalOpen(true);
  };

  const handleStatusUpdate = (
    statusId: string,
    data: { status: S3StatusType; note?: string }
  ) => {
    onStatusUpdate(statusId, data);
    setIsModalOpen(false);
  };

  return (
    <>
      <Card className={cn('overflow-hidden', className)}>
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <CardTitle className="text-base">{category.name}</CardTitle>
              <Badge variant={typeConfig.variant}>{typeConfig.label}</Badge>
            </div>
            <div className="flex items-center gap-2">
              <span className="text-sm text-muted-foreground">
                {progress}% {t('completed').toLowerCase()}
              </span>
              <div className="w-24 h-2 bg-muted rounded-full overflow-hidden">
                <div
                  className={cn(
                    'h-full transition-all duration-300',
                    progress >= 80
                      ? 'bg-green-500'
                      : progress >= 50
                      ? 'bg-yellow-500'
                      : 'bg-gray-400'
                  )}
                  style={{ width: `${progress}%` }}
                />
              </div>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <ScrollArea className="w-full">
            <div className="flex gap-1 pb-2">
              {/* Week headers */}
              <div className="flex flex-col gap-1">
                <div className="h-5 flex items-center justify-center text-xs text-muted-foreground font-medium">
                  KW
                </div>
              </div>

              {weeks.map((week) => {
                const status = statusByWeek.get(week);
                return (
                  <div key={week} className="flex flex-col gap-1 items-center">
                    <div className="h-5 flex items-center justify-center text-xs text-muted-foreground w-8">
                      {week}
                    </div>
                    {status ? (
                      <S3StatusCell
                        status={status.status}
                        week={week}
                        note={status.note}
                        completedBy={
                          status.completedBy
                            ? `${status.completedBy.firstName} ${status.completedBy.lastName}`
                            : null
                        }
                        completedAt={status.completedAt}
                        onClick={canEdit ? () => handleCellClick(status) : undefined}
                        isUpdating={updatingStatusId === status.id}
                      />
                    ) : (
                      <div className="w-8 h-8 rounded-sm bg-muted/50" />
                    )}
                  </div>
                );
              })}
            </div>
            <ScrollBar orientation="horizontal" />
          </ScrollArea>
        </CardContent>
      </Card>

      {/* Status Edit Modal */}
      <S3StatusModal
        open={isModalOpen}
        onOpenChange={setIsModalOpen}
        status={selectedStatus}
        categoryName={category.name}
        onUpdate={handleStatusUpdate}
        isUpdating={!!updatingStatusId}
      />
    </>
  );
}
