'use client';

import { useEffect, useState } from 'react';
import { format } from 'date-fns';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Textarea } from '@/components/ui/textarea';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { useToast } from '@/hooks/use-toast';

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

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

type CorrectionRequest = {
  id: string;
  record_id: string;
  reason: string;
  status: 'pending' | 'approved' | 'rejected';
  review_reason: string | null;
  created_at: string;
};

export default function AttendanceHistoryManager() {
  const now = new Date();
  const [month, setMonth] = useState(String(now.getMonth() + 1));
  const [year, setYear] = useState(String(now.getFullYear()));
  const [loading, setLoading] = useState(false);
  const [items, setItems] = useState<AttendanceRecord[]>([]);
  const [summary, setSummary] = useState<Summary>({
    presentDays: 0,
    absentDays: 0,
    lateCount: 0,
    sickDays: 0,
    leaveDays: 0,
    totalHours: 0,
  });
  const [corrections, setCorrections] = useState<CorrectionRequest[]>([]);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [selectedRecord, setSelectedRecord] = useState<AttendanceRecord | null>(null);
  const [reason, setReason] = useState('');
  const [requestedRecordType, setRequestedRecordType] = useState('');
  const [requestedCheckInTime, setRequestedCheckInTime] = useState('');
  const [requestedCheckOutTime, setRequestedCheckOutTime] = useState('');
  const [submittingCorrection, setSubmittingCorrection] = useState(false);
  const { toast } = useToast();

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

  const fetchData = async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams({ month, year });
      const res = await fetch(`/api/employee/attendance/history?${params.toString()}`);
      const payload = await res.json();

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

      setItems(payload.items || []);
      setSummary(
        payload.summary || {
          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 fetchCorrections = async () => {
    try {
      const res = await fetch('/api/employee/attendance/corrections?page=1&pageSize=100');
      const payload = await res.json();
      if (!res.ok) {
        throw new Error(payload?.error || 'Failed to load corrections');
      }
      setCorrections(payload.items || []);
    } catch (error) {
      toast({
        title: 'خطأ',
        description: error instanceof Error ? error.message : 'تعذر تحميل طلبات التصحيح',
        variant: 'destructive',
      });
    }
  };

  const toLocalInputValue = (iso: string | null) => {
    if (!iso) return '';
    const date = new Date(iso);
    const pad = (n: number) => String(n).padStart(2, '0');
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
  };

  const openCorrectionDialog = (record: AttendanceRecord) => {
    setSelectedRecord(record);
    setReason('');
    setRequestedRecordType(record.record_type || '');
    setRequestedCheckInTime(toLocalInputValue(record.check_in_time));
    setRequestedCheckOutTime(toLocalInputValue(record.check_out_time));
    setDialogOpen(true);
  };

  const submitCorrection = async () => {
    if (!selectedRecord) return;
    if (!reason.trim()) {
      toast({ title: 'تنبيه', description: 'يرجى كتابة سبب طلب التصحيح', variant: 'destructive' });
      return;
    }

    try {
      setSubmittingCorrection(true);
      const res = await fetch('/api/employee/attendance/corrections', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          recordId: selectedRecord.id,
          reason,
          requestedRecordType: requestedRecordType || undefined,
          requestedCheckInTime: requestedCheckInTime ? new Date(requestedCheckInTime).toISOString() : undefined,
          requestedCheckOutTime: requestedCheckOutTime ? new Date(requestedCheckOutTime).toISOString() : undefined,
        }),
      });

      const payload = await res.json();
      if (!res.ok) {
        throw new Error(payload?.error || 'Failed to create correction request');
      }

      toast({ title: 'تم', description: 'تم إرسال طلب التصحيح بنجاح' });
      setDialogOpen(false);
      await fetchCorrections();
    } catch (error) {
      toast({
        title: 'خطأ',
        description: error instanceof Error ? error.message : 'تعذر إرسال الطلب',
        variant: 'destructive',
      });
    } finally {
      setSubmittingCorrection(false);
    }
  };

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

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold">سجل حضوري</h1>
        <p className="text-muted-foreground mt-1">عرض تفاصيل حضوري وغيابي لكل شهر</p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>اختيار الشهر</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-4 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">&nbsp;</label>
              <Button onClick={() => void fetchData()} disabled={loading} className="w-full md:w-auto">
                {loading ? 'جاري التحميل...' : 'تحديث'}
              </Button>
            </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">{summary.presentDays}</div>
            </div>
            <div className="rounded-md border p-3">
              <div className="text-muted-foreground">غياب</div>
              <div className="text-xl font-bold">{summary.absentDays}</div>
            </div>
            <div className="rounded-md border p-3">
              <div className="text-muted-foreground">تأخير</div>
              <div className="text-xl font-bold">{summary.lateCount}</div>
            </div>
            <div className="rounded-md border p-3">
              <div className="text-muted-foreground">مرضي</div>
              <div className="text-xl font-bold">{summary.sickDays}</div>
            </div>
            <div className="rounded-md border p-3">
              <div className="text-muted-foreground">إجازات</div>
              <div className="text-xl font-bold">{summary.leaveDays}</div>
            </div>
            <div className="rounded-md border p-3">
              <div className="text-muted-foreground">ساعات العمل</div>
              <div className="text-xl font-bold">{summary.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>
                ) : items.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={8} className="text-center py-8 text-muted-foreground">
                      لا توجد بيانات لهذا الشهر
                    </TableCell>
                  </TableRow>
                ) : (
                  items.map((item) => (
                    <TableRow key={item.id}>
                      <TableCell>{item.date}</TableCell>
                      <TableCell>{typeLabel(item.record_type)}</TableCell>
                      <TableCell>
                        {item.check_in_time ? format(new Date(item.check_in_time), 'HH:mm:ss') : '-'}
                      </TableCell>
                      <TableCell>
                        {item.check_out_time ? format(new Date(item.check_out_time), 'HH:mm:ss') : '-'}
                      </TableCell>
                      <TableCell>{item.duration_hours ? item.duration_hours.toFixed(2) : '-'}</TableCell>
                      <TableCell>
                        <Badge variant="outline">{item.device || '-'}</Badge>
                      </TableCell>
                      <TableCell>
                        <Badge
                          className={
                            item.status === 'approved'
                              ? 'bg-green-100 text-green-800'
                              : item.status === 'rejected'
                                ? 'bg-red-100 text-red-800'
                                : 'bg-yellow-100 text-yellow-800'
                          }
                        >
                          {item.status === 'approved' ? 'موافق' : item.status === 'rejected' ? 'مرفوض' : 'قيد الانتظار'}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <Button size="sm" variant="outline" onClick={() => openCorrectionDialog(item)}>
                          طلب تصحيح
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </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>
                </TableRow>
              </TableHeader>
              <TableBody>
                {corrections.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={6} className="text-center py-8 text-muted-foreground">
                      لا توجد طلبات تصحيح
                    </TableCell>
                  </TableRow>
                ) : (
                  corrections.map((item) => (
                    <TableRow key={item.id}>
                      <TableCell>{item.id}</TableCell>
                      <TableCell>{item.record_id}</TableCell>
                      <TableCell className="max-w-xs whitespace-pre-wrap">{item.reason}</TableCell>
                      <TableCell>
                        <Badge
                          className={
                            item.status === 'approved'
                              ? 'bg-green-100 text-green-800'
                              : item.status === 'rejected'
                                ? 'bg-red-100 text-red-800'
                                : 'bg-yellow-100 text-yellow-800'
                          }
                        >
                          {item.status === 'approved' ? 'موافق' : item.status === 'rejected' ? 'مرفوض' : 'قيد الانتظار'}
                        </Badge>
                      </TableCell>
                      <TableCell>{item.review_reason || '-'}</TableCell>
                      <TableCell>{new Date(item.created_at).toLocaleString()}</TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>طلب تصحيح حضور</DialogTitle>
            <DialogDescription>
              يمكنك إرسال تعديل مقترح وسيتم مراجعته من قبل قسم HR.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-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={requestedRecordType}
                onChange={(e) => setRequestedRecordType(e.target.value)}
              >
                <option value="present">حاضر</option>
                <option value="absent">غائب</option>
                <option value="late">متأخر</option>
                <option value="sick">مرضي</option>
                <option value="leave">إجازة</option>
              </select>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
              <div className="space-y-1">
                <label className="text-xs text-muted-foreground">وقت الدخول المقترح</label>
                <Input
                  type="datetime-local"
                  value={requestedCheckInTime}
                  onChange={(e) => setRequestedCheckInTime(e.target.value)}
                />
              </div>
              <div className="space-y-1">
                <label className="text-xs text-muted-foreground">وقت الخروج المقترح</label>
                <Input
                  type="datetime-local"
                  value={requestedCheckOutTime}
                  onChange={(e) => setRequestedCheckOutTime(e.target.value)}
                />
              </div>
            </div>

            <div className="space-y-1">
              <label className="text-xs text-muted-foreground">سبب طلب التصحيح</label>
              <Textarea
                value={reason}
                onChange={(e) => setReason(e.target.value)}
                placeholder="اكتب سبب التصحيح بالتفصيل"
              />
            </div>

            <div className="flex justify-end gap-2">
              <Button variant="outline" onClick={() => setDialogOpen(false)}>
                إلغاء
              </Button>
              <Button onClick={() => void submitCorrection()} disabled={submittingCorrection}>
                {submittingCorrection ? 'جاري الإرسال...' : 'إرسال الطلب'}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
