'use client';

import { useEffect, useMemo, useState } from 'react';
import type { ExpenseAllocation, ExpenseObligation } 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 { Progress } from '@/components/ui/progress';
import { useToast } from '@/hooks/use-toast';

type Props = {
  obligation: ExpenseObligation;
  branches?: { id: string; name: string }[];
  costCenters?: { id: string; name: string }[];
  projects?: { id: string; name: string }[];
  departments?: { id: string; name: string }[];
};

type AllocationType = 'branch' | 'cost_center' | 'project' | 'department' | 'employee';

const ALLOCATION_TYPE_LABELS: Record<string, string> = {
  branch: 'فرع',
  cost_center: 'مركز تكلفة',
  project: 'مشروع',
  department: 'قسم',
  employee: 'موظف',
};

export function ExpenseAllocationManager({
  obligation,
  branches = [],
  costCenters = [],
  projects = [],
  departments = [],
}: Props) {
  const { toast } = useToast();

  const [allocations, setAllocations] = useState<ExpenseAllocation[]>([]);
  const [loadingAllocations, setLoadingAllocations] = useState(false);

  // Form state
  const [allocationType, setAllocationType] = useState<AllocationType>('branch');
  const [allocationTargetId, setAllocationTargetId] = useState('');
  const [percentage, setPercentage] = useState('');

  const totalPercentage = useMemo(() => {
    return allocations.reduce((sum, a) => sum + Number(a.percentage || 0), 0);
  }, [allocations]);

  const allocationTargets = useMemo(() => {
    switch (allocationType) {
      case 'branch':
        return branches;
      case 'cost_center':
        return costCenters;
      case 'project':
        return projects;
      case 'department':
        return departments;
      default:
        return [];
    }
  }, [allocationType, branches, costCenters, projects, departments]);

  const calculateAmount = (pct: number): number => {
    return Number((obligation.grossAmount * pct) / 100);
  };

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

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

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

    const pct = Number(percentage);
    if (pct <= 0 || pct > 100) {
      toast({
        title: 'خطأ التحقق',
        description: 'يجب أن تكون النسبة بين 0 و 100',
        variant: 'destructive',
      });
      return;
    }

    if (totalPercentage + pct > 100) {
      toast({
        title: 'خطأ التحقق',
        description: `إجمالي النسب سيتجاوز 100% (الحالي: ${totalPercentage}% + الجديد: ${pct}%)`,
        variant: 'destructive',
      });
      return;
    }

    try {
      const amount = calculateAmount(pct);
      const targetName = allocationTargets.find((t) => t.id === allocationTargetId)?.name;

      const response = await fetch(
        `/api/admin/expense-recurring/obligations/${encodeURIComponent(obligation.id)}/allocations`,
        {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            allocationType,
            allocationTargetId,
            allocationTargetName: targetName,
            percentage: pct,
            amount,
          }),
        }
      );

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

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

      // Reset form
      setAllocationTargetId('');
      setPercentage('');

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

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

  return (
    <div className="space-y-6">
      {/* Create Allocation Card */}
      <Card>
        <CardHeader>
          <CardTitle>إضافة توزيع</CardTitle>
          <CardDescription>
            توزيع المصروف على فروع أو مراكز تكلفة أو مشاريع ({ALLOCATION_TYPE_LABELS[allocationType]})
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleCreateAllocation} className="space-y-6">
            {/* Row 1: Type and Target */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              <div className="space-y-1">
                <Label>نوع التوزيع</Label>
                <Select value={allocationType} onValueChange={(v) => setAllocationType(v as AllocationType)}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="branch">فرع</SelectItem>
                    <SelectItem value="cost_center">مركز تكلفة</SelectItem>
                    <SelectItem value="project">مشروع</SelectItem>
                    <SelectItem value="department">قسم</SelectItem>
                    <SelectItem value="employee">موظف</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1">
                <Label>الهدف</Label>
                <Select value={allocationTargetId} onValueChange={setAllocationTargetId}>
                  <SelectTrigger>
                    <SelectValue placeholder="اختر" />
                  </SelectTrigger>
                  <SelectContent>
                    {allocationTargets.map((target) => (
                      <SelectItem key={target.id} value={target.id}>
                        {target.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1">
                <Label>النسبة المئوية (%)</Label>
                <Input
                  type="number"
                  min="0"
                  max="100"
                  step="0.01"
                  inputMode="decimal"
                  placeholder="مثال: 50"
                  value={percentage}
                  onChange={(e) => setPercentage(e.target.value)}
                  lang="en"
                  dir="ltr"
                />
              </div>
            </div>

            {/* Amount preview */}
            {percentage && (
              <div className="p-3 bg-muted rounded-md">
                <Label className="text-muted-foreground">المبلغ المحسوب</Label>
                <p className="text-lg font-semibold">
                  {calculateAmount(Number(percentage)).toLocaleString(undefined, { minimumFractionDigits: 2 })}
                </p>
              </div>
            )}

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

      {/* Allocations Summary */}
      <Card>
        <CardHeader>
          <CardTitle>ملخص التوزيعات</CardTitle>
          <CardDescription>إجمالي المبلغ: {Number(obligation.grossAmount).toLocaleString(undefined, { minimumFractionDigits: 2 })}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <div className="flex justify-between items-center">
              <span className="text-sm">إجمالي النسب المخصصة</span>
              <span className="text-sm font-semibold">{totalPercentage.toFixed(2)}%</span>
            </div>
            <Progress value={Math.min(totalPercentage, 100)} className="h-2" />
            {totalPercentage === 100 && (
              <p className="text-xs text-green-600">✓ تم توزيع 100% من المبلغ</p>
            )}
            {totalPercentage < 100 && (
              <p className="text-xs text-amber-600">
                متبقي: {(100 - totalPercentage).toFixed(2)}% ({calculateAmount(100 - totalPercentage).toLocaleString(undefined, { minimumFractionDigits: 2 })})
              </p>
            )}
            {totalPercentage > 100 && (
              <p className="text-xs text-red-600">
                ⚠ تجاوز: {(totalPercentage - 100).toFixed(2)}%
              </p>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Allocations List */}
      <Card>
        <CardHeader>
          <CardTitle>التوزيعات</CardTitle>
          <CardDescription>قائمة التوزيعات الحالية</CardDescription>
        </CardHeader>
        <CardContent>
          {loadingAllocations ? (
            <div className="text-center text-muted-foreground py-8">جاري التحميل...</div>
          ) : allocations.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>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {allocations.map((allocation) => (
                    <TableRow key={allocation.id}>
                      <TableCell>{ALLOCATION_TYPE_LABELS[allocation.allocationType] || allocation.allocationType}</TableCell>
                      <TableCell>{allocation.allocationTargetName || allocation.allocationTargetId}</TableCell>
                      <TableCell>
                        <span className="font-semibold">{Number(allocation.percentage).toFixed(2)}%</span>
                      </TableCell>
                      <TableCell>{Number(allocation.amount).toLocaleString(undefined, { minimumFractionDigits: 2 })}</TableCell>
                    </TableRow>
                  ))}
                  <TableRow className="bg-muted/50 font-semibold">
                    <TableCell colSpan={2}>الإجمالي</TableCell>
                    <TableCell>{totalPercentage.toFixed(2)}%</TableCell>
                    <TableCell>
                      {allocations
                        .reduce((sum, a) => sum + Number(a.amount), 0)
                        .toLocaleString(undefined, { minimumFractionDigits: 2 })}
                    </TableCell>
                  </TableRow>
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
