'use client';

import { useEffect, useMemo, useState } from 'react';
import type { RecurringExpenseContract, RecurringExpenseTemplate, ChartOfAccount } 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 { useToast } from '@/hooks/use-toast';

type Props = {
  templates: RecurringExpenseTemplate[];
  chartAccounts: ChartOfAccount[];
};

type ContractStatus = 'active' | 'suspended' | 'expired' | 'terminated' | 'under_review';
type RenewalTerms = 'auto_renew' | 'manual_renew' | 'term_end';
type EscalationPolicy = 'none' | 'fixed_percent' | 'indexed';
type AllocationStrategy = 'none' | 'branch' | 'cost_center' | 'project' | 'department';

const STATUS_LABELS: Record<string, string> = {
  active: 'نشط',
  suspended: 'موقوف',
  expired: 'منتهي',
  terminated: 'ملغي',
  under_review: 'قيد المراجعة',
  auto_renew: 'تجديد تلقائي',
  manual_renew: 'تجديد يدوي',
  term_end: 'انتهاء العقد',
  none: 'بدون تصعيد',
  fixed_percent: 'نسبة مئوية ثابتة',
  indexed: 'مفهرسة',
};

function getStatusBadgeVariant(status: string): 'default' | 'secondary' | 'destructive' | 'outline' {
  if (status === 'active' || status === 'auto_renew') return 'default';
  if (status === 'expired' || status === 'terminated') return 'destructive';
  if (status === 'suspended' || status === 'under_review') return 'secondary';
  return 'outline';
}

