'use client';

import { useState, useEffect } from 'react';
import { motion } from 'motion/react';
import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { TablePagination } from '@/components/ui/table-pagination';
import { LoggedHour } from '@/lib/types';
import {
  Clock,
  Calendar,
  BarChart3,
  Activity,
  AlertCircle
} from 'lucide-react';
import { Skeleton } from '@/components/ui/skeleton';
import { ChartPanelSkeleton, MetricStripSkeleton } from '@/components/ui/loading-skeletons';
import { staggerContainer, staggerItem } from '@/lib/motion';
import { cn } from '@/lib/utils';
import { api } from '@/lib/store/api';
import { apiCall } from '@/lib/store/api-call';
import { loggedHoursCalendarDay } from '@/lib/logged-hours-parse';

const PAGE_SIZE = 10;

interface UserLoggedHoursVizProps {
  userId: string;
  userName: string;
  dateFrom?: string;
  dateTo?: string;
}

export function UserLoggedHoursViz({ userId, userName, dateFrom, dateTo }: UserLoggedHoursVizProps) {
  const [loggedHours, setLoggedHours] = useState<LoggedHour[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [entriesPerPage] = useState(PAGE_SIZE);
  const [expectedDays, setExpectedDays] = useState<number | null>(null);
  const [attendanceLoading, setAttendanceLoading] = useState(true);
  const [attendanceError, setAttendanceError] = useState<string | null>(null);
  const [projectFilter, setProjectFilter] = useState<'all' | 'core' | 'supported'>('all');

  useEffect(() => {
    fetchLoggedHours();
    fetchMonthlyAttendance();
  }, [userId, dateFrom, dateTo]);

  useEffect(() => {
    setCurrentPage(1);
  }, [loggedHours.length, dateFrom, dateTo]);

  // Listen for logged hours updates via custom event
  useEffect(() => {
    const handleLoggedHoursUpdate = (event: CustomEvent) => {
      if (event.detail?.userId === userId) {
        fetchLoggedHours();
      }
    };

    window.addEventListener('loggedHoursUpdated', handleLoggedHoursUpdate as EventListener);
    
    return () => {
      window.removeEventListener('loggedHoursUpdated', handleLoggedHoursUpdate as EventListener);
    };
  }, [userId]);

  const fetchLoggedHours = async () => {
    try {
      setLoading(true);
      const data = await apiCall<LoggedHour[]>(
        api.endpoints.getLoggedHours.initiate({
          userId,
          startDate: dateFrom,
          endDate: dateTo,
        }),
      );
      setLoggedHours(data || []);
      setError(null);
    } catch (err) {
      console.error('Error fetching logged hours:', err);
      setError(err instanceof Error ? err.message : 'Failed to fetch logged hours');
    } finally {
      setLoading(false);
    }
  };

  const fetchMonthlyAttendance = async () => {
    try {
      setAttendanceLoading(true);
      const data = await apiCall<any>(
        api.endpoints.getMonthlyAttendance.initiate({
          userId,
          startDate: dateFrom,
          endDate: dateTo,
        }),
      );
      // Sum expectedDays from all months
      const totalExpectedDays = (data.monthlyAttendance || []).reduce((acc: number, rec: any) => acc + (rec.expectedDays || 0), 0);
      setExpectedDays(totalExpectedDays);
      setAttendanceError(null);
    } catch (err) {
      setAttendanceError(err instanceof Error ? err.message : 'Failed to fetch attendance');
      setExpectedDays(null);
    } finally {
      setAttendanceLoading(false);
    }
  };

  const calculateStats = () => {
    if (!loggedHours.length) return null;

    const totalHours = loggedHours.reduce((acc, log) => acc + log.hours, 0);
    const uniqueProjects = new Set(loggedHours.map(log => log.projectName || log.project?.name).filter(Boolean)).size;

    // Group by month
    const monthlyData = loggedHours.reduce((acc, log) => {
      const date = typeof log.date === 'string' ? new Date(log.date) : log.date;
      const day = loggedHoursCalendarDay(date);
      const monthKey = day ? day.slice(0, 7) : `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;

      if (!acc[monthKey]) {
        acc[monthKey] = {
          month: new Date(`${monthKey}-01T00:00:00.000Z`).toLocaleDateString('en-GB', {
            month: 'long',
            year: 'numeric',
            timeZone: 'UTC',
          }),
          hours: 0,
          projects: new Set()
        };
      }

      acc[monthKey].hours += log.hours;
      const projectName = log.projectName || log.project?.name;
      if (projectName) {
        acc[monthKey].projects.add(projectName);
      }

      return acc;
    }, {} as Record<string, { month: string; hours: number; projects: Set<string> }>);

    const monthlyStats = Object.values(monthlyData).map(data => ({
      month: data.month,
      hours: data.hours,
      projects: data.projects.size
    })).sort((a, b) => new Date(a.month).getTime() - new Date(b.month).getTime());

    // Project breakdown - prioritize projectName over linked project
    const projectBreakdown = loggedHours.reduce((acc, log) => {
      const projectName = log.projectName || log.project?.name || 'No Project';
      acc[projectName] = (acc[projectName] || 0) + log.hours;
      return acc;
    }, {} as Record<string, number>);

    const allProjects = Object.entries(projectBreakdown)
      .map(([name, hours]) => ({ name, hours, percentage: Math.round((hours / totalHours) * 100) }))
      .sort((a, b) => b.hours - a.hours);

    return {
      totalHours,
      uniqueProjects,
      monthlyStats,
      allProjects
    };
  };

  const formatHours = (hours: number) => {
    return hours.toFixed(2);
  };

  const formatDate = (dateString: string | Date) => {
    const date = typeof dateString === 'string' ? new Date(dateString) : dateString;
    const day = loggedHoursCalendarDay(date);
    if (day) {
      const [year, month, d] = day.split('-');
      return `${d}/${month}/${year}`;
    }
    return '';
  };

  if (loading) {
    return (
      <div className="space-y-6" aria-busy aria-label="Loading logged hours">
        <MetricStripSkeleton cells={4} />
        <ChartPanelSkeleton />
      </div>
    );
  }

  if (error) {
    return (
      <Card className="rounded-xl border border-border bg-card p-6">
        <div className="text-center">
          <AlertCircle className="h-12 w-12 text-red-500 dark:text-red-400 mx-auto mb-4" />
          <h3 className="text-lg font-semibold text-foreground mb-2">Error Loading Logged Hours</h3>
          <p className="text-muted-foreground mb-4">{error}</p>
          <Button onClick={fetchLoggedHours} variant="outline">
            Try Again
          </Button>
        </div>
      </Card>
    );
  }

  const stats = calculateStats();

  if (!stats || loggedHours.length === 0) {
    return (
      <Card className="rounded-xl border border-border bg-card p-6">
        <div className="text-center">
          <Clock className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
          <h3 className="text-lg font-semibold text-foreground mb-2">No Logged Hours</h3>
          <p className="text-muted-foreground">No logged hours found for {userName}</p>
        </div>
      </Card>
    );
  }

  const filterButtonClass = (active: boolean, variant: 'default' | 'primary' = 'default') =>
    cn(
      'px-3 py-1.5 rounded-lg text-xs font-medium transition-colors',
      active
        ? variant === 'primary'
          ? 'bg-primary text-primary-foreground'
          : 'bg-green-600 dark:bg-green-700 text-white'
        : 'bg-muted text-muted-foreground hover:bg-muted/80 hover:text-foreground'
    );

  const expectedHours = expectedDays && expectedDays > 0 ? expectedDays * 8 : null;
  const expectedPct =
    expectedHours && expectedHours > 0
      ? ((stats.totalHours / expectedHours) * 100).toFixed(1)
      : null;

  return (
    <motion.div
      className="space-y-5"
      variants={staggerContainer}
      initial="initial"
      animate="animate"
    >
      {/* Header + compact metric strip */}
      <motion.div variants={staggerItem} className="space-y-3">
        <div className="flex items-center justify-between gap-3">
          <div className="min-w-0">
            <h2 className="text-lg font-semibold tracking-tight text-foreground">Work Summary</h2>
            <p className="text-sm text-muted-foreground truncate">
              Time tracking for {userName}
            </p>
          </div>
          <Badge variant="outline" className="shrink-0 bg-primary/10 text-primary border-primary/20">
            {loggedHours.length} entries
          </Badge>
        </div>

        <div className="rounded-xl border border-border bg-card overflow-hidden shadow-sm">
          <div className="grid grid-cols-2 lg:grid-cols-4 divide-x divide-y lg:divide-y-0 divide-border">
            <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">
                <Clock className="h-3 w-3 text-primary" />
                Logged hours
              </div>
              {attendanceLoading ? (
                <Skeleton className="mt-1.5 h-7 w-28" />
              ) : (
                <p className="mt-1 text-xl font-semibold tracking-tight tabular-nums text-foreground">
                  {formatHours(stats.totalHours)}h
                  {expectedHours != null && (
                    <span className="text-sm font-medium text-muted-foreground">
                      {' '}
                      / {expectedHours}h
                    </span>
                  )}
                </p>
              )}
            </div>
            <div className="px-4 py-3.5 min-w-0">
              <p className="text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground">
                Of expected
              </p>
              {attendanceLoading ? (
                <Skeleton className="mt-1.5 h-7 w-16" />
              ) : attendanceError ? (
                <p className="mt-1 text-sm text-red-500 dark:text-red-400">Unavailable</p>
              ) : (
                <p className="mt-1 text-xl font-semibold tracking-tight tabular-nums text-foreground">
                  {expectedPct != null ? `${expectedPct}%` : '—'}
                </p>
              )}
            </div>
            <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">
                <BarChart3 className="h-3 w-3 text-primary" />
                Projects
              </div>
              <p className="mt-1 text-xl font-semibold tracking-tight tabular-nums text-foreground">
                {stats.uniqueProjects}
              </p>
            </div>
            <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">
                <Calendar className="h-3 w-3 text-primary" />
                Months
              </div>
              <p className="mt-1 text-xl font-semibold tracking-tight tabular-nums text-foreground">
                {stats.monthlyStats.length}
              </p>
            </div>
          </div>
        </div>
      </motion.div>

      {/* Monthly Breakdown — dense table, no wide gaps */}
      <motion.div variants={staggerItem}>
        <Card className="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 className="flex items-center gap-2 min-w-0">
              <Calendar className="h-4 w-4 text-primary shrink-0" />
              <h3 className="text-sm font-semibold text-foreground">Monthly Breakdown</h3>
            </div>
            <span className="text-xs text-muted-foreground tabular-nums shrink-0">
              {stats.monthlyStats.length} month{stats.monthlyStats.length === 1 ? '' : 's'}
            </span>
          </div>

          <div className="overflow-x-auto">
            <table className="w-full border-collapse">
              <thead>
                <tr className="bg-muted/50 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                  <th className="text-left px-4 py-2 border-b border-border">Month</th>
                  <th className="text-center px-3 py-2 border-b border-border w-[100px]">Projects</th>
                  <th className="text-right px-3 py-2 border-b border-border w-[110px]">Hours</th>
                  <th className="text-right px-4 py-2 border-b border-border w-[120px]">Share</th>
                </tr>
              </thead>
              <tbody>
                {stats.monthlyStats.map((month, index) => {
                  const share = Math.round((month.hours / stats.totalHours) * 100);
                  return (
                    <tr
                      key={index}
                      className="border-b border-border/60 last:border-b-0 hover:bg-muted/40"
                    >
                      <td className="px-4 py-2.5 text-sm font-medium text-foreground">
                        {month.month}
                      </td>
                      <td className="px-3 py-2.5 text-center text-sm tabular-nums text-muted-foreground">
                        {month.projects}
                      </td>
                      <td className="px-3 py-2.5 text-right text-sm font-semibold tabular-nums text-foreground">
                        {formatHours(month.hours)}h
                      </td>
                      <td className="px-4 py-2.5">
                        <div className="flex items-center justify-end gap-2">
                          <div className="hidden sm:block h-1.5 w-16 rounded-full bg-muted overflow-hidden">
                            <div
                              className="h-full rounded-full bg-primary"
                              style={{ width: `${Math.min(100, share)}%` }}
                            />
                          </div>
                          <span className="text-xs tabular-nums text-muted-foreground w-8 text-right">
                            {share}%
                          </span>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </Card>
      </motion.div>

      {/* All Projects by Hours */}
      <motion.div variants={staggerItem}>
        <Card className="rounded-xl border border-border bg-card overflow-hidden">
          <div className="flex flex-col sm:flex-row sm:items-center gap-3 px-4 py-3 border-b border-border">
            <div className="flex items-center gap-2">
              <BarChart3 className="h-4 w-4 text-green-600 dark:text-green-400" />
              <h3 className="text-sm font-semibold text-foreground">All Projects by Hours</h3>
            </div>
            <div className="sm:ml-auto flex gap-2">
              <button onClick={() => setProjectFilter('all')} className={filterButtonClass(projectFilter === 'all')}>All</button>
              <button onClick={() => setProjectFilter('core')} className={filterButtonClass(projectFilter === 'core')}>Core Projects</button>
              <button onClick={() => setProjectFilter('supported')} className={filterButtonClass(projectFilter === 'supported', 'primary')}>Supported Projects</button>
            </div>
          </div>

          <div className="p-4 grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
            {stats.allProjects.filter(project => {
              if (projectFilter === 'core') return project.hours >= 50;
              if (projectFilter === 'supported') return project.hours < 50;
              return true;
            }).map((project, index) => {
              const isCore = project.hours >= 50;
              return (
                <div
                  key={project.name}
                  className={cn(
                    'flex flex-col justify-between p-4 rounded-xl border h-full',
                    isCore
                      ? 'bg-green-50 dark:bg-green-950/30 border-green-200 dark:border-green-900/50'
                      : 'bg-primary/10 border-primary/20'
                  )}
                >
                  <div className="flex items-center space-x-3 mb-2">
                    <div className={cn(
                      'w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold',
                      isCore
                        ? 'bg-green-100 dark:bg-green-900/50 text-green-700 dark:text-green-300'
                        : 'bg-primary/15 text-primary'
                    )}>{index + 1}</div>
                    <div>
                      <div className="font-medium text-foreground">{project.name}</div>
                      <div className="text-sm text-muted-foreground">{formatHours(project.hours)} hours</div>
                    </div>
                  </div>
                  <div className="flex items-center flex-wrap gap-2 mt-2">
                    <Progress value={project.percentage} className="w-24 h-2" />
                    <Badge className={isCore
                      ? 'bg-green-50 dark:bg-green-950/50 text-green-700 dark:text-green-300 border-green-200 dark:border-green-800'
                      : 'bg-primary/10 text-primary border-primary/20'
                    }>
                      {project.percentage}%
                    </Badge>
                    <span className={cn(
                      'px-2 py-0.5 rounded text-xs font-semibold',
                      isCore
                        ? 'bg-green-200 dark:bg-green-900/50 text-green-800 dark:text-green-300'
                        : 'bg-primary/20 text-primary'
                    )}>{isCore ? 'Core Project' : 'Supported Project'}</span>
                  </div>
                </div>
              );
            })}
          </div>
        </Card>
      </motion.div>

      {/* All Entries with Pagination */}
      <motion.div variants={staggerItem}>
        <Card 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">
            <Activity className="h-4 w-4 text-primary" />
            <h3 className="text-sm font-semibold text-foreground">All Entries</h3>
          </div>

          <div className="overflow-x-auto">
            <table className="w-full border-collapse">
              <thead className="bg-muted/50 border-b border-border">
                <tr>
                  <th className="text-left py-3 px-4 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Date</th>
                  <th className="text-left py-3 px-4 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Project</th>
                  <th className="text-center py-3 px-4 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Hours</th>
                  <th className="text-left py-3 px-4 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Description</th>
                  <th className="text-left py-3 px-4 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Task</th>
                </tr>
              </thead>
              <tbody>
                {loggedHours
                  .slice((currentPage - 1) * entriesPerPage, currentPage * entriesPerPage)
                  .map((entry) => {
                    const projectName = entry.projectName || entry.project?.name || 'No Project';
                    const projectStatus = entry.project?.status || 'No status';
                    return (
                      <tr key={entry.id} className="border-b border-border transition-colors hover:bg-muted/50">
                        <td className="py-3 px-4 text-foreground">{formatDate(entry.date)}</td>
                        <td className="py-3 px-4">
                          <div className="font-medium text-foreground">
                            {projectName}
                          </div>
                          <div className="text-sm text-muted-foreground">
                            {projectName !== 'No Project' ? projectStatus : 'No status'}
                          </div>
                        </td>
                        <td className="py-3 px-4 text-center">
                          <Badge className="bg-primary/10 text-primary border-primary/20">
                            {formatHours(entry.hours)}h
                          </Badge>
                        </td>
                        <td className="py-3 px-4 text-foreground/80 whitespace-pre-line break-words max-w-xs">{entry.description || 'No description'}</td>
                        <td className="py-3 px-4 text-foreground/80 whitespace-pre-line break-words max-w-xs">{entry.task || 'No task'}</td>
                      </tr>
                    );
                  })}
              </tbody>
            </table>
          </div>

          <TablePagination
            currentPage={currentPage}
            totalItems={loggedHours.length}
            pageSize={entriesPerPage}
            onPageChange={setCurrentPage}
            itemLabel="entries"
          />
        </Card>
      </motion.div>
    </motion.div>
  );
} 