'use client';

import { useState, useEffect, useCallback, useMemo } from 'react';
import { useSession } from 'next-auth/react';
import { motion } from 'motion/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 { TablePagination } from '@/components/ui/table-pagination';
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 { staggerContainer, staggerItem } from '@/lib/motion';
import { api } from '@/lib/store/api';
import { apiCall } from '@/lib/store/api-call';

const PAGE_SIZE = 10;

function getAttendanceBadgeClass(rate: number) {
  if (rate >= 95) return 'bg-green-100 dark:bg-green-950/50 text-green-800 dark:text-green-300 border-green-200 dark:border-green-800';
  if (rate >= 85) return 'bg-primary/15 text-primary border-primary/20';
  if (rate >= 75) return 'bg-yellow-100 dark:bg-yellow-950/50 text-yellow-800 dark:text-yellow-300 border-yellow-200 dark:border-yellow-800';
  return 'bg-red-100 dark:bg-red-950/50 text-red-800 dark:text-red-300 border-red-200 dark:border-red-800';
}

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;
  isItUser?: boolean;
  dateFrom?: string;
  dateTo?: string;
}

export function UserAttendance({ userId, userName, isItUser = false, dateFrom, dateTo }: 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 [currentPage, setCurrentPage] = useState(1);
  const { toast } = useToast();

  const sortedAttendance = useMemo(
    () =>
      [...monthlyAttendance].sort((a, b) =>
        a.year !== b.year ? a.year - b.year : a.month - b.month
      ),
    [monthlyAttendance]
  );

  const paginatedAttendance = useMemo(
    () => sortedAttendance.slice((currentPage - 1) * PAGE_SIZE, currentPage * PAGE_SIZE),
    [sortedAttendance, currentPage]
  );

  useEffect(() => {
    setCurrentPage(1);
  }, [monthlyAttendance]);

  const fetchAttendance = useCallback(async () => {
    setLoading(true);
    let hasError = false;
    try {
      const fromDate = dateFrom ? new Date(dateFrom) : null;
      const toDate = dateTo ? new Date(dateTo) : null;
      const fromYear = fromDate ? fromDate.getFullYear() : new Date().getFullYear();
      const fromMonth = fromDate ? fromDate.getMonth() + 1 : 1;
      const toYear = toDate ? toDate.getFullYear() : new Date().getFullYear();
      const toMonth = toDate ? toDate.getMonth() + 1 : 12;

      // Determine unique years we need to fetch
      const yearsToFetch: number[] = [];
      for (let y = fromYear; y <= toYear; y++) yearsToFetch.push(y);

      const yearResults = await Promise.all(
        yearsToFetch.map((y) =>
          apiCall<any>(
            api.endpoints.getMonthlyAttendance.initiate({ userId, year: y }),
          ),
        ),
      );

      let allRecords: MonthlyAttendanceRecord[] = [];
      for (const d of yearResults) {
        allRecords = allRecords.concat(d.monthlyAttendance || []);
      }

      // Filter by the month range
      const filtered = allRecords.filter((r: MonthlyAttendanceRecord) => {
        const val = r.year * 100 + r.month;
        return val >= fromYear * 100 + fromMonth && val <= toYear * 100 + toMonth;
      }).sort((a, b) => a.year !== b.year ? a.year - b.year : a.month - b.month);

      setMonthlyAttendance(filtered);
      calculateMonthlyStats(filtered);
    } catch (error) {
      console.error('Error fetching attendance:', error);
      hasError = true;
    } finally {
      setLoading(false);
      // Show toast after state update is complete
      if (hasError) {
        setTimeout(() => {
          toast({
            title: 'Error',
            description: 'Failed to fetch attendance data',
            variant: 'destructive',
          });
        }, 0);
      }
    }
  }, [userId, isItUser, dateFrom, dateTo]);

  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', 'UserID', 'Full Name', 'Designation', 'Month', 'Expected Days', 'Present Days', 'Absent Days', 'In Late', 'Out Late', 'Late', 'Leave Amount', 'Department'];
    const sampleData = [
      ['JP-6230', 'cmcjl1wcy001l2o0j6bi16kj7', 'Shayan Ahmed', 'Associate Software Engineer', 'January 2025', '21', '18', '0', '00:00', '86:59', '86:59', '3', 'Production - Web & Apps'],
      ['JP-6233', 'cmcnjjoif00021298hey5q6sc', 'Muhammad Usman Siddiqui', 'Associate Software Engineer', 'January 2025', '21', '21', '0', '00:00', '103:06', '103:06', '0', 'Production - Web & Apps'],
      ['JP-6245', 'cmcnjjr8t00051298hxuka72s', 'Muhammad Almas Saleem', 'Associate Software Engineer', 'January 2025', '21', '18', '0', '00:09', '00:01', '00:10', '3', 'Production - Web & Apps'],
      ['JP-6246', 'cmcnjjulc00081298ircppxj5', 'Muhammad Arqam Khursheed', 'Associate Software Engineer', 'January 2025', '21', '21', '0', '00:00', '86:40', '86:40', '0', 'Production - Web & Apps'],
      ['JP-6389', 'cmcjl577v001r2o0jl3lk5gk3', 'Pankaj Kumar', 'Software Engineer Level 1', 'January 2025', '21', '20', '0', '00:56', '00:00', '00:56', '1', 'Production - Web & Apps'],
    ];

    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(() => {
    console.log('🔄 UserAttendance: Fetching data for user:', userId);
    fetchAttendance();
  }, [fetchAttendance]);

  return (
    <motion.div
      className="space-y-6"
      variants={staggerContainer}
      initial="initial"
      animate="animate"
    >
      {/* Monthly Attendance Overview - HIDDEN */}
      {false && (
        <>
          {/* 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-2 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>
                  </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 Minutes</p>
                    <p className="text-2xl font-bold text-red-600">{stats?.totalLateMinutes}</p>
                    <p className="text-xs text-muted-foreground">total this month</p>
                  </div>
                </div>
              </Card>
            </div>
          )}
        </>
      )}

      {/* Monthly Summary View */}
      <motion.div variants={staggerItem}>
        <Card className="rounded-xl border border-border bg-card overflow-hidden">
          <div className="flex items-center gap-3 px-6 py-5 border-b border-border">
            <div className="p-2 rounded-lg bg-muted/50">
              <BarChart3 className="h-5 w-5 text-muted-foreground" />
            </div>
            <div>
              <h4 className="text-lg font-semibold text-foreground">Monthly Attendance Summary</h4>
              <p className="text-sm text-muted-foreground">Monthly records for {userName}</p>
            </div>
          </div>

          {loading ? (
            <div className="p-6">
              <AttendanceTableSkeleton />
            </div>
          ) : monthlyAttendance.length === 0 ? (
            <div className="text-center py-12 px-6">
              <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 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">Employee ID</th>
                      <th className="text-left py-3 px-4 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Month</th>
                      <th className="text-center py-3 px-4 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Expected Days</th>
                      <th className="text-center py-3 px-4 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Present Days</th>
                      <th className="text-center py-3 px-4 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Absent Days</th>
                      <th className="text-center py-3 px-4 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Attendance %</th>
                      <th className="text-center py-3 px-4 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Leave Occupied</th>
                    </tr>
                  </thead>
                  <tbody>
                    {paginatedAttendance.map(record => {
                      const attendanceRate = record.expectedDays > 0 ? (record.presentDays / record.expectedDays) * 100 : 0;
                      return (
                        <tr key={record.id} className="border-b border-border transition-colors 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 text-foreground">
                              {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 text-foreground">{record.expectedDays}</span>
                          </td>
                          <td className="py-3 px-4 text-center">
                            <span className="font-medium text-green-600 dark:text-green-400">{record.presentDays}</span>
                          </td>
                          <td className="py-3 px-4 text-center">
                            <span className="font-medium text-red-600 dark:text-red-400">{record.absentDays}</span>
                          </td>
                          <td className="py-3 px-4 text-center">
                            <Badge
                              variant="outline"
                              className={getAttendanceBadgeClass(attendanceRate)}
                            >
                              {attendanceRate.toFixed(1)}%
                            </Badge>
                          </td>
                          <td className="py-3 px-4 text-center">
                            <span className="font-medium text-foreground">{record.leaveAmount}</span>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
              <TablePagination
                currentPage={currentPage}
                totalItems={sortedAttendance.length}
                pageSize={PAGE_SIZE}
                onPageChange={setCurrentPage}
                itemLabel="records"
              />
            </>
          )}
        </Card>
      </motion.div>
    </motion.div>
  );
} 