'use client';

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

type AttendanceRecord = {
  id: string;
  employee_id: string;
  date: string;
  record_type: string;
  check_in_time: string | null;
  check_out_time: string | null;
  duration_hours: number | null;
  late_minutes: number;
  device: string;
  status: string;
  created_at: string;
};

export default function AttendanceManager() {
  const [records, setRecords] = useState<AttendanceRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [fromDate, setFromDate] = useState(format(subDays(new Date(), 30), 'yyyy-MM-dd'));
  const [toDate, setToDate] = useState(format(new Date(), 'yyyy-MM-dd'));
  const [recordType, setRecordType] = useState('');
  const [status, setStatus] = useState('');
  const { toast } = useToast();

  useEffect(() => {
    fetchRecords();
  }, [page, fromDate, toDate, recordType, status]);

  const fetchRecords = async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        page: String(page),
        pageSize: '50',
        fromDate,
        toDate,
        ...(recordType && { recordType }),
        ...(status && { status }),
      });

      const res = await fetch(`/api/hr/attendance/records?${params}`);
      if (!res.ok) throw new Error('Failed to fetch records');

      const data = await res.json();
      setRecords(data.items || []);
    } catch (error) {
      console.error('Error:', error);
      toast({ title: 'خطأ', description: 'فشل تحميل السجلات', variant: 'destructive' });
    } finally {
      setLoading(false);
    }
  };

  const handleApprove = async (recordId: string) => {
    try {
      const res = await fetch(`/api/hr/attendance/records/${recordId}/approve`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ reason: 'Approved by HR' }),
      });

      if (!res.ok) throw new Error('Failed to approve');
      toast({ title: 'نجح', description: 'تمت الموافقة على السجل' });
      fetchRecords();
    } catch (error) {
      toast({ title: 'خطأ', description: 'فشل الموافقة', variant: 'destructive' });
    }
  };

  const handleReject = async (recordId: string) => {
    try {
      const res = await fetch(`/api/hr/attendance/records/${recordId}/reject`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ reason: 'Rejected by HR' }),
      });

      if (!res.ok) throw new Error('Failed to reject');
      toast({ title: 'نجح', description: 'تم رفض السجل' });
      fetchRecords();
    } catch (error) {
      toast({ title: 'خطأ', description: 'فشل الرفض', variant: 'destructive' });
    }
  };

  const recordTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      present: '✓ حاضر',
      absent: '✗ غائب',
      late: '⏰ متأخر',
      sick: '🏥 مرضي',
      leave: '📅 إجازة',
    };
    return labels[type] || type;
  };

  const statusBadge = (status: string) => {
    const colors: Record<string, string> = {
      pending: 'bg-yellow-100 text-yellow-800',
      approved: 'bg-green-100 text-green-800',
      rejected: 'bg-red-100 text-red-800',
    };
    return colors[status] || 'bg-gray-100 text-gray-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">
          <div className="flex gap-2">
            <Button asChild variant="outline" size="sm">
              <Link href="/admin/hr/biometric-devices">إدارة أجهزة البصمة</Link>
            </Button>
            <Button asChild variant="outline" size="sm">
              <Link href="/admin/hr/attendance/reports">تقارير الحضور</Link>
            </Button>
            <Button asChild variant="outline" size="sm">
              <Link href="/admin/hr/attendance/corrections">طلبات التصحيح</Link>
            </Button>
          </div>
        </div>
      </div>

      {/* Filters */}
      <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="date"
                value={fromDate}
                onChange={(e) => { setFromDate(e.target.value); setPage(1); }}
              />
            </div>
            <div className="space-y-1">
              <label className="text-xs text-muted-foreground">إلى تاريخ</label>
              <Input
                type="date"
                value={toDate}
                onChange={(e) => { setToDate(e.target.value); setPage(1); }}
              />
            </div>
            <div className="space-y-1">
              <label className="text-xs text-muted-foreground">النوع</label>
              <select
                value={recordType}
                onChange={(e) => { setRecordType(e.target.value); setPage(1); }}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
              >
                <option value="">الكل</option>
                <option value="present">حاضر</option>
                <option value="absent">غائب</option>
                <option value="late">متأخر</option>
                <option value="sick">مرضي</option>
                <option value="leave">إجازة</option>
              </select>
            </div>
            <div className="space-y-1">
              <label className="text-xs text-muted-foreground">الحالة</label>
              <select
                value={status}
                onChange={(e) => { setStatus(e.target.value); setPage(1); }}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
              >
                <option value="">الكل</option>
                <option value="pending">قيد الانتظار</option>
                <option value="approved">موافق عليه</option>
                <option value="rejected">مرفوض</option>
              </select>
            </div>
            <div className="space-y-1">
              <label className="text-xs text-muted-foreground">&nbsp;</label>
              <Button onClick={() => fetchRecords()} className="w-full">
                تحديث
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Records Table */}
      <Card>
        <CardHeader>
          <CardTitle>سجلات الحضور</CardTitle>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="text-center py-8">جاري التحميل...</div>
          ) : (
            <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>
                  {records.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={8} className="text-center py-8">
                        لا توجد سجلات
                      </TableCell>
                    </TableRow>
                  ) : (
                    records.map((record) => (
                      <TableRow key={record.id}>
                        <TableCell>{record.date}</TableCell>
                        <TableCell>{recordTypeLabel(record.record_type)}</TableCell>
                        <TableCell>
                          {record.check_in_time ? format(new Date(record.check_in_time), 'HH:mm:ss') : '-'}
                        </TableCell>
                        <TableCell>
                          {record.check_out_time ? format(new Date(record.check_out_time), 'HH:mm:ss') : '-'}
                        </TableCell>
                        <TableCell>
                          {record.duration_hours ? `${record.duration_hours.toFixed(1)} س` : '-'}
                        </TableCell>
                        <TableCell>
                          <Badge variant="outline">{record.device}</Badge>
                        </TableCell>
                        <TableCell>
                          <Badge className={statusBadge(record.status)}>
                            {record.status === 'pending' ? 'قيد الانتظار' : record.status === 'approved' ? 'موافق' : 'مرفوض'}
                          </Badge>
                        </TableCell>
                        <TableCell className="space-x-2">
                          {record.status === 'pending' && (
                            <>
                              <Button
                                onClick={() => handleApprove(record.id)}
                                size="sm"
                                variant="outline"
                                className="text-green-600 hover:text-green-700"
                              >
                                ✓
                              </Button>
                              <Button
                                onClick={() => handleReject(record.id)}
                                size="sm"
                                variant="outline"
                                className="text-red-600 hover:text-red-700"
                              >
                                ✗
                              </Button>
                            </>
                          )}
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
