'use client';

import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { formatDistanceToNow } from 'date-fns';
import { de, enUS } from 'date-fns/locale';
import { motion } from 'framer-motion';
import {
  ClipboardCheck,
  AlertTriangle,
  Search,
  Shield,
  TrendingUp,
  TrendingDown,
  Minus,
  Calendar,
} from 'lucide-react';

import { cn } from '@/lib/utils';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { Progress } from '@/components/ui/progress';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  useAudits,
  useOpenFindings,
  useFindingCounts,
  useComplianceScore,
  getDaysUntilAudit,
} from '@/hooks/integrations';

interface GembaDocsContentProps {
  locale: string;
}

const severityColors: Record<string, { bg: string; text: string }> = {
  critical: { bg: 'bg-red-100', text: 'text-red-700' },
  high: { bg: 'bg-orange-100', text: 'text-orange-700' },
  medium: { bg: 'bg-yellow-100', text: 'text-yellow-700' },
  low: { bg: 'bg-blue-100', text: 'text-blue-700' },
};

const statusColors: Record<string, { bg: string; text: string }> = {
  scheduled: { bg: 'bg-blue-100', text: 'text-blue-700' },
  in_progress: { bg: 'bg-yellow-100', text: 'text-yellow-700' },
  completed: { bg: 'bg-green-100', text: 'text-green-700' },
  cancelled: { bg: 'bg-gray-100', text: 'text-gray-700' },
  open: { bg: 'bg-red-100', text: 'text-red-700' },
  resolved: { bg: 'bg-green-100', text: 'text-green-700' },
  verified: { bg: 'bg-emerald-100', text: 'text-emerald-700' },
};

/**
 * GembaDocs integration content - displays audits, findings, and compliance scores
 */
