'use client';

import { useState, useTransition, useEffect } from 'react';
import { useForm, useFieldArray } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
import { useToast } from '@/hooks/use-toast';
import { useDocumentLock } from '@/hooks/use-document-lock';
import { DocumentLockBanner } from '@/components/admin/document-lock-banner';
import { handleUpdateCustomerPricing, handleAddCategory, handleDeleteCategory } from '@/lib/actions';
import { type Customer, type ProductionItem, type CustomerPricing, type CustomerCategory } from '@/lib/types';
import { Loader2, PlusCircle, Trash2 } from 'lucide-react';

const customerPricingSchema = z.object({
  category: z.string(),
  prices: z.array(z.object({
    materialId: z.string().min(1, 'Please select an item.'),
    price: z.coerce.number().min(0, 'Price must be 0 or more.'),
  })),
  bonus: z.object({
    materialId: z.string().optional(),
    buyQuantity: z.coerce.number().min(0).optional(),
    bonusQuantity: z.coerce.number().min(0).optional(),
  }).optional(),
});

type CustomerPricingFormProps = {
  customers: Customer[];
  materials: ProductionItem[];
  allPricing: CustomerPricing[];
  categories: CustomerCategory[];
  t: any;
  tGlobal: any;
};

export default function CustomerPricingForm({ customers, materials, allPricing, categories, t, tGlobal }: CustomerPricingFormProps) {
  const [selectedCategory, setSelectedCategory] = useState<string>('');
  const [showAddCategoryDialog, setShowAddCategoryDialog] = useState(false);
  const [newCategoryName, setNewCategoryName] = useState('');
  const [isPending, startTransition] = useTransition();
  const [isCategoryPending, startCategoryTransition] = useTransition();
  const { toast } = useToast();
  const { lockStatus } = useDocumentLock('customer-pricing', selectedCategory, { enabled: !!selectedCategory });
  const isEditLocked = !!selectedCategory && lockStatus.isLocked;


  const form = useForm<z.infer<typeof customerPricingSchema>>({
    resolver: zodResolver(customerPricingSchema),
  });

  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: 'prices',
  });

  useEffect(() => {
    if (selectedCategory) {
      const pricingData = allPricing.find(p => p.category === selectedCategory);
      form.reset({
        category: selectedCategory,
        prices: pricingData?.prices || [],
        bonus: {
          materialId: pricingData?.bonus?.materialId || '',
          buyQuantity: pricingData?.bonus?.buyQuantity || 0,
          bonusQuantity: pricingData?.bonus?.bonusQuantity || 0,
        },
      });
    } else {
      form.reset({
        category: '',
        prices: [],
        bonus: { materialId: '', buyQuantity: 0, bonusQuantity: 0 },
      });
    }
  }, [selectedCategory, allPricing, form]);

  const onSubmit = (values: z.infer<typeof customerPricingSchema>) => {
    if (isEditLocked) { return; }
    startTransition(async () => {
      const result = await handleUpdateCustomerPricing(values);
      if (result.success) {
        toast({ title: t.saveSuccessTitle ?? "Success", description: result.message });
      } else {
        toast({ title: t.saveErrorTitle ?? "Error", description: result.error, variant: 'destructive' });
      }
    });
  };

  const onAddCategory = () => {
    if (!newCategoryName.trim()) return;
    startCategoryTransition(async () => {
      const result = await handleAddCategory({ name: newCategoryName });
      if (result.success) {
        toast({ title: t.saveSuccessTitle ?? "Success", description: t.categoryAddedSuccess ?? "تمت إضافة التصنيف بنجاح" });
        setNewCategoryName('');
        setShowAddCategoryDialog(false);
        setSelectedCategory(result.category?.name || '');
      } else {
        toast({ title: t.saveErrorTitle ?? "Error", description: result.error, variant: 'destructive' });
      }
    });
  };

  const onDeleteCategory = (id: string) => {
    startCategoryTransition(async () => {
      const result = await handleDeleteCategory(id);
      if (result.success) {
        toast({ title: t.deleteSuccessTitle ?? "Success", description: t.categoryDeletedSuccess ?? "تم حذف التصنيف بنجاح" });
        if (selectedCategory === categories.find(c => c.id === id)?.name) {
          setSelectedCategory('');
        }
      } else {
        toast({ title: t.deleteErrorTitle ?? "Error", description: result.error, variant: 'destructive' });
      }
    });
  };

  const categoryLabel = selectedCategory || t.allCategories?.general || 'عام';

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader>
          <CardTitle>{t.manageCustomerPricing ?? 'أسعار الزبائن'}</CardTitle>
          <CardDescription>{t.manageCustomerPricingDescription ?? 'تحديد أسعار مخصصة حسب تصنيف الزبون.'}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-2">
          <div className="flex items-end gap-2">
            <div className="flex-1">
              <label className="text-sm font-medium">{t.customerCategoryLabel || 'تصنيف الزبون'}</label>
              <Select onValueChange={setSelectedCategory} value={selectedCategory}>
                <SelectTrigger className="w-full mt-1">
                  <SelectValue placeholder={t.selectCustomerCategoryPlaceholder ?? 'اختر تصنيف الزبون'} />
                </SelectTrigger>
                <SelectContent>
                  {categories.map(cat => (
                    <SelectItem key={cat.name} value={cat.name}>{cat.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <Button type="button" onClick={() => setShowAddCategoryDialog(true)} size="sm" variant="outline">
              <PlusCircle className="h-4 w-4 mr-1" />
              {t.addCategoryButton || 'إضافة تصنيف'}
            </Button>
            {selectedCategory && selectedCategory !== 'general' && (
              <AlertDialog>
                <AlertDialogTrigger asChild>
                  <Button type="button" size="sm" variant="outline" disabled={isCategoryPending}>
                    <Trash2 className="h-4 w-4 mr-1" />
                    {t.deleteCategoryButton || 'حذف'}
                  </Button>
                </AlertDialogTrigger>
                <AlertDialogContent>
                  <AlertDialogHeader>
                    <AlertDialogTitle>{t.deleteCategoryTitle || 'حذف التصنيف'}</AlertDialogTitle>
                    <AlertDialogDescription>
                      {(t.deleteCategoryDescription || 'هل أنت متأكد من حذف التصنيف "{name}"؟').replace('{name}', selectedCategory)}
                    </AlertDialogDescription>
                  </AlertDialogHeader>
                  <AlertDialogFooter>
                    <AlertDialogCancel>{tGlobal.cancel}</AlertDialogCancel>
                    <AlertDialogAction onClick={() => onDeleteCategory(categories.find(c => c.name === selectedCategory)?.id || '')} className="bg-destructive hover:bg-destructive/90">
                      {isCategoryPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                      {tGlobal.delete}
                    </AlertDialogAction>
                  </AlertDialogFooter>
                </AlertDialogContent>
              </AlertDialog>
            )}
          </div>
        </CardContent>
      </Card>
      
      <Dialog open={showAddCategoryDialog} onOpenChange={setShowAddCategoryDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{t.addCategoryTitle || 'إضافة تصنيف جديد'}</DialogTitle>
            <DialogDescription>{t.addCategoryDescription || 'أدخل اسم التصنيف الجديد'}</DialogDescription>
          </DialogHeader>
          <Input
            value={newCategoryName}
            onChange={(e) => setNewCategoryName(e.target.value)}
            placeholder={t.categoryNamePlaceholder || 'اسم التصنيف'}
            onKeyDown={(e) => {
              if (e.key === 'Enter') {
                e.preventDefault();
                onAddCategory();
              }
            }}
          />
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setShowAddCategoryDialog(false)}>{tGlobal.cancel}</Button>
            <Button type="button" onClick={onAddCategory} disabled={isCategoryPending || !newCategoryName.trim()}>
              {isCategoryPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              {t.addButton || 'إضافة'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      
      {selectedCategory && (
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>{(t.pricingFor ?? 'Pricing for {customerName}').replace('{customerName}', categoryLabel)}</CardTitle>
              </CardHeader>
              <DocumentLockBanner lockStatus={lockStatus} />
              <CardContent className="space-y-6">
                <div>
                  <h3 className="text-lg font-medium mb-2">{t.customerSpecificPrices ?? 'الأسعار الخاصة بالزبون'}</h3>
                  <div className="space-y-4">
                    {fields.length === 0 && <p className="text-sm text-muted-foreground">{t.noPricesMessage ?? "لم يتم تحديد أسعار خاصة لهذا الزبون."}</p>}
                    {fields.map((field, index) => (
                      <div key={field.id} className="flex items-center gap-2">
                        <FormField
                          control={form.control}
                          name={`prices.${index}.materialId`}
                          render={({ field }) => (
                            <FormItem className="flex-1">
                              <Select onValueChange={field.onChange} defaultValue={field.value}>
                                <FormControl>
                                  <SelectTrigger><SelectValue placeholder={t.item ?? 'الصنف'} /></SelectTrigger>
                                </FormControl>
                                <SelectContent>
                                  {materials.map(m => <SelectItem key={m.id} value={m.id}>{m.name}</SelectItem>)}
                                </SelectContent>
                              </Select>
                            </FormItem>
                          )}
                        />
                        <FormField
                          control={form.control}
                          name={`prices.${index}.price`}
                          render={({ field }) => (
                            <FormItem>
                              <FormControl><Input type="number" placeholder={t.price ?? 'السعر'} {...field} /></FormControl>
                            </FormItem>
                          )}
                        />
                        <Button type="button" variant="ghost" size="icon" onClick={() => remove(index)}><Trash2 className="h-4 w-4" /></Button>
                      </div>
                    ))}
                    <Button type="button" variant="outline" size="sm" onClick={() => append({ materialId: '', price: 0 })}>
                      <PlusCircle className="mr-2 h-4 w-4" />{t.addPriceButton ?? 'إضافة سعر صنف'}
                    </Button>
                  </div>
                </div>
                
                <Separator />

                <div>
                    <h3 className="text-lg font-medium">{t.bonusItemTitle ?? 'قاعدة البونص'}</h3>
                    <p className="text-sm text-muted-foreground mb-4">{t.bonusItemDescription ?? 'حدد الصنف الذي سيتم منحه كبونص، وكمية الشراء اللازمة للحصول عليه، وكمية البونص الممنوحة.'}</p>
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4 items-end">
                         <FormField
                            control={form.control}
                            name="bonus.materialId"
                            render={({ field }) => (
                            <FormItem>
                                <FormLabel>{t.bonusItem ?? 'صنف البونص'}</FormLabel>
                                <Select 
                                onValueChange={(value) => field.onChange(value === 'none' ? '' : value)} 
                                value={field.value ? field.value : 'none'}
                                >
                                <FormControl>
                                    <SelectTrigger>
                                        <SelectValue placeholder={t.noBonus ?? 'لا يوجد بونص'} />
                                    </SelectTrigger>
                                </FormControl>
                                <SelectContent>
                                    <SelectItem value="none">{t.noBonus ?? 'لا يوجد بونص'}</SelectItem>
                                    {materials.map(m => <SelectItem key={m.id} value={m.id}>{m.name}</SelectItem>)}
                                </SelectContent>
                                </Select>
                            </FormItem>
                            )}
                        />
                         <FormField
                            control={form.control}
                            name="bonus.buyQuantity"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>{t.buyQuantityLabel ?? 'مقابل شراء (كمية)'}</FormLabel>
                                    <FormControl><Input type="number" {...field} /></FormControl>
                                </FormItem>
                            )}
                        />
                         <FormField
                            control={form.control}
                            name="bonus.bonusQuantity"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>{t.bonusQuantityLabel ?? 'يحصل على (كمية بونص)'}</FormLabel>
                                    <FormControl><Input type="number" {...field} /></FormControl>
                                </FormItem>
                            )}
                        />
                    </div>
                </div>
              </CardContent>
              <div className="p-6 pt-0">
                <Button type="submit" disabled={isPending || isEditLocked}>
                  {isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  {t.savePricingButton ?? 'حفظ الأسعار'}
                </Button>
              </div>
            </Card>
          </form>
        </Form>
      )}
    </div>
  );
}