export function ExpenseContractManager({ templates, chartAccounts }: Props) {
  const { toast } = useToast();

  const [contracts, setContracts] = useState<RecurringExpenseContract[]>([]);
  const [loadingContracts, setLoadingContracts] = useState(false);
  const [statusFilter, setStatusFilter] = useState<ContractStatus | 'all'>('active');

  // Form state
  const [contractName, setContractName] = useState('');
  const [contractTemplateId, setContractTemplateId] = useState('');
  const [contractVendorId, setContractVendorId] = useState('');
  const [contractDate, setContractDate] = useState('');
  const [contractStartDate, setContractStartDate] = useState('');
  const [contractEndDate, setContractEndDate] = useState('');
  const [renewalTerms, setRenewalTerms] = useState<RenewalTerms>('manual_renew');
  const [escalationPolicy, setEscalationPolicy] = useState<EscalationPolicy>('none');
  const [escalationValue, setEscalationValue] = useState('');
  const [allocationStrategy, setAllocationStrategy] = useState<AllocationStrategy>('none');
  const [contractNotes, setContractNotes] = useState('');

  const fetchContracts = async () => {
    setLoadingContracts(true);
    try {
      const statusParam = statusFilter === 'all' ? '' : `&status=${statusFilter}`;
      const response = await fetch(`/api/admin/expense-recurring/contracts?page=1&pageSize=200${statusParam}`);
      if (!response.ok) throw new Error('تعذر جلب العقود');
      const data = await response.json();
      const items = Array.isArray(data?.items) ? data.items : [];
      setContracts(items as RecurringExpenseContract[]);
    } catch (error) {
      toast({
        title: 'خطأ',
        description: error instanceof Error ? error.message : 'فشل في جلب العقود',
        variant: 'destructive',
      });
    } finally {
      setLoadingContracts(false);
    }
  };

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

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

    try {
      const response = await fetch('/api/admin/expense-recurring/contracts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: contractName,
          templateId: contractTemplateId || undefined,
          vendorId: contractVendorId || undefined,
          contractDate,
          startDate: contractStartDate,
          endDate: contractEndDate || undefined,
          renewalTerms,
          escalationPolicy,
          escalationValue: escalationValue ? Number(escalationValue) : undefined,
          allocationStrategy,
          notes: contractNotes || undefined,
        }),
      });

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

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

      // Reset form
      setContractName('');
      setContractTemplateId('');
      setContractVendorId('');
      setContractDate('');
      setContractStartDate('');
      setContractEndDate('');
      setRenewalTerms('manual_renew');
      setEscalationPolicy('none');
      setEscalationValue('');
      setAllocationStrategy('none');
      setContractNotes('');

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

  useEffect(() => {
    fetchContracts();
  }, [statusFilter]);

  return (
    <div className="space-y-6">
      {/* Create Contract Card */}
      <Card>
        <CardHeader>
          <CardTitle>إنشاء عقد جديد</CardTitle>
          <CardDescription>ربط قالب مصروف دوري بعقد رسمي مع شروط التجديد والتصعيد</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleCreateContract} className="space-y-6">
            {/* Row 1: Name, Template, Vendor */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              <div className="space-y-1">
                <Label>اسم العقد *</Label>
                <Input
                  placeholder="مثال: عقد إيجار المستودع"
                  value={contractName}
                  onChange={(e) => setContractName(e.target.value)}
                />
              </div>
              <div className="space-y-1">
                <Label>قالب المصروف (اختياري)</Label>
                <Select value={contractTemplateId || "none"} onValueChange={(val) => setContractTemplateId(val === "none" ? "" : val)}>
                  <SelectTrigger>
                    <SelectValue placeholder="اختر قالب" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">بدون ربط</SelectItem>
                    {templates.map((t) => (
                      <SelectItem key={t.id} value={t.id}>
                        {t.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1">
                <Label>معرف البائع (اختياري)</Label>
                <Input
                  placeholder="مثال: VENDOR-001"
                  value={contractVendorId}
                  onChange={(e) => setContractVendorId(e.target.value)}
                />
              </div>
            </div>

            {/* Row 2: Dates */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              <div className="space-y-1">
                <Label>تاريخ العقد *</Label>
                <Input
                  type="date"
                  value={contractDate}
                  onChange={(e) => setContractDate(e.target.value)}
                  lang="en"
                  dir="ltr"
                />
              </div>
              <div className="space-y-1">
                <Label>تاريخ البداية *</Label>
                <Input
                  type="date"
                  value={contractStartDate}
                  onChange={(e) => setContractStartDate(e.target.value)}
                  lang="en"
                  dir="ltr"
                />
              </div>
              <div className="space-y-1">
                <Label>تاريخ النهاية (اختياري)</Label>
                <Input
                  type="date"
                  value={contractEndDate}
                  onChange={(e) => setContractEndDate(e.target.value)}
                  lang="en"
                  dir="ltr"
                />
              </div>
            </div>

            {/* Row 3: Renewal & Escalation */}
            <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
              <div className="space-y-1">
                <Label>شروط التجديد</Label>
                <Select value={renewalTerms} onValueChange={(v) => setRenewalTerms(v as RenewalTerms)}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="auto_renew">تجديد تلقائي</SelectItem>
                    <SelectItem value="manual_renew">تجديد يدوي</SelectItem>
                    <SelectItem value="term_end">انتهاء العقد</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1">
                <Label>سياسة التصعيد</Label>
                <Select value={escalationPolicy} onValueChange={(v) => setEscalationPolicy(v as EscalationPolicy)}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">بدون تصعيد</SelectItem>
                    <SelectItem value="fixed_percent">نسبة مئوية ثابتة</SelectItem>
                    <SelectItem value="indexed">مفهرسة</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              {escalationPolicy !== 'none' && (
                <div className="space-y-1">
                  <Label>قيمة التصعيد</Label>
                  <Input
                    type="number"
                    step="0.01"
                    placeholder="مثال: 5.5"
                    value={escalationValue}
                    onChange={(e) => setEscalationValue(e.target.value)}
                    lang="en"
                    dir="ltr"
                  />
                </div>
              )}
              <div className="space-y-1">
                <Label>استراتيجية التوزيع</Label>
                <Select value={allocationStrategy} onValueChange={(v) => setAllocationStrategy(v as AllocationStrategy)}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">بدون توزيع</SelectItem>
                    <SelectItem value="branch">فرع</SelectItem>
                    <SelectItem value="cost_center">مركز تكلفة</SelectItem>
                    <SelectItem value="project">مشروع</SelectItem>
                    <SelectItem value="department">قسم</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Notes */}
            <div className="space-y-1">
              <Label>ملاحظات</Label>
              <Input
                placeholder="ملاحظات إضافية حول العقد"
                value={contractNotes}
                onChange={(e) => setContractNotes(e.target.value)}
              />
            </div>

            {/* Submit Button */}
            <Button type="submit" className="w-full">
              إنشاء العقد
            </Button>
          </form>
        </CardContent>
      </Card>

      {/* Contracts List */}
      <Card>
        <CardHeader>
          <div className="flex justify-between items-center">
            <div>
              <CardTitle>العقود النشطة</CardTitle>
              <CardDescription>قائمة العقود والالتزامات المرتبطة بالمصاريف الدورية</CardDescription>
            </div>
            <Select value={statusFilter} onValueChange={(v) => setStatusFilter(v as any)}>
              <SelectTrigger className="w-48">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">الكل</SelectItem>
                <SelectItem value="active">نشط</SelectItem>
                <SelectItem value="suspended">موقوف</SelectItem>
                <SelectItem value="expired">منتهي</SelectItem>
                <SelectItem value="terminated">ملغي</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardHeader>
        <CardContent>
          {loadingContracts ? (
            <div className="text-center text-muted-foreground py-8">جاري التحميل...</div>
          ) : contracts.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>
                    <TableHead>الحالة</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {contracts.map((contract) => (
                    <TableRow key={contract.id}>
                      <TableCell className="font-medium">{contract.name}</TableCell>
                      <TableCell>
                        {contract.templateId
                          ? templates.find((t) => t.id === contract.templateId)?.name || '-'
                          : '-'}
                      </TableCell>
                      <TableCell>{formatDateDDMMYYYY(contract.contractDate)}</TableCell>
                      <TableCell>
                        {formatDateDDMMYYYY(contract.startDate)} -{' '}
                        {contract.endDate ? formatDateDDMMYYYY(contract.endDate) : 'مفتوح'}
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline">{STATUS_LABELS[contract.renewalTerms] || contract.renewalTerms}</Badge>
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline">
                          {STATUS_LABELS[contract.escalationPolicy] || contract.escalationPolicy}
                          {contract.escalationValue && ` (${contract.escalationValue}%)`}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <Badge variant={getStatusBadgeVariant(contract.status)}>
                          {STATUS_LABELS[contract.status] || contract.status}
                        </Badge>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
