'use client';

import Link from 'next/link';
import { motion } from 'motion/react';
import {
  AlertTriangle,
  ArrowRight,
  Award,
  Clock,
  TrendingUp,
  Users,
  UserCheck,
  CalendarCheck,
  Sparkles,
  ShieldAlert,
} from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { DatePicker } from '@/components/ui/date-picker';
import { AppSpinner } from '@/components/ui/app-loader';
import { staggerContainer, staggerItem } from '@/lib/motion';
import { useTeamInsights } from '@/hooks/use-team-insights';
import { getPerformanceGrade } from '@/lib/scoring-utils';
import { cn } from '@/lib/utils';
import { useState, type ReactNode, type ElementType } from 'react';
import { DASHBOARD_DEFAULT_DATE_FROM, DASHBOARD_DEFAULT_DATE_TO } from '@/lib/date-utils';

function Metric({
  label,
  value,
  hint,
  icon: Icon,
}: {
  label: string;
  value: ReactNode;
  hint?: string;
  icon: ElementType;
}) {
  return (
    <div className="px-4 py-3.5 min-w-0">
      <div className="flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground">
        <Icon className="h-3 w-3 text-primary" />
        {label}
      </div>
      <div className="mt-1 text-xl font-semibold tracking-tight tabular-nums text-foreground">
        {value}
      </div>
      {hint ? <p className="mt-0.5 text-xs text-muted-foreground truncate">{hint}</p> : null}
    </div>
  );
}

function scoreTone(score: number) {
  if (score >= 80) return 'text-emerald-600 dark:text-emerald-400';
  if (score >= 70) return 'text-primary';
  if (score >= 60) return 'text-amber-600 dark:text-amber-400';
  return 'text-red-600 dark:text-red-400';
}

