'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 { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { useToast } from '@/hooks/use-toast';

type CorrectionRequest = {
  id: string;
  record_id: string;
  employee_id: string;
  reason: string;
  requested_record_type: string | null;
  requested_check_in_time: string | null;
  requested_check_out_time: string | null;
  status: 'pending' | 'approved' | 'rejected';
  review_reason: string | null;
  created_at: string;
  attendance_date?: string | null;
  attendance_record_type?: string | null;
};

type SortMode = 'sla' | 'newest' | 'oldest';

export default function AttendanceCorrectionsManager() {
  const [items, setItems] = useState<CorrectionRequest[]>([]);
  const [loading, setLoading] = useState(false);
  const [status, setStatus] = useState('pending');
  const [query, setQuery] = useState('');
  const [sortMode, setSortMode] = useState<SortMode>('sla');
  const [reviewReasonById, setReviewReasonById] = useState<Record<string, string>>({});
  const { toast } = useToast();

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

  const fetchRequests = async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams({ page: '1', pageSize: '200', ...(status ? { status } : {}) });
      const res = await fetch(`/api/hr/attendance/corrections?${params.toString()}`);
      const payload = await res.json();
      if (!res.ok) {
        throw new Error(payload?.error || 'Failed to load correction requests');
      }
      setItems(payload.items || []);
    } catch (error) {
      toast({
        title: 'خطأ',
        description: error instanceof Error ? error.message : 'تعذر تحميل الطلبات',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const filtered = items.filter((item) => {
    const q = query.trim().toLowerCase();
    if (!q) return true;
    return (
      String(item.employee_id || '').toLowerCase().includes(q) ||
      String(item.record_id || '').toLowerCase().includes(q) ||
      String(item.reason || '').toLowerCase().includes(q)
    );
  });

  const sortedFiltered = useMemo(() => {
    if (sortMode === 'newest') {
      return [...filtered].sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
    }

    if (sortMode === 'oldest') {
      return [...filtered].sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
    }

    const levelPriority: Record<string, number> = {
      critical: 0,
      warning: 1,
      normal: 2,
      none: 3,
    };

    return [...filtered].sort((a, b) => {
      const slaA = getSlaInfo(a);
      const slaB = getSlaInfo(b);

      const priorityA = levelPriority[slaA.level] ?? 99;
      const priorityB = levelPriority[slaB.level] ?? 99;
      if (priorityA !== priorityB) {
        return priorityA - priorityB;
      }

      const createdA = new Date(a.created_at).getTime();
      const createdB = new Date(b.created_at).getTime();

      // For pending items, prioritize older requests first.
      if (a.status === 'pending' && b.status === 'pending') {
        return createdA - createdB;
      }

      // For non-pending items, show newest first.
      return createdB - createdA;
    });
  }, [filtered, sortMode]);

  const sortHint =
    sortMode === 'sla'
      ? 'الطلبات مرتبة حسب SLA: حرج ثم تحذير ثم عادي'
      : sortMode === 'newest'
        ? 'الطلبات مرتبة حسب تاريخ الإنشاء: الأحدث أولًا'
        : 'الطلبات مرتبة حسب تاريخ الإنشاء: الأقدم أولًا';

  const statusSummary = items.reduce(
    (acc, item) => {
      if (item.status === 'pending') acc.pending += 1;
      if (item.status === 'approved') acc.approved += 1;
      if (item.status === 'rejected') acc.rejected += 1;
      return acc;
    },
    { pending: 0, approved: 0, rejected: 0 }
  );

  const getSlaInfo = (item: CorrectionRequest) => {
    if (item.status !== 'pending') {
      return { label: '-', level: 'none' as const };
    }

    const createdAtMs = new Date(item.created_at).getTime();
    const nowMs = Date.now();
    const hours = Math.max(0, Math.floor((nowMs - createdAtMs) / (1000 * 60 * 60)));

    if (hours >= 48) {
      return { label: `${hours}h (حرج)`, level: 'critical' as const };
    }
    if (hours >= 24) {
      return { label: `${hours}h (تحذير)`, level: 'warning' as const };
    }
    return { label: `${hours}h`, level: 'normal' as const };
  };

  const handleAction = async (id: string, action: 'approve' | 'reject') => {
    try {
      const res = await fetch(`/api/hr/attendance/corrections/${id}/${action}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ reviewReason: reviewReasonById[id] || undefined }),
      });
      const payload = await res.json();
      if (!res.ok) {
        throw new Error(payload?.error || `Failed to ${action}`);
      }
      toast({
        title: 'تم',
        description: action === 'approve' ? 'تمت الموافقة على طلب التصحيح' : 'تم رفض طلب التصحيح',
      });
      await fetchRequests();
    } catch (error) {
      toast({
        title: 'خطأ',
        description: error instanceof Error ? error.message : 'فشل تنفيذ الإجراء',
        variant: 'destructive',
      });
    }
  };

  const statusBadge = (value: string) => {
    if (value === 'approved') return 'bg-green-100 text-green-800';
    if (value === 'rejected') return 'bg-red-100 text-red-800';
    return 'bg-yellow-100 text-yellow-800';
  };

  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>
        </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>
              <select
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                value={status}
                onChange={(e) => setStatus(e.target.value)}
              >
                <option value="">الكل</option>
                <option value="pending">قيد الانتظار</option>
                <option value="approved">موافق عليه</option>
                <option value="rejected">مرفوض</option>
              </select>
            </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">الترتيب</label>
              <select
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                value={sortMode}
                onChange={(e) => setSortMode(e.target.value as SortMode)}
              >
                <option value="sla">حسب SLA</option>
                <option value="newest">الأحدث أولًا</option>
                <option value="oldest">الأقدم أولًا</option>
              </select>
            </div>
            <div className="space-y-1">
              <label className="text-xs text-muted-foreground">&nbsp;</label>
              <Button onClick={() => void fetchRequests()} className="w-full">تحديث</Button>
            </div>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>القائمة</CardTitle>
          <p className="text-xs text-muted-foreground">{sortHint}</p>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3 mb-4 text-sm">
            <div className="rounded-md border p-3">
              <div className="text-muted-foreground">قيد الانتظار</div>
              <div className="text-xl font-bold text-yellow-700">{statusSummary.pending}</div>
            </div>
            <div className="rounded-md border p-3">
              <div className="text-muted-foreground">موافق عليه</div>
              <div className="text-xl font-bold text-green-700">{statusSummary.approved}</div>
            </div>
            <div className="rounded-md border p-3">
              <div className="text-muted-foreground">مرفوض</div>
              <div className="text-xl font-bold text-red-700">{statusSummary.rejected}</div>
            </div>
          </div>

          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>الموظف</TableHead>
                  <TableHead>تاريخ السجل</TableHead>
                  <TableHead>الحالة الحالية</TableHead>
                  <TableHead>المطلوب</TableHead>
                  <TableHead>السبب</TableHead>
                  <TableHead>الحالة</TableHead>
                  <TableHead>SLA</TableHead>
                  <TableHead>ملاحظة المراجعة</TableHead>
                  <TableHead>إجراءات</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading ? (
                  <TableRow>
                    <TableCell colSpan={9} className="text-center py-8 text-muted-foreground">
                      جاري التحميل...
                    </TableCell>
                  </TableRow>
                ) : sortedFiltered.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={9} className="text-center py-8 text-muted-foreground">
                      لا توجد طلبات
                    </TableCell>
                  </TableRow>
                ) : (
                  sortedFiltered.map((item) => {
                    const sla = getSlaInfo(item);
                    return (
                      <TableRow
                        key={item.id}
                        className={
                          sla.level === 'critical'
                            ? 'bg-red-50/70'
                            : sla.level === 'warning'
                              ? 'bg-amber-50/70'
                              : undefined
                        }
                      >
                        <TableCell>{item.employee_id}</TableCell>
                        <TableCell>{item.attendance_date || '-'}</TableCell>
                        <TableCell>{item.attendance_record_type || '-'}</TableCell>
                        <TableCell>
                          <div className="text-xs space-y-1">
                            <div>النوع: {item.requested_record_type || '-'}</div>
                            <div>دخول: {item.requested_check_in_time ? new Date(item.requested_check_in_time).toLocaleTimeString() : '-'}</div>
                            <div>خروج: {item.requested_check_out_time ? new Date(item.requested_check_out_time).toLocaleTimeString() : '-'}</div>
                          </div>
                        </TableCell>
                        <TableCell className="max-w-xs whitespace-pre-wrap">{item.reason}</TableCell>
                        <TableCell>
                          <Badge className={statusBadge(item.status)}>
                            {item.status === 'pending' ? 'قيد الانتظار' : item.status === 'approved' ? 'موافق' : 'مرفوض'}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <Badge
                            variant="outline"
                            className={
                              sla.level === 'critical'
                                ? 'border-red-300 text-red-700'
                                : sla.level === 'warning'
                                  ? 'border-amber-300 text-amber-700'
                                  : ''
                            }
                          >
                            {sla.label}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          {item.status === 'pending' ? (
                            <Textarea
                              value={reviewReasonById[item.id] || ''}
                              onChange={(e) => setReviewReasonById((prev) => ({ ...prev, [item.id]: e.target.value }))}
                              placeholder="سبب القرار (اختياري)"
                              className="min-h-[70px]"
                            />
                          ) : (
                            <span className="text-xs text-muted-foreground">{item.review_reason || '-'}</span>
                          )}
                        </TableCell>
                        <TableCell>
                          {item.status === 'pending' ? (
                            <div className="flex gap-2">
                              <Button size="sm" onClick={() => void handleAction(item.id, 'approve')}>
                                موافقة
                              </Button>
                              <Button size="sm" variant="destructive" onClick={() => void handleAction(item.id, 'reject')}>
                                رفض
                              </Button>
                            </div>
                          ) : (
                            <span className="text-xs text-muted-foreground">-</span>
                          )}
                        </TableCell>
                      </TableRow>
                    );
                  })
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
