'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import type { SalesInvoice, SalesInvoicePaymentMethod } from '@/lib/modules/sales';
import {
  handleRecordSalesPayment,
  handleCancelSalesInvoice,
} from '@/lib/actions/sales-invoice.actions';
import { useToast } from '@/hooks/use-toast';
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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';

type SalesInvoiceViewActionsProps = {
  invoice: SalesInvoice;
  userId: string;
  userName: string;
};

const PAYMENT_METHODS: Array<{ value: SalesInvoicePaymentMethod['method']; label: string }> = [
  { value: 'cash', label: 'نقدي' },
  { value: 'check', label: 'شيك' },
  { value: 'bank_transfer', label: 'تحويل بنكي' },
  { value: 'credit', label: 'آجل' },
];

export default function SalesInvoiceViewActions({
  invoice,
  userId,
  userName,
}: SalesInvoiceViewActionsProps) {
  const router = useRouter();
  const { toast } = useToast();

  // Payment state
  const [paymentAmount, setPaymentAmount] = useState(invoice.amountDue.toFixed(2));
  const [paymentMethod, setPaymentMethod] = useState<SalesInvoicePaymentMethod['method']>('cash');
  const [paymentReference, setPaymentReference] = useState('');
  const [isPaymentSubmitting, setIsPaymentSubmitting] = useState(false);

  // Cancel state
  const [cancelReason, setCancelReason] = useState('');
  const [isCancelSubmitting, setIsCancelSubmitting] = useState(false);
  const [showCancelForm, setShowCancelForm] = useState(false);

  const canRecordPayment = invoice.status !== 'cancelled'
    && invoice.amountDue > 0
    && (invoice as any).documentType !== 'shipment';
  const canCancel = invoice.status === 'active';

  const onRecordPayment = async () => {
    const parsed = Number(paymentAmount);
    if (!Number.isFinite(parsed) || parsed <= 0) {
      toast({ title: 'خطأ', description: 'يرجى إدخال مبلغ صحيح أكبر من صفر.', variant: 'destructive' });
      return;
    }
    if (parsed > invoice.amountDue) {
      toast({ title: 'خطأ', description: 'المبلغ أكبر من الرصيد المتبقي.', variant: 'destructive' });
      return;
    }

    try {
      setIsPaymentSubmitting(true);
      const result = await handleRecordSalesPayment(
        invoice.id,
        parsed,
        {
          method: paymentMethod,
          amount: parsed,
          date: new Date().toISOString(),
          reference: paymentReference || undefined,
        },
        userId,
        userName
      );

      if (!result.success) {
        toast({ title: 'تعذر تسجيل الدفعة', description: result.error, variant: 'destructive' });
        return;
      }

      toast({ title: 'تم تسجيل الدفعة', description: `تم تسجيل ${parsed.toFixed(2)} بنجاح.` });
      router.refresh();
    } catch {
      toast({ title: 'خطأ', description: 'حدث خطأ غير متوقع.', variant: 'destructive' });
    } finally {
      setIsPaymentSubmitting(false);
    }
  };

  const onCancelInvoice = async () => {
    if (!cancelReason.trim()) {
      toast({ title: 'خطأ', description: 'يرجى إدخال سبب الإلغاء.', variant: 'destructive' });
      return;
    }

    try {
      setIsCancelSubmitting(true);
      const result = await handleCancelSalesInvoice(
        invoice.id,
        cancelReason.trim(),
        userId,
        userName
      );

      if (!result.success) {
        toast({ title: 'تعذر إلغاء الفاتورة', description: result.error, variant: 'destructive' });
        return;
      }

      toast({ title: 'تم الإلغاء', description: 'تم إلغاء الفاتورة بنجاح.' });
      router.refresh();
    } catch {
      toast({ title: 'خطأ', description: 'حدث خطأ غير متوقع.', variant: 'destructive' });
    } finally {
      setIsCancelSubmitting(false);
    }
  };

  if (!canRecordPayment && !canCancel) {
    return null;
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>الإجراءات السريعة</CardTitle>
      </CardHeader>
      <CardContent className="space-y-6">
        {canRecordPayment && (
          <div className="space-y-3 rounded-md border p-4">
            <p className="text-sm font-semibold">تسجيل دفعة</p>
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
              <div className="space-y-1">
                <label className="text-xs text-muted-foreground">المبلغ (المتبقي: {invoice.amountDue.toFixed(2)})</label>
                <Input
                  type="number"
                  min="0"
                  step="0.01"
                  value={paymentAmount}
                  onChange={(e) => setPaymentAmount(e.target.value)}
                />
              </div>
              <div className="space-y-1">
                <label className="text-xs text-muted-foreground">طريقة الدفع</label>
                <Select
                  value={paymentMethod}
                  onValueChange={(v) => setPaymentMethod(v as SalesInvoicePaymentMethod['method'])}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {PAYMENT_METHODS.map((m) => (
                      <SelectItem key={m.value} value={m.value}>{m.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1">
                <label className="text-xs text-muted-foreground">مرجع (اختياري)</label>
                <Input
                  value={paymentReference}
                  onChange={(e) => setPaymentReference(e.target.value)}
                  placeholder="رقم الشيك / مرجع التحويل"
                />
              </div>
            </div>
            <div className="flex justify-end">
              <Button size="sm" disabled={isPaymentSubmitting} onClick={onRecordPayment}>
                {isPaymentSubmitting ? 'جاري التسجيل...' : 'تسجيل الدفعة'}
              </Button>
            </div>
          </div>
        )}

        {canCancel && (
          <div className="space-y-3 rounded-md border border-destructive/40 p-4">
            <p className="text-sm font-semibold text-destructive">إلغاء الفاتورة</p>
            {!showCancelForm ? (
              <Button
                size="sm"
                variant="destructive"
                onClick={() => setShowCancelForm(true)}
              >
                إلغاء الفاتورة
              </Button>
            ) : (
              <>
                <Textarea
                  value={cancelReason}
                  onChange={(e) => setCancelReason(e.target.value)}
                  placeholder="اكتب سبب الإلغاء"
                  rows={2}
                />
                <div className="flex gap-2 justify-end">
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => { setShowCancelForm(false); setCancelReason(''); }}
                  >
                    تراجع
                  </Button>
                  <Button
                    size="sm"
                    variant="destructive"
                    disabled={isCancelSubmitting}
                    onClick={onCancelInvoice}
                  >
                    {isCancelSubmitting ? 'جاري الإلغاء...' : 'تأكيد الإلغاء'}
                  </Button>
                </div>
              </>
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
}