export function ExecutiveOverview({
  title = 'Department overview',
  subtitle,
}: {
  title?: string;
  subtitle?: string;
}) {
  const [dateFrom, setDateFrom] = useState(DASHBOARD_DEFAULT_DATE_FROM);
  const [dateTo, setDateTo] = useState(DASHBOARD_DEFAULT_DATE_TO);
  const { data, loading, error, progress, reload } = useTeamInsights(dateFrom, dateTo);

  if (loading && !data) {
    return (
      <div className="flex min-h-[50vh] flex-col items-center justify-center gap-3">
        <AppSpinner className="h-8 w-8" />
        <p className="text-sm text-muted-foreground">
          Evaluating department performance…
          {progress.total > 0 ? ` ${progress.done}/${progress.total}` : ''}
        </p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="rounded-xl border border-border bg-card p-8 text-center space-y-3">
        <p className="text-sm text-destructive">{error}</p>
        <Button variant="outline" size="sm" onClick={reload}>
          Retry
        </Button>
      </div>
    );
  }

  if (!data) return null;
  const { overview, leads } = data;
  const bestLead = leads[0];
  const attentionLead = [...leads].sort((a, b) => a.avgOverall - b.avgOverall)[0];

  return (
    <motion.div
      className="space-y-6"
      variants={staggerContainer}
      initial="initial"
      animate="animate"
    >
      <motion.div
        variants={staggerItem}
        className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between"
      >
        <div className="space-y-1 min-w-0">
          <p className="text-sm text-muted-foreground">{data.department}</p>
          <h2 className="text-2xl font-semibold tracking-tight text-foreground">{title}</h2>
          <p className="text-sm text-muted-foreground max-w-2xl">
            {subtitle ||
              'Executive bird’s-eye view of departmental health, team leadership, and people who need attention.'}
          </p>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          <DatePicker value={dateFrom} onChange={setDateFrom} max={dateTo} buttonClassName="h-9 w-[148px]" />
          <span className="text-xs text-muted-foreground">to</span>
          <DatePicker value={dateTo} onChange={setDateTo} min={dateFrom} buttonClassName="h-9 w-[148px]" />
          <Button
            variant="ghost"
            size="sm"
            className="h-9 text-xs"
            onClick={() => {
              setDateFrom(DASHBOARD_DEFAULT_DATE_FROM);
              setDateTo(DASHBOARD_DEFAULT_DATE_TO);
            }}
          >
            Reset
          </Button>
        </div>
      </motion.div>

      {/* KPI strip */}
      <motion.div
        variants={staggerItem}
        className="rounded-xl border border-border bg-card overflow-hidden shadow-sm"
      >
        <div className="grid grid-cols-2 lg:grid-cols-5 divide-x divide-y lg:divide-y-0 divide-border">
          <Metric
            label="Headcount"
            value={overview.headcount}
            hint={`${overview.leadCount} leads · ${overview.memberCount} members`}
            icon={Users}
          />
          <Metric
            label="Dept performance"
            value={
              <span className={scoreTone(overview.avgOverall)}>
                {overview.avgOverall.toFixed(1)}%
                <span className="ml-1.5 text-sm font-medium text-muted-foreground">
                  {getPerformanceGrade(overview.avgOverall)}
                </span>
              </span>
            }
            hint="Weighted team average"
            icon={TrendingUp}
          />
          <Metric
            label="Attendance"
            value={`${overview.avgAttendance.toFixed(1)}%`}
            hint="Average present rate"
            icon={CalendarCheck}
          />
          <Metric
            label="Logged hours"
            value={`${overview.totalHours.toFixed(0)}h`}
            hint={
              overview.expectedHours > 0
                ? `${overview.hoursUtilization}% of expected`
                : 'Period total'
            }
            icon={Clock}
          />
          <Metric
            label="Needs attention"
            value={overview.needsAttention.length}
            hint="Score under 70% or gaps"
            icon={ShieldAlert}
          />
        </div>
      </motion.div>

      {/* Alerts */}
      {overview.alerts.length > 0 && (
        <motion.div variants={staggerItem} className="grid gap-2 sm:grid-cols-2">
          {overview.alerts.map((alert, i) => (
            <div
              key={i}
              className={cn(
                'flex items-start gap-2.5 rounded-xl border px-4 py-3 text-sm',
                alert.type === 'danger' &&
                  'border-red-500/25 bg-red-500/5 text-red-700 dark:text-red-300',
                alert.type === 'warning' &&
                  'border-amber-500/25 bg-amber-500/5 text-amber-800 dark:text-amber-300',
                alert.type === 'success' &&
                  'border-emerald-500/25 bg-emerald-500/5 text-emerald-800 dark:text-emerald-300',
                alert.type === 'info' && 'border-border bg-muted/40 text-muted-foreground'
              )}
            >
              {alert.type === 'success' ? (
                <Sparkles className="h-4 w-4 shrink-0 mt-0.5" />
              ) : (
                <AlertTriangle className="h-4 w-4 shrink-0 mt-0.5" />
              )}
              <span>{alert.message}</span>
            </div>
          ))}
        </motion.div>
      )}

      {/* Unit / skill-group comparison (within department) */}
      {overview.unitBreakdown.length > 1 && (
        <motion.section
          variants={staggerItem}
          className="rounded-xl border border-border bg-card overflow-hidden"
        >
          <div className="px-4 py-3 border-b border-border">
            <h3 className="text-sm font-semibold text-foreground">
              Performance by unit / specialty
            </h3>
            <p className="text-xs text-muted-foreground">
              Groups from design sub-team, tech stack, or position
            </p>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 divide-y sm:divide-y-0 sm:divide-x divide-border">
            {overview.unitBreakdown.slice(0, 4).map((unit) => (
              <div key={unit.name} className="px-4 py-3.5 min-w-0">
                <p className="text-xs font-medium text-foreground truncate" title={unit.name}>
                  {unit.name}
                </p>
                <p className={cn('mt-1 text-lg font-semibold tabular-nums', scoreTone(unit.avgOverall))}>
                  {unit.avgOverall.toFixed(1)}%
                </p>
                <p className="text-[11px] text-muted-foreground tabular-nums">
                  {unit.count} people · {unit.totalHours.toFixed(0)}h
                </p>
              </div>
            ))}
          </div>
        </motion.section>
      )}

      <div className="grid grid-cols-1 xl:grid-cols-3 gap-5">
        {/* Team lead comparison */}
        <motion.section
          variants={staggerItem}
          className="xl:col-span-2 rounded-xl border border-border bg-card overflow-hidden"
        >
          <div className="flex items-center justify-between gap-3 px-4 py-3 border-b border-border">
            <div>
              <h3 className="text-sm font-semibold text-foreground">Performance by Team Lead</h3>
              <p className="text-xs text-muted-foreground">
                Ranked by average overall score of the lead’s team
              </p>
            </div>
            {bestLead && (
              <Badge className="bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 border-emerald-500/20">
                Top: {bestLead.lead.name.split(' ')[0]}
              </Badge>
            )}
          </div>
          <div className="divide-y divide-border">
            {leads.length === 0 ? (
              <p className="px-4 py-8 text-sm text-muted-foreground text-center">
                No unit leads found in this department.
              </p>
            ) : (
              leads.map((team, idx) => (
                <div key={team.lead.id} className="px-4 py-3.5 flex flex-col gap-2 sm:flex-row sm:items-center">
                  <div className="flex items-center gap-3 min-w-0 sm:w-[42%]">
                    <span className="text-xs font-semibold tabular-nums text-muted-foreground w-5">
                      #{idx + 1}
                    </span>
                    <div className="min-w-0">
                      <p className="text-sm font-medium text-foreground truncate">{team.lead.name}</p>
                      <p className="text-xs text-muted-foreground truncate">
                        {team.lead.position || 'Team Lead'} · {team.memberCount} people
                      </p>
                    </div>
                  </div>
                  <div className="flex-1 space-y-1.5 min-w-0">
                    <div className="flex items-center justify-between text-xs">
                      <span className="text-muted-foreground">Team avg</span>
                      <span className={cn('font-semibold tabular-nums', scoreTone(team.avgOverall))}>
                        {team.avgOverall.toFixed(1)}%
                      </span>
                    </div>
                    <Progress value={Math.min(100, team.avgOverall)} className="h-1.5" />
                  </div>
                  <div className="sm:w-28 text-right text-xs text-muted-foreground tabular-nums">
                    {team.totalHours.toFixed(0)}h logged
                  </div>
                </div>
              ))
            )}
          </div>
          {attentionLead && attentionLead.avgOverall > 0 && attentionLead.avgOverall < 70 && (
            <div className="px-4 py-2.5 border-t border-border bg-amber-500/5 text-xs text-amber-800 dark:text-amber-300">
              Immediate attention: <strong>{attentionLead.lead.name}</strong>’s team at{' '}
              {attentionLead.avgOverall.toFixed(1)}%
            </div>
          )}
        </motion.section>

        {/* Grade distribution */}
        <motion.section
          variants={staggerItem}
          className="rounded-xl border border-border bg-card overflow-hidden"
        >
          <div className="px-4 py-3 border-b border-border">
            <h3 className="text-sm font-semibold text-foreground">Score distribution</h3>
            <p className="text-xs text-muted-foreground">Employees with scored data</p>
          </div>
          <div className="p-4 space-y-3">
            {overview.gradeDistribution.length === 0 ? (
              <p className="text-sm text-muted-foreground text-center py-6">No grades yet</p>
            ) : (
              (() => {
                const scoredTotal =
                  overview.gradeDistribution.reduce((s, g) => s + g.count, 0) || 1;
                return overview.gradeDistribution.map((g) => (
                  <div key={g.grade} className="space-y-1">
                    <div className="flex items-center justify-between text-xs">
                      <span className="font-medium text-foreground">{g.grade}</span>
                      <span className="tabular-nums text-muted-foreground">{g.count}</span>
                    </div>
                    <div className="h-1.5 rounded-full bg-muted overflow-hidden">
                      <div
                        className="h-full rounded-full bg-primary"
                        style={{ width: `${(g.count / scoredTotal) * 100}%` }}
                      />
                    </div>
                  </div>
                ));
              })()
            )}
          </div>
        </motion.section>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
        {/* Top performers */}
        <motion.section
          variants={staggerItem}
          className="rounded-xl border border-border bg-card overflow-hidden"
        >
          <div className="flex items-center gap-2 px-4 py-3 border-b border-border">
            <Award className="h-4 w-4 text-emerald-600 dark:text-emerald-400" />
            <h3 className="text-sm font-semibold text-foreground">Top performers</h3>
          </div>
          <div className="divide-y divide-border">
            {overview.topPerformers.length === 0 ? (
              <p className="px-4 py-8 text-sm text-muted-foreground text-center">No scored employees</p>
            ) : (
              overview.topPerformers.map((e, i) => (
                <Link
                  key={e.user.id}
                  href={`/dashboard/users/${e.user.id}`}
                  className="flex items-center gap-3 px-4 py-3 hover:bg-muted/40 transition-colors"
                >
                  <span className="text-xs font-semibold text-muted-foreground w-4">#{i + 1}</span>
                  <div className="min-w-0 flex-1">
                    <p className="text-sm font-medium text-foreground truncate">{e.user.name}</p>
                    <p className="text-xs text-muted-foreground truncate">
                      {e.user.position || e.user.role}
                      {e.user.managerName ? ` · ${e.user.managerName}` : ''}
                    </p>
                  </div>
                  <div className="text-right shrink-0">
                    <p className={cn('text-sm font-semibold tabular-nums', scoreTone(e.overallScore))}>
                      {e.overallScore.toFixed(1)}%
                    </p>
                    <p className="text-[10px] text-muted-foreground">{e.grade}</p>
                  </div>
                </Link>
              ))
            )}
          </div>
        </motion.section>

        {/* Needs attention */}
        <motion.section
          variants={staggerItem}
          className="rounded-xl border border-border bg-card overflow-hidden"
        >
          <div className="flex items-center gap-2 px-4 py-3 border-b border-border">
            <UserCheck className="h-4 w-4 text-amber-600 dark:text-amber-400" />
            <h3 className="text-sm font-semibold text-foreground">Requires attention</h3>
          </div>
          <div className="divide-y divide-border">
            {overview.needsAttention.length === 0 ? (
              <p className="px-4 py-8 text-sm text-muted-foreground text-center">
                No critical flags in this period
              </p>
            ) : (
              overview.needsAttention.map((e) => (
                <Link
                  key={e.user.id}
                  href={`/dashboard/users/${e.user.id}`}
                  className="flex items-start gap-3 px-4 py-3 hover:bg-muted/40 transition-colors"
                >
                  <div className="min-w-0 flex-1">
                    <p className="text-sm font-medium text-foreground truncate">{e.user.name}</p>
                    <p className="text-xs text-muted-foreground truncate">
                      {e.alerts[0] || e.description}
                    </p>
                  </div>
                  <div className="text-right shrink-0">
                    <p className={cn('text-sm font-semibold tabular-nums', scoreTone(e.overallScore))}>
                      {e.overallScore.toFixed(1)}%
                    </p>
                    <p className="text-[10px] text-muted-foreground">{e.grade}</p>
                  </div>
                </Link>
              ))
            )}
          </div>
        </motion.section>
      </div>

      <motion.div variants={staggerItem} className="flex flex-wrap gap-2">
        <Button asChild variant="outline" size="sm">
          <Link href="/dashboard/analytics">
            Open detailed analytics
            <ArrowRight className="h-3.5 w-3.5 ml-1.5" />
          </Link>
        </Button>
        <Button asChild variant="outline" size="sm">
          <Link href="/dashboard/users">
            View users list
            <ArrowRight className="h-3.5 w-3.5 ml-1.5" />
          </Link>
        </Button>
      </motion.div>
    </motion.div>
  );
}
