'use client';

import { useEffect, useMemo, useState } from 'react';
import type { ExpensePaymentSchedule, ExpenseObligation } from '@/lib/types';
import { formatDateDDMMYYYY } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { useToast } from '@/hooks/use-toast';

type Props = {
  obligation: ExpenseObligation;
  banks?: { code: string; name: string }[];
};

type PaymentScheduleStatus = 'pending' | 'partially_paid' | 'paid' | 'overdue' | 'cancelled';

const STATUS_LABELS: Record<string, string> = {
  pending: 'في الانتظار',
  partially_paid: 'مسدد جزئياً',
  paid: 'مسدد',
  overdue: 'متأخر',
  cancelled: 'ملغي',
};

function getStatusBadgeVariant(status: string): 'default' | 'secondary' | 'destructive' | 'outline' {
  if (status === 'paid') return 'default';
  if (status === 'partially_paid' || status === 'pending') return 'secondary';
  if (status === 'overdue' || status === 'cancelled') return 'destructive';
  return 'outline';
}

export function ExpensePaymentScheduleManager({ obligation, banks = [] }: Props) {
  const { toast } = useToast();

  const [schedules, setSchedules] = useState<ExpensePaymentSchedule[]>([]);
  const [loadingSchedules, setLoadingSchedules] = useState(false);

  // Form state
  const [dueDate, setDueDate] = useState('');
  const [amount, setAmount] = useState('');
  const [paymentMethod, setPaymentMethod] = useState('bank');

  const totalScheduled = useMemo(() => {
    return schedules.reduce((sum, s) => sum + Number(s.amount || 0), 0);
  }, [schedules]);

  const totalPaid = useMemo(() => {
    return schedules.reduce((sum, s) => sum + Number(s.paidAmount || 0), 0);
  }, [schedules]);

  const remainingAmount = useMemo(() => {
    return Math.max(0, Number(obligation.grossAmount) - totalScheduled);
  }, [obligation.grossAmount, totalScheduled]);

  const paidPercentage = useMemo(() => {
    if (totalScheduled === 0) return 0;
    return (totalPaid / totalScheduled) * 100;
  }, [totalPaid, totalScheduled]);

  const fetchSchedules = async () => {
    setLoadingSchedules(true);
    try {
      const response = await fetch(
        `/api/admin/expense-recurring/obligations/${encodeURIComponent(obligation.id)}/payment-schedules`
      );
      if (!response.ok) throw new Error('تعذر جلب جداول الدفع');
      const data = await response.json();
      const items = Array.isArray(data?.items) ? data.items : [];
      setSchedules(items as ExpensePaymentSchedule[]);
    } catch (error) {
      toast({
        title: 'خطأ',
        description: error instanceof Error ? error.message : 'فشل في جلب جداول الدفع',
        variant: 'destructive',
      });
    } finally {
      setLoadingSchedules(false);
    }
  };

  const handleCreateSchedule = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!dueDate || !amount) {
      toast({
        title: 'خطأ التحقق',
        description: 'يرجى ملء الحقول المطلوبة',
        variant: 'destructive',
      });
      return;
    }

    const newAmount = Number(amount);
    if (totalScheduled + newAmount > Number(obligation.grossAmount)) {
      toast({
        title: 'خطأ التحقق',
        description: `مجموع الدفعات سيتجاوز الالتزام (${totalScheduled} + ${newAmount} > ${obligation.grossAmount})`,
        variant: 'destructive',
      });
      return;
    }

    try {
      const response = await fetch(
        `/api/admin/expense-recurring/obligations/${encodeURIComponent(obligation.id)}/payment-schedules`,
        {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            dueDate,
            amount: newAmount,
            paymentMethod,
            status: 'pending',
          }),
        }
      );

      if (!response.ok) throw new Error('فشل في إنشاء جدول الدفع');

      toast({
        title: 'نجح',
        description: 'تم إنشاء جدول الدفع بنجاح',
      });

      // Reset form
      setDueDate('');
      setAmount('');
      setPaymentMethod('bank');

      // Refresh list
      await fetchSchedules();
    } catch (error) {
      toast({
        title: 'خطأ',
        description: error instanceof Error ? error.message : 'فشل في إنشاء جدول الدفع',
        variant: 'destructive',
      });
    }
  };

  useEffect(() => {
    fetchSchedules();
  }, [obligation.id]);

  return (
    <div className="space-y-6">
      {/* Create Schedule Card */}
      <Card>
        <CardHeader>
          <CardTitle>إضافة جدول دفع</CardTitle>
          <CardDescription>تحديد تاريخ استحقاق ومبلغ الدفعة</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleCreateSchedule} className="space-y-6">
            {/* Row 1: Date, Amount, Method */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              <div className="space-y-1">
                <Label>تاريخ الاستحقاق *</Label>
                <Input
                  type="date"
                  value={dueDate}
                  onChange={(e) => setDueDate(e.target.value)}
                  lang="en"
                  dir="ltr"
                />
              </div>
              <div className="space-y-1">
                <Label>المبلغ *</Label>
                <Input
                  type="number"
                  step="0.01"
                  inputMode="decimal"
                  placeholder="0.00"
                  value={amount}
                  onChange={(e) => setAmount(e.target.value)}
                  lang="en"
                  dir="ltr"
                />
              </div>
              <div className="space-y-1">
                <Label>طريقة الدفع</Label>
                <Select value={paymentMethod} onValueChange={setPaymentMethod}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="bank">بنكي</SelectItem>
                    <SelectItem value="cash">نقد</SelectItem>
                    <SelectItem value="credit">دفع إلكتروني</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Remaining info */}
            {amount && (
              <div className="p-3 bg-muted rounded-md space-y-2 text-sm">
                <div className="flex justify-between">
                  <span>الالتزام الكامل:</span>
                  <span className="font-semibold">
                    {Number(obligation.grossAmount).toLocaleString(undefined, { minimumFractionDigits: 2 })}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span>المجدول حالياً:</span>
                  <span className="font-semibold">
                    {totalScheduled.toLocaleString(undefined, { minimumFractionDigits: 2 })}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span>هذه الدفعة:</span>
                  <span className="font-semibold">{Number(amount).toLocaleString(undefined, { minimumFractionDigits: 2 })}</span>
                </div>
                <div className="border-t pt-2 flex justify-between">
                  <span>المتبقي بعد الدفعة:</span>
                  <span className="font-semibold">
                    {Math.max(0, Number(obligation.grossAmount) - (totalScheduled + Number(amount))).toLocaleString(
                      undefined,
                      { minimumFractionDigits: 2 }
                    )}
                  </span>
                </div>
              </div>
            )}

            {/* Submit Button */}
            <Button type="submit" className="w-full">
              إضافة الدفعة
            </Button>
          </form>
        </CardContent>
      </Card>

      {/* Payment Status Summary */}
      <Card>
        <CardHeader>
          <CardTitle>ملخص حالة الدفع</CardTitle>
        </CardHeader>
        <CardContent className="space-y-6">
          {/* Payment Breakdown */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div className="space-y-1">
              <Label className="text-muted-foreground text-xs">الالتزام الكامل</Label>
              <p className="text-2xl font-bold">
                {Number(obligation.grossAmount).toLocaleString(undefined, { minimumFractionDigits: 2 })}
              </p>
            </div>
            <div className="space-y-1">
              <Label className="text-muted-foreground text-xs">المجدول</Label>
              <p className="text-2xl font-bold">
                {totalScheduled.toLocaleString(undefined, { minimumFractionDigits: 2 })}
              </p>
            </div>
            <div className="space-y-1">
              <Label className="text-muted-foreground text-xs">المسدد</Label>
              <p className="text-2xl font-bold text-green-600">
                {totalPaid.toLocaleString(undefined, { minimumFractionDigits: 2 })}
              </p>
            </div>
            <div className="space-y-1">
              <Label className="text-muted-foreground text-xs">المتبقي</Label>
              <p className="text-2xl font-bold text-amber-600">
                {remainingAmount.toLocaleString(undefined, { minimumFractionDigits: 2 })}
              </p>
            </div>
          </div>

          {/* Progress */}
          <div className="space-y-2">
            <div className="flex justify-between text-sm">
              <span>نسبة الدفع من المجدول</span>
              <span className="font-semibold">{paidPercentage.toFixed(1)}%</span>
            </div>
            <Progress value={Math.min(paidPercentage, 100)} className="h-2" />
          </div>
        </CardContent>
      </Card>

      {/* Schedules List */}
      <Card>
        <CardHeader>
          <CardTitle>جداول الدفع</CardTitle>
          <CardDescription>
            إجمالي الدفعات: {schedules.length} ({totalScheduled.toLocaleString(undefined, { minimumFractionDigits: 2 })})
          </CardDescription>
        </CardHeader>
        <CardContent>
          {loadingSchedules ? (
            <div className="text-center text-muted-foreground py-8">جاري التحميل...</div>
          ) : schedules.length === 0 ? (
            <div className="text-center text-muted-foreground py-8">لا توجد جداول دفع</div>
          ) : (
            <div className="overflow-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>تاريخ الاستحقاق</TableHead>
                    <TableHead>المبلغ المجدول</TableHead>
                    <TableHead>المبلغ المسدد</TableHead>
                    <TableHead>المتبقي</TableHead>
                    <TableHead>طريقة الدفع</TableHead>
                    <TableHead>الحالة</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {schedules.map((schedule) => (
                    <TableRow key={schedule.id}>
                      <TableCell>{formatDateDDMMYYYY(schedule.dueDate)}</TableCell>
                      <TableCell>
                        {Number(schedule.amount).toLocaleString(undefined, { minimumFractionDigits: 2 })}
                      </TableCell>
                      <TableCell>
                        {Number(schedule.paidAmount).toLocaleString(undefined, { minimumFractionDigits: 2 })}
                      </TableCell>
                      <TableCell>
                        {Number(schedule.amount - schedule.paidAmount).toLocaleString(undefined, {
                          minimumFractionDigits: 2,
                        })}
                      </TableCell>
                      <TableCell>{schedule.paymentMethod || 'بنكي'}</TableCell>
                      <TableCell>
                        <Badge variant={getStatusBadgeVariant(schedule.status)}>
                          {STATUS_LABELS[schedule.status] || schedule.status}
                        </Badge>
                      </TableCell>
                    </TableRow>
                  ))}
                  <TableRow className="bg-muted/50 font-semibold">
                    <TableCell>الإجمالي</TableCell>
                    <TableCell>{totalScheduled.toLocaleString(undefined, { minimumFractionDigits: 2 })}</TableCell>
                    <TableCell className="text-green-600">
                      {totalPaid.toLocaleString(undefined, { minimumFractionDigits: 2 })}
                    </TableCell>
                    <TableCell>
                      {(totalScheduled - totalPaid).toLocaleString(undefined, { minimumFractionDigits: 2 })}
                    </TableCell>
                    <TableCell colSpan={2}></TableCell>
                  </TableRow>
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