export function GembaDocsContent({ locale }: GembaDocsContentProps) {
  const t = useTranslations('integrations');
  const tTime = useTranslations('time');
  const [searchQuery, setSearchQuery] = useState('');
  const dateLocale = locale === 'de' ? de : enUS;

  const { data: audits, isLoading: auditsLoading } = useAudits();
  const { data: openFindings, isLoading: findingsLoading } = useOpenFindings();
  const { data: findingCounts, isLoading: countsLoading } = useFindingCounts();
  const { data: compliance, isLoading: complianceLoading } = useComplianceScore();

  const TrendIcon =
    compliance?.trend === 'up'
      ? TrendingUp
      : compliance?.trend === 'down'
        ? TrendingDown
        : Minus;

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

  const filteredAudits = audits?.filter(
    (a) =>
      !searchQuery ||
      a.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      a.department.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <div className="space-y-6">
      {/* Stats Cards */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">
              {t('complianceScore')}
            </CardTitle>
            <Shield className="h-4 w-4 text-primary" />
          </CardHeader>
          <CardContent>
            {complianceLoading ? (
              <Skeleton className="h-8 w-16" />
            ) : (
              <div className="flex items-center gap-2">
                <div className="text-2xl font-bold">{compliance?.overall ?? 0}%</div>
                <TrendIcon className={cn('h-4 w-4', trendColor)} />
              </div>
            )}
            {!complianceLoading && compliance && (
              <Progress value={compliance.overall} className="mt-2" />
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">
              {t('audits')}
            </CardTitle>
            <ClipboardCheck className="h-4 w-4 text-blue-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {auditsLoading ? <Skeleton className="h-8 w-12" /> : audits?.length ?? 0}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">
              {t('openFindings')}
            </CardTitle>
            <AlertTriangle className="h-4 w-4 text-orange-500" />
          </CardHeader>
          <CardContent>
            <div className={cn('text-2xl font-bold', (findingCounts?.total ?? 0) > 0 && 'text-orange-500')}>
              {countsLoading ? <Skeleton className="h-8 w-12" /> : findingCounts?.total ?? 0}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">
              {t('critical')}
            </CardTitle>
            <AlertTriangle className="h-4 w-4 text-red-500" />
          </CardHeader>
          <CardContent>
            <div className={cn('text-2xl font-bold', (findingCounts?.critical ?? 0) > 0 && 'text-red-500')}>
              {countsLoading ? <Skeleton className="h-8 w-12" /> : findingCounts?.critical ?? 0}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Finding Severity Breakdown */}
      {!countsLoading && findingCounts && findingCounts.total > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>{t('findingsBySeverity')}</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex gap-3">
              {(['critical', 'high', 'medium', 'low'] as const).map((severity) => {
                const count = findingCounts[severity];
                const colors = severityColors[severity];
                return (
                  <Badge key={severity} className={cn(colors.bg, colors.text, 'text-sm')}>
                    {severity}: {count}
                  </Badge>
                );
              })}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Audits Table */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle>{t('audits')}</CardTitle>
              <CardDescription>
                {t('allAuditsStatus')}
              </CardDescription>
            </div>
            <div className="relative w-64">
              <Search className="absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder={t('searchAudits')}
                className="pl-8"
              />
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <ScrollArea className="h-[400px]">
            {auditsLoading ? (
              <div className="space-y-2">
                {Array.from({ length: 5 }).map((_, i) => (
                  <Skeleton key={i} className="h-16 w-full" />
                ))}
              </div>
            ) : filteredAudits && filteredAudits.length > 0 ? (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>{t('documentTitle')}</TableHead>
                    <TableHead>{t('type')}</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>{t('department')}</TableHead>
                    <TableHead>{t('findings')}</TableHead>
                    <TableHead>{t('scheduled')}</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredAudits.map((audit, index) => {
                    const daysUntil = getDaysUntilAudit(audit.scheduledDate);
                    const colors = statusColors[audit.status] ?? statusColors.scheduled;
                    return (
                      <motion.tr
                        key={audit.id}
                        initial={{ opacity: 0, y: 10 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ duration: 0.2, delay: index * 0.03 }}
                        className="border-b transition-colors hover:bg-muted/50"
                      >
                        <TableCell>
                          <div className="flex items-center gap-3">
                            <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10 text-primary">
                              <ClipboardCheck className="h-5 w-5" />
                            </div>
                            <div>
                              <p className="font-medium">{audit.title}</p>
                              <p className="text-xs text-muted-foreground">{audit.auditor}</p>
                            </div>
                          </div>
                        </TableCell>
                        <TableCell>
                          <Badge variant="outline">{audit.type}</Badge>
                        </TableCell>
                        <TableCell>
                          <Badge className={cn(colors.bg, colors.text)}>
                            {audit.status.replace('_', ' ')}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-muted-foreground">{audit.department}</TableCell>
                        <TableCell>
                          <span className={cn(audit.openFindingsCount > 0 && 'text-orange-600 font-medium')}>
                            {audit.openFindingsCount}/{audit.findingsCount}
                          </span>
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-1 text-sm">
                            <Calendar className="h-3 w-3" />
                            {daysUntil !== null && daysUntil >= 0 ? (
                              <span className={cn(daysUntil <= 7 && 'text-orange-600')}>
                                {daysUntil === 0
                                  ? t('today')
                                  : `${daysUntil}d`}
                              </span>
                            ) : (
                              <span className="text-muted-foreground">
                                {formatDistanceToNow(audit.scheduledDate, {
                                  addSuffix: true,
                                  locale: dateLocale,
                                })}
                              </span>
                            )}
                          </div>
                        </TableCell>
                      </motion.tr>
                    );
                  })}
                </TableBody>
              </Table>
            ) : (
              <div className="flex items-center justify-center py-8 text-muted-foreground">
                <ClipboardCheck className="mr-2 h-5 w-5" />
                {searchQuery
                  ? t('noAuditsFound')
                  : t('noAuditsAvailable')}
              </div>
            )}
          </ScrollArea>
        </CardContent>
      </Card>
    </div>
  );
}
