'use client';

import { useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { useToast } from '@/hooks/use-toast';

type ReportItem = {
  employeeId: string;
  employeeName: string;
  presentDays: number;
  absentDays: number;
  lateCount: number;
  sickDays: number;
  leaveDays: number;
  totalHours: number;
};

type Totals = {
  presentDays: number;
  absentDays: number;
  lateCount: number;
  sickDays: number;
  leaveDays: number;
  totalHours: number;
};

export default function AttendanceReportsManager() {
  const now = new Date();
  const [month, setMonth] = useState(String(now.getMonth() + 1));
  const [year, setYear] = useState(String(now.getFullYear()));
  const [query, setQuery] = useState('');
  const [loading, setLoading] = useState(false);
  const [items, setItems] = useState<ReportItem[]>([]);
  const [totals, setTotals] = useState<Totals>({
    presentDays: 0,
    absentDays: 0,
    lateCount: 0,
    sickDays: 0,
    leaveDays: 0,
    totalHours: 0,
  });
  const { toast } = useToast();

  useEffect(() => {
    void fetchReport();
  }, []);

  const fetchReport = async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        month,
        year,
      });

      const res = await fetch(`/api/hr/attendance/reports/monthly?${params.toString()}`);
      const payload = await res.json();

      if (!res.ok) {
        throw new Error(payload?.error || 'Failed to load report');
      }

      setItems(payload.items || []);
      setTotals(
        payload.totals || {
          presentDays: 0,
          absentDays: 0,
          lateCount: 0,
          sickDays: 0,
          leaveDays: 0,
          totalHours: 0,
        }
      );
    } catch (error) {
      toast({
        title: 'خطأ',
        description: error instanceof Error ? error.message : 'تعذر تحميل التقرير',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const filteredItems = useMemo(() => {
    const normalized = query.trim().toLowerCase();
    if (!normalized) return items;

    return items.filter((item) => {
      return (
        String(item.employeeName || '').toLowerCase().includes(normalized) ||
        String(item.employeeId || '').toLowerCase().includes(normalized)
      );
    });
  }, [items, query]);

  const exportCsv = () => {
    const headers = [
      'Employee ID',
      'Employee Name',
      'Present Days',
      'Absent Days',
      'Late Count',
      'Sick Days',
      'Leave Days',
      'Total Hours',
    ];

    const rows = filteredItems.map((item) => [
      item.employeeId,
      item.employeeName,
      String(item.presentDays),
      String(item.absentDays),
      String(item.lateCount),
      String(item.sickDays),
      String(item.leaveDays),
      String(item.totalHours),
    ]);

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

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `attendance-report-${year}-${month.padStart(2, '0')}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold">تقارير الحضور الشهرية</h1>
        <p className="text-muted-foreground mt-1">ملخص أيام الحضور والغياب والتأخير لكل موظف</p>
        <div className="mt-3 flex gap-2">
          <Button asChild variant="outline" size="sm">
            <Link href="/admin/hr/attendance">العودة لإدارة الحضور</Link>
          </Button>
          <Button asChild variant="outline" size="sm">
            <Link href="/admin/hr/biometric-devices">إدارة أجهزة البصمة</Link>
          </Button>
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>فلاتر التقرير</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-5 gap-3">
            <div className="space-y-1">
              <label className="text-xs text-muted-foreground">الشهر</label>
              <Input
                type="number"
                min={1}
                max={12}
                value={month}
                onChange={(e) => setMonth(e.target.value)}
              />
            </div>
            <div className="space-y-1">
              <label className="text-xs text-muted-foreground">السنة</label>
              <Input
                type="number"
                min={2000}
                max={2100}
                value={year}
                onChange={(e) => setYear(e.target.value)}
              />
            </div>
            <div className="space-y-1 md:col-span-2">
              <label className="text-xs text-muted-foreground">بحث</label>
              <Input
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder="بحث بالاسم أو رقم الموظف"
              />
            </div>
            <div className="space-y-1">
              <label className="text-xs text-muted-foreground">&nbsp;</label>
              <div className="flex gap-2">
                <Button onClick={() => void fetchReport()} disabled={loading} className="w-full">
                  {loading ? 'جاري التحميل...' : 'تحديث'}
                </Button>
                <Button variant="outline" onClick={exportCsv} disabled={filteredItems.length === 0}>
                  CSV
                </Button>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>ملخص إجمالي</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-6 gap-3 text-sm">
            <div className="rounded-md border p-3">
              <div className="text-muted-foreground">حضور</div>
              <div className="text-xl font-bold">{totals.presentDays}</div>
            </div>
            <div className="rounded-md border p-3">
              <div className="text-muted-foreground">غياب</div>
              <div className="text-xl font-bold">{totals.absentDays}</div>
            </div>
            <div className="rounded-md border p-3">
              <div className="text-muted-foreground">تأخير</div>
              <div className="text-xl font-bold">{totals.lateCount}</div>
            </div>
            <div className="rounded-md border p-3">
              <div className="text-muted-foreground">مرضي</div>
              <div className="text-xl font-bold">{totals.sickDays}</div>
            </div>
            <div className="rounded-md border p-3">
              <div className="text-muted-foreground">إجازات</div>
              <div className="text-xl font-bold">{totals.leaveDays}</div>
            </div>
            <div className="rounded-md border p-3">
              <div className="text-muted-foreground">ساعات العمل</div>
              <div className="text-xl font-bold">{totals.totalHours.toFixed(2)}</div>
            </div>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>تفصيل الموظفين</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>الموظف</TableHead>
                  <TableHead>معرف الموظف</TableHead>
                  <TableHead>حضور</TableHead>
                  <TableHead>غياب</TableHead>
                  <TableHead>تأخير</TableHead>
                  <TableHead>مرضي</TableHead>
                  <TableHead>إجازات</TableHead>
                  <TableHead>ساعات العمل</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading ? (
                  <TableRow>
                    <TableCell colSpan={8} className="text-center py-8 text-muted-foreground">
                      جاري التحميل...
                    </TableCell>
                  </TableRow>
                ) : filteredItems.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={8} className="text-center py-8 text-muted-foreground">
                      لا توجد بيانات
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredItems.map((item) => (
                    <TableRow key={item.employeeId}>
                      <TableCell>{item.employeeName}</TableCell>
                      <TableCell>{item.employeeId}</TableCell>
                      <TableCell>{item.presentDays}</TableCell>
                      <TableCell>{item.absentDays}</TableCell>
                      <TableCell>{item.lateCount}</TableCell>
                      <TableCell>{item.sickDays}</TableCell>
                      <TableCell>{item.leaveDays}</TableCell>
                      <TableCell>{item.totalHours.toFixed(2)}</TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
