import Link from 'next/link';
import { notFound, redirect } from 'next/navigation';
import { getSession } from '@/lib/auth';
import { hasEmployeePermission } from '@/lib/employee-permissions';
import { pgGetSettings } from '@/lib/postgres/data-access';
import { pgGetRecurringExpenseTemplateById } from '@/lib/postgres/expense-recurring';
import { pgGetScheduleJobById, pgListBackgroundJobLogs } from '@/lib/postgres/scheduler';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { ExpenseSchedulerJobActions } from '@/components/admin/expense-scheduler-job-actions';

function toLocal(value?: string) {
  if (!value) return '-';
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return '-';
  return date.toLocaleString('ar-SA');
}

type Props = {
  params: Promise<{ jobId: string }>;
};

export default async function SchedulerJobDetailsPage({ params }: Props) {
  const session = await getSession();
  const settings = await pgGetSettings();

  if (
    !session?.user ||
    (!hasEmployeePermission(session.user, settings, 'admin.accounting') &&
      !hasEmployeePermission(session.user, settings, 'admin.expense-recurring'))
  ) {
    redirect('/login');
  }

  const { jobId } = await params;
  const job = await pgGetScheduleJobById(jobId);

  if (!job) {
    notFound();
  }

  const [template, logs] = await Promise.all([
    pgGetRecurringExpenseTemplateById(job.templateId),
    pgListBackgroundJobLogs({ jobId: job.id, limit: 200 }),
  ]);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between gap-3">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">تفاصيل وظيفة المجدول</h1>
          <p className="text-muted-foreground mt-1">عرض حالة الوظيفة وسجل التنفيذ والإجراءات المباشرة.</p>
        </div>
        <Button asChild variant="outline">
          <Link href="/admin/accounting/expense-recurring-advanced">العودة للوحة المجدول</Link>
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>ملخص الوظيفة</CardTitle>
          <CardDescription>البيانات الأساسية للوظيفة المجدولة الحالية.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4 text-sm">
            <div>
              <div className="text-muted-foreground">معرف الوظيفة</div>
              <div className="font-medium break-all">{job.id}</div>
            </div>
            <div>
              <div className="text-muted-foreground">القالب</div>
              <div className="font-medium">{template?.name || job.templateId}</div>
            </div>
            <div>
              <div className="text-muted-foreground">التشغيل القادم</div>
              <div className="font-medium">{toLocal(job.nextRunDate)}</div>
            </div>
            <div>
              <div className="text-muted-foreground">الحالة</div>
              <div><Badge variant={job.status === 'active' ? 'default' : 'secondary'}>{job.status}</Badge></div>
            </div>
            <div>
              <div className="text-muted-foreground">التشغيل الأخير</div>
              <div className="font-medium">{toLocal(job.lastRunDate)}</div>
            </div>
            <div>
              <div className="text-muted-foreground">إجمالي مرات التشغيل</div>
              <div className="font-medium">{job.totalRuns}</div>
            </div>
            <div>
              <div className="text-muted-foreground">المحاولات</div>
              <div className="font-medium">{job.retryCount} / {job.maxRetries}</div>
            </div>
            <div>
              <div className="text-muted-foreground">أساس الالتزام</div>
              <div className="font-medium">{job.obligationBasis}</div>
            </div>
          </div>

          <div className="text-sm">
            <div className="text-muted-foreground">آخر خطأ</div>
            <div className="font-medium break-all">{job.lastError || '-'}</div>
          </div>

          <ExpenseSchedulerJobActions jobId={job.id} status={job.status} />
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>سجل التنفيذ</CardTitle>
          <CardDescription>أحدث محاولات تشغيل هذه الوظيفة.</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="border rounded-md overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>الوقت</TableHead>
                  <TableHead>الحالة</TableHead>
                  <TableHead>النوع</TableHead>
                  <TableHead>Generated</TableHead>
                  <TableHead>Failed</TableHead>
                  <TableHead>الخطأ</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {logs.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={6} className="text-center text-muted-foreground">
                      لا توجد سجلات لهذه الوظيفة
                    </TableCell>
                  </TableRow>
                ) : (
                  logs.map((log) => (
                    <TableRow key={log.id}>
                      <TableCell>{toLocal(log.startedAt)}</TableCell>
                      <TableCell>
                        <Badge variant={log.status === 'success' ? 'default' : log.status === 'failed' ? 'destructive' : 'secondary'}>
                          {log.status}
                        </Badge>
                      </TableCell>
                      <TableCell>{log.jobType}</TableCell>
                      <TableCell>{log.generatedDocuments}</TableCell>
                      <TableCell>{log.failedDocuments}</TableCell>
                      <TableCell className="max-w-[360px] truncate">{log.errorMessage || '-'}</TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
