'use client';

import { useEffect, useMemo, useState } from 'react';
import type { ExpensePosting, ExpenseObligation, ChartOfAccount } from '@/lib/types';
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 { useToast } from '@/hooks/use-toast';

type Props = {
  obligation: ExpenseObligation;
  chartAccounts: ChartOfAccount[];
};

type PostingStatus = 'pending' | 'posted' | 'reversed' | 'cancelled';
type PostingType = 'regular' | 'reversal' | 'adjustment';

const STATUS_LABELS: Record<string, string> = {
  pending: 'قيد الانتظار',
  posted: 'مرحل',
  reversed: 'معكوس',
  cancelled: 'ملغي',
};

const POSTING_TYPE_LABELS: Record<string, string> = {
  regular: 'عادي',
  reversal: 'عكس',
  adjustment: 'تعديل',
};

function getStatusBadgeVariant(status: string): 'default' | 'secondary' | 'destructive' | 'outline' {
  if (status === 'posted') return 'default';
  if (status === 'pending' || status === 'adjustment') return 'secondary';
  if (status === 'reversed' || status === 'cancelled') return 'destructive';
  return 'outline';
}

export function ExpensePostingManager({ obligation, chartAccounts }: Props) {
  const { toast } = useToast();

  const [postings, setPostings] = useState<ExpensePosting[]>([]);
  const [loadingPostings, setLoadingPostings] = useState(false);

  // Form state
  const [debitAccount, setDebitAccount] = useState('');
  const [creditAccount, setCreditAccount] = useState('');
  const [amount, setAmount] = useState('');
  const [postingDate, setPostingDate] = useState(new Date().toISOString().slice(0, 10));
  const [postingType, setPostingType] = useState<PostingType>('regular');

  const expenseAccounts = useMemo(() => {
    return chartAccounts.filter((a) => String(a.code || '').startsWith('5'));
  }, [chartAccounts]);

  const payableAccounts = useMemo(() => {
    return chartAccounts.filter((a) => String(a.code || '').startsWith('21'));
  }, [chartAccounts]);

  const debitAccountName = useMemo(() => {
    return chartAccounts.find((a) => a.code === debitAccount)?.name;
  }, [debitAccount, chartAccounts]);

  const creditAccountName = useMemo(() => {
    return chartAccounts.find((a) => a.code === creditAccount)?.name;
  }, [creditAccount, chartAccounts]);

  const totalDebits = useMemo(() => {
    return postings
      .filter((p) => p.status === 'posted')
      .reduce((sum, p) => sum + Number(p.amount || 0), 0);
  }, [postings]);

  const totalCredits = useMemo(() => {
    return postings
      .filter((p) => p.status === 'posted')
      .reduce((sum, p) => sum + Number(p.amount || 0), 0);
  }, [postings]);

  const isBalanced = Math.abs(totalDebits - totalCredits) < 0.01;

  const fetchPostings = async () => {
    setLoadingPostings(true);
    try {
      const response = await fetch(
        `/api/admin/expense-recurring/obligations/${encodeURIComponent(obligation.id)}/postings`
      );
      if (!response.ok) throw new Error('تعذر جلب القيود');
      const data = await response.json();
      const items = Array.isArray(data?.items) ? data.items : [];
      setPostings(items as ExpensePosting[]);
    } catch (error) {
      toast({
        title: 'خطأ',
        description: error instanceof Error ? error.message : 'فشل في جلب القيود',
        variant: 'destructive',
      });
    } finally {
      setLoadingPostings(false);
    }
  };

  const handleCreatePosting = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!debitAccount || !creditAccount || !amount) {
      toast({
        title: 'خطأ التحقق',
        description: 'يرجى ملء جميع الحقول',
        variant: 'destructive',
      });
      return;
    }

    if (debitAccount === creditAccount) {
      toast({
        title: 'خطأ التحقق',
        description: 'لا يمكن أن يكون حساب القيد والدائن متطابقين',
        variant: 'destructive',
      });
      return;
    }

    try {
      const response = await fetch(
        `/api/admin/expense-recurring/obligations/${encodeURIComponent(obligation.id)}/postings`,
        {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            debitAccount,
            creditAccount,
            amount: Number(amount),
            postingDate,
            postingType,
            status: 'pending',
          }),
        }
      );

      if (!response.ok) throw new Error('فشل في إنشاء القيد');

      toast({
        title: 'نجح',
        description: 'تم إنشاء القيد بنجاح',
      });

      // Reset form
      setDebitAccount('');
      setCreditAccount('');
      setAmount('');
      setPostingDate(new Date().toISOString().slice(0, 10));
      setPostingType('regular');

      // Refresh list
      await fetchPostings();
    } catch (error) {
      toast({
        title: 'خطأ',
        description: error instanceof Error ? error.message : 'فشل في إنشاء القيد',
        variant: 'destructive',
      });
    }
  };

  useEffect(() => {
    fetchPostings();
  }, [obligation.id]);

  return (
    <div className="space-y-6">
      {/* Create Posting Card */}
      <Card>
        <CardHeader>
          <CardTitle>إنشاء قيد محاسبي</CardTitle>
          <CardDescription>تسجيل المصروف والالتزام في الدفاتر المحاسبية</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleCreatePosting} className="space-y-6">
            {/* Row 1: Accounts */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
              <div className="space-y-1">
                <Label>حساب المدين (مصروف) *</Label>
                <Select value={debitAccount} onValueChange={setDebitAccount}>
                  <SelectTrigger>
                    <SelectValue placeholder="اختر الحساب" />
                  </SelectTrigger>
                  <SelectContent>
                    {expenseAccounts.map((a) => (
                      <SelectItem key={a.code} value={a.code || ''}>
                        {a.code} - {a.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1">
                <Label>حساب الدائن (التزام) *</Label>
                <Select value={creditAccount} onValueChange={setCreditAccount}>
                  <SelectTrigger>
                    <SelectValue placeholder="اختر الحساب" />
                  </SelectTrigger>
                  <SelectContent>
                    {payableAccounts.map((a) => (
                      <SelectItem key={a.code} value={a.code || ''}>
                        {a.code} - {a.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Row 2: Amount, Date, Type */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              <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>
                <Input
                  type="date"
                  value={postingDate}
                  onChange={(e) => setPostingDate(e.target.value)}
                  lang="en"
                  dir="ltr"
                />
              </div>
              <div className="space-y-1">
                <Label>نوع القيد</Label>
                <Select value={postingType} onValueChange={(v) => setPostingType(v as PostingType)}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="regular">عادي</SelectItem>
                    <SelectItem value="reversal">عكس</SelectItem>
                    <SelectItem value="adjustment">تعديل</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Preview */}
            {debitAccount && creditAccount && amount && (
              <div className="p-3 bg-muted rounded-md space-y-2 text-sm">
                <div className="font-semibold">معاينة القيد:</div>
                <div className="flex justify-between">
                  <span>
                    مدين: {debitAccount} {debitAccountName && `- ${debitAccountName}`}
                  </span>
                  <span className="font-semibold">{Number(amount).toLocaleString(undefined, { minimumFractionDigits: 2 })}</span>
                </div>
                <div className="flex justify-between">
                  <span>
                    دائن: {creditAccount} {creditAccountName && `- ${creditAccountName}`}
                  </span>
                  <span className="font-semibold">{Number(amount).toLocaleString(undefined, { minimumFractionDigits: 2 })}</span>
                </div>
              </div>
            )}

            {/* Submit Button */}
            <Button type="submit" className="w-full">
              إنشاء القيد
            </Button>
          </form>
        </CardContent>
      </Card>

      {/* Trial Balance */}
      <Card>
        <CardHeader>
          <CardTitle>ميزان التحقق</CardTitle>
          <CardDescription>التحقق من توازن القيود المرحلة</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="space-y-1">
              <Label className="text-muted-foreground text-xs">إجمالي المدين</Label>
              <p className="text-2xl font-bold">
                {totalDebits.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">
                {totalCredits.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 ${isBalanced ? 'text-green-600' : 'text-red-600'}`}>
                {Math.abs(totalDebits - totalCredits).toLocaleString(undefined, { minimumFractionDigits: 2 })}
              </p>
            </div>
          </div>
          <div className="mt-4 p-2 rounded-md bg-muted">
            {isBalanced ? (
              <p className="text-sm text-green-600">✓ القيود متوازنة</p>
            ) : (
              <p className="text-sm text-red-600">⚠ القيود غير متوازنة</p>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Postings List */}
      <Card>
        <CardHeader>
          <CardTitle>القيود المحاسبية</CardTitle>
          <CardDescription>قائمة جميع القيود المرتبطة بهذا الالتزام</CardDescription>
        </CardHeader>
        <CardContent>
          {loadingPostings ? (
            <div className="text-center text-muted-foreground py-8">جاري التحميل...</div>
          ) : postings.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>
                  {postings.map((posting) => (
                    <TableRow key={posting.id}>
                      <TableCell>{formatDateDDMMYYYY(posting.postingDate)}</TableCell>
                      <TableCell>
                        <span className="text-xs">{posting.debitAccount}</span>
                      </TableCell>
                      <TableCell>
                        <span className="text-xs">{posting.creditAccount}</span>
                      </TableCell>
                      <TableCell>{Number(posting.amount).toLocaleString(undefined, { minimumFractionDigits: 2 })}</TableCell>
                      <TableCell>
                        <Badge variant="outline">{POSTING_TYPE_LABELS[posting.postingType] || posting.postingType}</Badge>
                      </TableCell>
                      <TableCell>
                        <Badge variant={getStatusBadgeVariant(posting.status)}>
                          {STATUS_LABELS[posting.status] || posting.status}
                        </Badge>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
