'use client';

import { useTranslations } from 'next-intl';
import { motion } from 'framer-motion';
import Link from 'next/link';
import {
  ClipboardCheck,
  AlertTriangle,
  Calendar,
  TrendingUp,
  TrendingDown,
  Minus,
  ExternalLink,
  AlertCircle,
} from 'lucide-react';

import { cn } from '@/lib/utils';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Separator } from '@/components/ui/separator';
import { WidgetContainer } from '../../widget-container';
import {
  useUpcomingAudits,
  useFindingCounts,
  useComplianceScore,
  getDaysUntilAudit,
} from '@/hooks/integrations';
import type { AuditType, FindingSeverity } from '@/types/integrations';

interface GembaDocsWidgetProps {
  id: string;
  isEditing?: boolean;
  onRemove?: () => void;
  locale?: string;
  className?: string;
}

/** Audit type badge configuration */
const auditTypeConfig: Record<AuditType, { variant: 'default' | 'secondary' | 'outline' }> = {
  internal: { variant: 'secondary' },
  external: { variant: 'default' },
  certification: { variant: 'outline' },
};

/** Severity badge configuration */
const severityConfig: Record<
  FindingSeverity,
  { variant: 'default' | 'secondary' | 'destructive' | 'warning'; className: string }
> = {
  critical: { variant: 'destructive', className: 'bg-red-500 hover:bg-red-600' },
  high: { variant: 'warning', className: 'bg-orange-500 hover:bg-orange-600' },
  medium: { variant: 'secondary', className: 'bg-yellow-500 hover:bg-yellow-600 text-black' },
  low: { variant: 'default', className: 'bg-blue-500 hover:bg-blue-600' },
};

/**
 * GembaDocs Widget - Displays upcoming audits, findings, and compliance score
 */
