'use client';

import { useState, useEffect } from '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 {
  Clock,
  Calendar,
  TrendingUp,
  BarChart3,
  Target,
  Activity,
  CheckCircle,
  AlertCircle
} from 'lucide-react';
import { ChartPanelSkeleton, MetricStripSkeleton } from '@/components/ui/loading-skeletons';
import { api } from '@/lib/store/api';
import { apiCall } from '@/lib/store/api-call';

interface LoggedHour {
  id: string;
  date: string;
  hours: number;
  description: string;
  task?: string;
  isPublished: boolean;
  project: {
    id: string;
    name: string;
    status: string;
  } | null;
}

interface UserLoggedHoursVisualizationProps {
  userId: string;
  userName: string;
}

export function UserLoggedHoursVisualization({ userId, userName }: UserLoggedHoursVisualizationProps) {
  const [loggedHours, setLoggedHours] = useState<LoggedHour[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

  const fetchLoggedHours = async () => {
    try {
      setLoading(true);
      const data = await apiCall<LoggedHour[]>(
        api.endpoints.getLoggedHours.initiate({ userId }),
      );
      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 calculateStats = () => {
    if (!loggedHours.length) return null;

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

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

      if (!acc[monthKey]) {
        acc[monthKey] = {
          month: date.toLocaleDateString('en-GB', { month: 'long', year: 'numeric' }),
          hours: 0,
          projects: new Set()
        };
      }

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

      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
    const projectBreakdown = loggedHours.reduce((acc, log) => {
      const projectName = log.project?.name || 'No Project';
      acc[projectName] = (acc[projectName] || 0) + log.hours;
      return acc;
    }, {} as Record<string, number>);

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

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

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

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const day = String(date.getDate()).padStart(2, '0');
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const year = date.getFullYear();
    return `${day}/${month}/${year}`;
  };

  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="p-6">
        <div className="text-center">
          <AlertCircle className="h-12 w-12 text-red-500 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="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>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-foreground">Work Summary</h2>
          <p className="text-muted-foreground">Time tracking analysis for {userName}</p>
        </div>
        <Badge variant="outline" className="bg-primary/10 text-primary border-primary/20">
          {loggedHours.length} entries
        </Badge>
      </div>

      {/* Stats Overview */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <Card className="p-6">
          <div className="flex items-center space-x-3">
            <div className="p-2 bg-primary/10 rounded-lg">
              <Clock className="h-6 w-6 text-primary" />
            </div>
            <div>
              <div className="text-2xl font-bold text-foreground">{formatHours(stats.totalHours)}h</div>
              <div className="text-sm text-muted-foreground">Total Hours</div>
            </div>
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center space-x-3">
            <div className="p-2 bg-primary/5 rounded-lg">
              <BarChart3 className="h-6 w-6 text-primary" />
            </div>
            <div>
              <div className="text-2xl font-bold text-foreground">{stats.uniqueProjects}</div>
              <div className="text-sm text-muted-foreground">Projects</div>
            </div>
          </div>
        </Card>
      </div>

      {/* Monthly Breakdown */}
      <Card className="p-6">
        <div className="flex items-center space-x-2 mb-6">
          <Calendar className="h-5 w-5 text-primary" />
          <h3 className="text-lg font-semibold text-foreground">Monthly Breakdown</h3>
        </div>

        <div className="space-y-4">
          {stats.monthlyStats.map((month, index) => (
            <div key={index} className="flex items-center justify-between p-4 bg-muted/50 rounded-lg">
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-primary/15 rounded-full flex items-center justify-center">
                  <Calendar className="h-5 w-5 text-primary" />
                </div>
                <div>
                  <div className="font-medium text-foreground">{month.month}</div>
                  <div className="text-sm text-muted-foreground">{month.projects} projects</div>
                </div>
              </div>
              <div className="text-right">
                <div className="text-lg font-bold text-foreground">{formatHours(month.hours)}h</div>
                <div className="text-sm text-muted-foreground">
                  {Math.round((month.hours / stats.totalHours) * 100)}% of total
                </div>
              </div>
            </div>
          ))}
        </div>
      </Card>

      {/* Top Projects */}
      <Card className="p-6">
        <div className="flex items-center space-x-2 mb-6">
          <BarChart3 className="h-5 w-5 text-green-600" />
          <h3 className="text-lg font-semibold text-foreground">Top Projects by Hours</h3>
        </div>

        <div className="space-y-4">
          {stats.topProjects.map((project, index) => (
            <div key={index} className="flex items-center justify-between p-4 bg-muted/50 rounded-lg">
              <div className="flex items-center space-x-3">
                <div className="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center text-sm font-bold text-green-700">
                  {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 space-x-3">
                <Progress value={project.percentage} className="w-24 h-2" />
                <Badge className="bg-green-50 text-green-700 border-green-200">
                  {project.percentage}%
                </Badge>
              </div>
            </div>
          ))}
        </div>
      </Card>

      {/* Recent Entries */}
      <Card className="p-6">
        <div className="flex items-center space-x-2 mb-6">
          <Activity className="h-5 w-5 text-primary" />
          <h3 className="text-lg font-semibold text-foreground">Recent Entries</h3>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full border-collapse">
            <thead>
              <tr className="border-b-2 border-border">
                <th className="text-left p-3 font-medium text-foreground">Date</th>
                <th className="text-left p-3 font-medium text-foreground">Project</th>
                <th className="text-center p-3 font-medium text-foreground">Hours</th>
                <th className="text-left p-3 font-medium text-foreground">Description</th>
              </tr>
            </thead>
            <tbody>
              {loggedHours.slice(0, 10).map((entry) => (
                <tr key={entry.id} className="border-b border-border hover:bg-muted/50">
                  <td className="p-3 text-foreground">{formatDate(entry.date)}</td>
                  <td className="p-3">
                    <div className="font-medium text-foreground">
                      {entry.project?.name || 'No Project'}
                    </div>
                    <div className="text-sm text-muted-foreground">
                      {entry.project?.status || 'No status'}
                    </div>
                  </td>
                  <td className="p-3 text-center">
                    <Badge className="bg-primary/10 text-primary border-primary/20">
                      {formatHours(entry.hours)}h
                    </Badge>
                  </td>
                  <td className="p-3 text-foreground/80 max-w-xs truncate">
                    {entry.description || 'No description'}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          {loggedHours.length > 10 && (
            <p className="text-sm text-muted-foreground mt-4 text-center">
              Showing 10 most recent entries of {loggedHours.length} total
            </p>
          )}
        </div>
      </Card>
    </div>
  );
} 