'use client';

import { useState, useEffect, useCallback } from 'react';
import { useSession } from 'next-auth/react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useToast } from '@/hooks/use-toast';
import { Upload, Download, BarChart3, Users, Clock, TrendingUp } from 'lucide-react';
import { format } from 'date-fns';
import { AttendanceTableSkeleton } from '@/components/ui/loading-skeletons';
import { api } from '@/lib/store/api';
import { apiCall } from '@/lib/store/api-call';

interface AttendanceStats {
  totalDays: number;
  presentDays: number;
  absentDays: number;
  attendancePercentage: number;
  avgWorkingHours: number;
  totalLateMinutes: number;
}

interface MonthlyAttendanceRecord {
  id: string;
  userId: string;
  employeeNumber?: string;
  month: number;
  year: number;
  expectedDays: number;
  presentDays: number;
  absentDays: number;
  inLateMinutes: number;
  outLateMinutes: number;
  totalLateMinutes: number;
  leaveAmount: number;
  department?: string;
  designation?: string;
  createdAt: string;
  updatedAt: string;
}

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

export function UserAttendance({ userId, userName }: UserAttendanceProps) {
  const { data: session } = useSession();
  const [monthlyAttendance, setMonthlyAttendance] = useState<MonthlyAttendanceRecord[]>([]);
  
  // Check if user has restricted position (CEO, COO, HR)
  const isRestrictedPosition = () => {
    if (!session?.user?.position) return false;
    
    const userPosition = session.user.position;
    const isExecutive = ['CEO', 'COO'].includes(userPosition);
    const isHR = userPosition.includes('HR') || 
                 userPosition.includes('Human Resources') ||
                 userPosition === 'VP Human Resources' ||
                 userPosition === 'HR Manager' ||
                 userPosition === 'HR Business Partner' ||
                 userPosition === 'Talent Acquisition Manager';
    
    return isExecutive || isHR;
  };
  const [loading, setLoading] = useState(false);
  const [importing, setImporting] = useState(false);
  const [stats, setStats] = useState<AttendanceStats | null>(null);
  const { toast } = useToast();

  const fetchAttendance = useCallback(async () => {
    setLoading(true);
    try {
      const monthlyData = await apiCall<any>(
        api.endpoints.getMonthlyAttendance.initiate({ userId, year: 2025 }),
      );
      setMonthlyAttendance(monthlyData.monthlyAttendance || []);
      calculateMonthlyStats(monthlyData.monthlyAttendance || []);
    } catch (error) {
      console.error('Error fetching attendance:', error);
      toast({
        title: 'Error',
        description: 'Failed to fetch attendance data',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  }, [userId, toast]);

  const calculateMonthlyStats = (monthlyData: MonthlyAttendanceRecord[]) => {
    if (monthlyData.length === 0) {
      setStats({
        totalDays: 0,
        presentDays: 0,
        absentDays: 0,
        attendancePercentage: 0,
        avgWorkingHours: 0,
        totalLateMinutes: 0,
      });
      return;
    }

    // Calculate totals from monthly data
    const totals = monthlyData.reduce((acc, record) => {
      acc.totalDays += record.expectedDays;
      acc.presentDays += record.presentDays;
      acc.absentDays += record.absentDays;
      acc.totalLateMinutes += record.totalLateMinutes;
      return acc;
    }, {
      totalDays: 0,
      presentDays: 0,
      absentDays: 0,
      totalLateMinutes: 0,
    });

    const attendancePercentage = totals.totalDays > 0 ? (totals.presentDays / totals.totalDays) * 100 : 0;
    const avgWorkingHours = totals.presentDays > 0 ? 8 : 0; // Assuming 8 hours per day

    setStats({
      totalDays: totals.totalDays,
      presentDays: totals.presentDays,
      absentDays: totals.absentDays,
      attendancePercentage,
      avgWorkingHours,
      totalLateMinutes: totals.totalLateMinutes,
    });
  };

  const handleFileImport = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    setImporting(true);
    try {
      const formData = new FormData();
      formData.append('file', file);

      const result = await apiCall<any>(
        api.endpoints.importMonthlyAttendance.initiate(formData),
      );
      
      toast({
        title: 'Import Successful',
        description: `Imported ${result.successful} records successfully. ${result.failed} failed.`,
      });

      // Refresh data
      fetchAttendance();
    } catch (error) {
      console.error('Error importing attendance:', error);
      toast({
        title: 'Import Failed',
        description: 'Failed to import attendance data',
        variant: 'destructive',
      });
    } finally {
      setImporting(false);
      // Reset file input
      event.target.value = '';
    }
  };

  const downloadTemplate = () => {
    const headers = ['Number', 'Full Name', 'Designation', 'Date', 'Expected Days', 'Present Days', 'Absent Days', 'In Late', 'Out Late', 'Late', 'Leave Amount', 'Department', 'Month'];
    const sampleData = [
      ['JP-6230', 'Muhammad Uzair', 'Associate Software Engineer', '', '127', '116', '2', '04:53', '163:48', '168:41', '9', 'Production - Web & Apps', 'Jul'],
      ['JP-6231', 'Muhammad Osama', 'Associate Software Engineer', '', '21', '18', '0', '00:00', '86:59', '86:59', '3', 'Production - Web & Apps', 'Jan'],
    ];

    const csvContent = [headers, ...sampleData]
      .map(row => row.map(cell => `"${cell}"`).join(','))
      .join('\n');

    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'monthly_attendance_template.csv';
    link.click();
    window.URL.revokeObjectURL(url);
  };

  useEffect(() => {
    fetchAttendance();
  }, [fetchAttendance]);

  return (
    <div className="space-y-6">
      {/* Header Controls */}
      <Card className="p-6">
        <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
          <div>
            <h3 className="text-lg font-semibold text-foreground">Monthly Attendance Overview</h3>
            <p className="text-sm text-muted-foreground">Track monthly attendance statistics for {userName}</p>
          </div>
          
          {!isRestrictedPosition() && (
            <div className="flex gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={downloadTemplate}
                className="flex items-center space-x-2"
              >
                <Download className="h-4 w-4" />
                <span>Download Template</span>
              </Button>
              
              <Label htmlFor="attendance-file" className="cursor-pointer">
                <Button
                  variant="outline"
                  size="sm"
                  disabled={importing}
                  className="flex items-center space-x-2"
                  asChild
                >
                  <span>
                    <Upload className="h-4 w-4" />
                    <span>{importing ? 'Importing...' : 'Import Monthly Data'}</span>
                  </span>
                </Button>
              </Label>
              <Input
                id="attendance-file"
                type="file"
                accept=".xlsx,.xls,.csv"
                onChange={handleFileImport}
                className="hidden"
              />
            </div>
          )}
        </div>
      </Card>

      {/* Statistics Cards */}
      {stats && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <Card className="p-4">
            <div className="flex items-center space-x-3">
              <div className="p-2 bg-green-100 rounded-lg">
                <Users className="h-5 w-5 text-green-600" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">Attendance Rate</p>
                <p className="text-2xl font-bold text-green-600">{stats.attendancePercentage.toFixed(1)}%</p>
              </div>
            </div>
          </Card>
          
          <Card className="p-4">
            <div className="flex items-center space-x-3">
              <div className="p-2 bg-primary/15 rounded-lg">
                <Users className="h-5 w-5 text-primary" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">Present Days</p>
                <p className="text-2xl font-bold text-primary">{stats.presentDays}</p>
                <p className="text-xs text-muted-foreground">of {stats.totalDays} expected days</p>
              </div>
            </div>
          </Card>
          
          <Card className="p-4">
            <div className="flex items-center space-x-3">
              <div className="p-2 bg-orange-100 rounded-lg">
                <Clock className="h-5 w-5 text-orange-600" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">Avg Working Hours</p>
                <p className="text-2xl font-bold text-orange-600">{stats.avgWorkingHours.toFixed(1)}h</p>
                <p className="text-xs text-muted-foreground">per working day</p>
              </div>
            </div>
          </Card>
          
          <Card className="p-4">
            <div className="flex items-center space-x-3">
              <div className="p-2 bg-red-100 rounded-lg">
                <TrendingUp className="h-5 w-5 text-red-600" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">Late Hours</p>
                <p className="text-2xl font-bold text-red-600">{Math.floor(stats.totalLateMinutes / 60)}h {stats.totalLateMinutes % 60}m</p>
                <p className="text-xs text-muted-foreground">total late time</p>
              </div>
            </div>
          </Card>
        </div>
      )}

      {/* Monthly Summary View */}
      <Card className="p-6">
        <div className="flex items-center space-x-3 mb-6">
          <BarChart3 className="h-5 w-5 text-muted-foreground" />
          <h4 className="text-lg font-semibold text-foreground">Monthly Attendance Summary</h4>
        </div>
        
        {loading ? (
          <AttendanceTableSkeleton />
        ) : monthlyAttendance.length === 0 ? (
          <div className="text-center py-8">
            <p className="text-muted-foreground">No monthly attendance records found.</p>
            <p className="text-sm text-muted-foreground mt-2">Import your CSV file to see monthly summaries.</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full table-auto">
              <thead>
                <tr className="border-b border-border">
                  <th className="text-left py-3 px-4 font-medium text-foreground/80">Employee ID</th>
                  <th className="text-left py-3 px-4 font-medium text-foreground/80">Month</th>
                  <th className="text-left py-3 px-4 font-medium text-foreground/80">Expected Days</th>
                  <th className="text-left py-3 px-4 font-medium text-foreground/80">Present Days</th>
                  <th className="text-left py-3 px-4 font-medium text-foreground/80">Absent Days</th>
                  <th className="text-left py-3 px-4 font-medium text-foreground/80">Attendance %</th>
                  <th className="text-left py-3 px-4 font-medium text-foreground/80">Late Time</th>
                  <th className="text-left py-3 px-4 font-medium text-foreground/80">Leave Days</th>
                </tr>
              </thead>
              <tbody>
                {monthlyAttendance.map(record => {
                  const attendanceRate = record.expectedDays > 0 ? (record.presentDays / record.expectedDays) * 100 : 0;
                  const lateHours = Math.floor(record.totalLateMinutes / 60);
                  const lateMinutes = record.totalLateMinutes % 60;
                  
                  return (
                    <tr key={record.id} className="border-b border-border hover:bg-muted/50">
                      <td className="py-3 px-4">
                        <div className="font-medium text-foreground">
                          {record.employeeNumber || 'N/A'}
                        </div>
                        {record.department && (
                          <div className="text-sm text-muted-foreground">{record.department}</div>
                        )}
                      </td>
                      <td className="py-3 px-4">
                        <div className="font-medium">
                          {format(new Date(record.year, record.month - 1), 'MMM yyyy')}
                        </div>
                        {record.designation && (
                          <div className="text-sm text-muted-foreground">{record.designation}</div>
                        )}
                      </td>
                      <td className="py-3 px-4 text-center">
                        <span className="font-medium">{record.expectedDays}</span>
                      </td>
                      <td className="py-3 px-4 text-center">
                        <span className="font-medium text-green-600">{record.presentDays}</span>
                      </td>
                      <td className="py-3 px-4 text-center">
                        <span className="font-medium text-red-600">{record.absentDays}</span>
                      </td>
                      <td className="py-3 px-4 text-center">
                        <Badge
                          variant="outline"
                          className={`${
                            attendanceRate >= 95 ? 'bg-green-100 text-green-800 border-green-200' :
                            attendanceRate >= 85 ? 'bg-primary/15 text-primary border-primary/20' :
                            attendanceRate >= 75 ? 'bg-yellow-100 text-yellow-800 border-yellow-200' :
                            'bg-red-100 text-red-800 border-red-200'
                          }`}
                        >
                          {attendanceRate.toFixed(1)}%
                        </Badge>
                      </td>
                      <td className="py-3 px-4 text-center">
                        {record.totalLateMinutes > 0 ? (
                          <span className="text-orange-600 font-medium">
                            {lateHours > 0 ? `${lateHours}h ` : ''}{lateMinutes}m
                          </span>
                        ) : (
                          <span className="text-muted-foreground">-</span>
                        )}
                      </td>
                      <td className="py-3 px-4 text-center">
                        <span className="font-medium">{record.leaveAmount}</span>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </Card>
    </div>
  );
} 