export function GembaDocsWidget({
  id,
  isEditing = false,
  onRemove,
  locale = 'de',
  className,
}: GembaDocsWidgetProps) {
  const t = useTranslations('widgets.gembadocs');
  const { data: audits, isLoading: auditsLoading } = useUpcomingAudits(3);
  const { data: findingCounts, isLoading: findingsLoading } = useFindingCounts();
  const { data: complianceScore, isLoading: complianceLoading } = useComplianceScore();

  const isLoading = auditsLoading || findingsLoading || complianceLoading;

  /**
   * Format days until audit
   */
  const formatDaysLeft = (scheduledDate: Date): string => {
    const days = getDaysUntilAudit(scheduledDate);
    if (days === 0) return t('today');
    if (days === 1) return t('tomorrow');
    return t('daysLeft', { days });
  };

  /**
   * Get trend icon component
   */
  const TrendIcon = complianceScore?.trend === 'up'
    ? TrendingUp
    : complianceScore?.trend === 'down'
      ? TrendingDown
      : Minus;

  const trendColor = complianceScore?.trend === 'up'
    ? 'text-green-500'
    : complianceScore?.trend === 'down'
      ? 'text-red-500'
      : 'text-muted-foreground';

  return (
    <WidgetContainer
      id={id}
      title={t('name')}
      icon={<ClipboardCheck className="h-4 w-4 text-primary" />}
      isEditing={isEditing}
      onRemove={onRemove}
      className={className}
      colSpan={2}
    >
      {isLoading ? (
        <div className="space-y-4">
          <div className="space-y-2">
            <Skeleton className="h-4 w-1/3" />
            <Skeleton className="h-20 w-full" />
          </div>
          <div className="space-y-2">
            <Skeleton className="h-4 w-1/3" />
            <Skeleton className="h-12 w-full" />
          </div>
        </div>
      ) : (
        <div className="space-y-4">
          {/* Compliance Score */}
          <div className="flex items-center justify-between rounded-lg bg-muted/50 p-3">
            <div className="space-y-1">
              <p className="text-xs text-muted-foreground">{t('complianceScore')}</p>
              <div className="flex items-baseline gap-2">
                <span className="text-2xl font-bold">{complianceScore?.overall ?? 0}%</span>
                <TrendIcon className={cn('h-4 w-4', trendColor)} />
              </div>
            </div>
            {/* Circular progress indicator */}
            <div className="relative h-12 w-12">
              <svg className="h-12 w-12 -rotate-90" viewBox="0 0 36 36">
                <path
                  className="stroke-muted"
                  fill="none"
                  strokeWidth="3"
                  d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
                />
                <path
                  className="stroke-primary"
                  fill="none"
                  strokeWidth="3"
                  strokeLinecap="round"
                  strokeDasharray={`${complianceScore?.overall ?? 0}, 100`}
                  d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
                />
              </svg>
            </div>
          </div>

          {/* Open Findings Summary */}
          <div>
            <div className="mb-2 flex items-center gap-2">
              <AlertTriangle className="h-4 w-4 text-muted-foreground" />
              <span className="text-sm font-medium">{t('openFindings')}</span>
              {findingCounts && findingCounts.total > 0 && (
                <Badge variant="secondary" className="ml-auto">
                  {findingCounts.total}
                </Badge>
              )}
            </div>

            {findingCounts && findingCounts.total > 0 ? (
              <div className="flex flex-wrap gap-2">
                {findingCounts.critical > 0 && (
                  <Badge className={severityConfig.critical.className}>
                    <AlertCircle className="mr-1 h-3 w-3" />
                    {findingCounts.critical} {t('severity.critical')}
                  </Badge>
                )}
                {findingCounts.high > 0 && (
                  <Badge className={severityConfig.high.className}>
                    {findingCounts.high} {t('severity.high')}
                  </Badge>
                )}
                {findingCounts.medium > 0 && (
                  <Badge className={severityConfig.medium.className}>
                    {findingCounts.medium} {t('severity.medium')}
                  </Badge>
                )}
                {findingCounts.low > 0 && (
                  <Badge className={severityConfig.low.className}>
                    {findingCounts.low} {t('severity.low')}
                  </Badge>
                )}
              </div>
            ) : (
              <p className="text-sm text-muted-foreground">
                {t('noAudits')}
              </p>
            )}
          </div>

          <Separator />

          {/* Upcoming Audits */}
          <div>
            <div className="mb-2 flex items-center gap-2">
              <Calendar className="h-4 w-4 text-muted-foreground" />
              <span className="text-sm font-medium">{t('upcomingAudits')}</span>
            </div>

            {audits && audits.length > 0 ? (
              <div className="space-y-2">
                {audits.map((audit, index) => (
                  <motion.div
                    key={audit.id}
                    initial={{ opacity: 0, x: -10 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ duration: 0.2, delay: index * 0.05 }}
                    className="flex items-center justify-between rounded-lg border p-2 text-sm"
                  >
                    <div className="min-w-0 flex-1">
                      <p className="truncate font-medium">{audit.title}</p>
                      <div className="flex items-center gap-2 text-xs text-muted-foreground">
                        <Badge
                          variant={auditTypeConfig[audit.type].variant}
                          className="text-xs"
                        >
                          {t(`auditType.${audit.type}`)}
                        </Badge>
                        <span>{audit.department}</span>
                      </div>
                    </div>
                    <Badge
                      variant="outline"
                      className={cn(
                        'shrink-0 ml-2',
                        getDaysUntilAudit(audit.scheduledDate) <= 3 && 'border-orange-500 text-orange-500'
                      )}
                    >
                      {formatDaysLeft(audit.scheduledDate)}
                    </Badge>
                  </motion.div>
                ))}
              </div>
            ) : (
              <p className="text-sm text-muted-foreground">{t('noAudits')}</p>
            )}
          </div>

          {/* Footer link */}
          <div className="border-t pt-3">
            <Button variant="ghost" size="sm" className="w-full" asChild>
              <Link href={`/${locale}/integrations/gembadocs`}>
                <ExternalLink className="mr-2 h-4 w-4" />
                {t('openGembaDocs')}
              </Link>
            </Button>
          </div>
        </div>
      )}
    </WidgetContainer>
  );
}
