'use client';

import { useTransition } from 'react';
import { useRouter } from 'next/navigation';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { Button } from '@/components/ui/button';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { useDocumentLock } from '@/hooks/use-document-lock';
import { DocumentLockBanner } from '@/components/admin/document-lock-banner';
import { useToast } from '@/hooks/use-toast';
import { handleUpdateWarehouse } from '@/lib/actions';
import type { Warehouse } from '@/lib/types';
import { ArrowRight } from 'lucide-react';

const warehouseSchema = z.object({
  name: z.string().min(2, 'Warehouse name is required.'),
  branchName: z.string().optional().default(''),
  departmentsText: z.string().optional().default(''),
  warehouseType: z.enum(['main', 'branch', 'returns', 'transit']).default('branch'),
  managerEmployeeId: z.string().optional().default(''),
  managerName: z.string().optional().default(''),
  operatingStatus: z.enum(['active', 'stopped', 'inventory']).default('active'),
  city: z.string().optional().default(''),
  address: z.string().optional().default(''),
  contactPhone: z.string().optional().default(''),
  allowIssueWithoutStock: z.enum(['yes', 'no']).default('no'),
  useInPos: z.enum(['yes', 'no']).default('yes'),
  location: z.string().optional().default(''),
  notes: z.string().optional().default(''),
});

type WarehouseValues = z.infer<typeof warehouseSchema>;

interface Props {
  warehouse: Warehouse;
  employees: { id: string; name: string }[];
  branchOptions: string[];
  t?: Record<string, string>;
  tGlobal?: Record<string, string>;
}

export default function WarehouseEditForm({ warehouse, employees, branchOptions, t, tGlobal }: Props) {
  const router = useRouter();
  const { toast } = useToast();
  const [isPending, startTransition] = useTransition();
  const { lockStatus } = useDocumentLock('warehouse', warehouse.id);
  const isEditLocked = lockStatus.isLocked;

  const form = useForm<WarehouseValues>({
    resolver: zodResolver(warehouseSchema),
    defaultValues: {
      name: warehouse.name || '',
      branchName: warehouse.branchName || '',
      departmentsText: Array.isArray(warehouse.departments) ? warehouse.departments.join(', ') : '',
      warehouseType: (warehouse.warehouseType || 'branch') as WarehouseValues['warehouseType'],
      managerEmployeeId: warehouse.managerEmployeeId || '',
      managerName: warehouse.managerName || '',
      operatingStatus: (warehouse.operatingStatus || (warehouse.inactive ? 'stopped' : 'active')) as WarehouseValues['operatingStatus'],
      city: warehouse.city || '',
      address: warehouse.address || warehouse.location || '',
      contactPhone: warehouse.contactPhone || '',
      allowIssueWithoutStock: warehouse.allowIssueWithoutStock ? 'yes' : 'no',
      useInPos: warehouse.useInPos === false ? 'no' : 'yes',
      location: warehouse.location || '',
      notes: warehouse.notes || '',
    },
  });

  const onSubmit = (values: WarehouseValues) => {
    if (isEditLocked) return;

    startTransition(async () => {
      const departments = String(values.departmentsText || '')
        .split(',')
        .map((entry) => entry.trim())
        .filter(Boolean);
      const result = await handleUpdateWarehouse(warehouse.id, {
        ...values,
        departments,
        allowIssueWithoutStock: values.allowIssueWithoutStock === 'yes',
        useInPos: values.useInPos === 'yes',
      });
      if (result && 'success' in result && result.success) {
        toast({ title: t?.warehouseUpdatedSuccess ?? 'تم تحديث المستودع بنجاح' });
        router.push('/admin/data/warehouses');
        return;
      }
      toast({
        title: t?.saveErrorTitle ?? tGlobal?.error ?? 'Error',
        description: (result as any)?.error || t?.warehouseUpdateError || 'Failed to update warehouse',
        variant: 'destructive',
      });
    });
  };

  return (
    <div className="w-full max-w-3xl mx-auto space-y-6">
      <div className="flex items-center gap-3">
        <Button type="button" variant="ghost" size="icon" onClick={() => router.push('/admin/data/warehouses')}>
          <ArrowRight className="h-4 w-4" />
        </Button>
        <div>
          <h1 className="text-2xl font-bold">{t?.editWarehouseTitle ?? 'تعديل المستودع'}</h1>
          <p className="text-sm text-muted-foreground">{t?.editWarehouseDescription ?? 'يمكنك تعديل الاسم والموقع والملاحظات دون التأثير على المرجع الثابت.'}</p>
        </div>
      </div>

      <div className="rounded-md border bg-muted/30 px-3 py-2 text-sm">
        <span className="text-muted-foreground">{t?.warehouseReferenceLabel ?? 'مرجع المستودع'}: </span>
        <span className="font-mono">{warehouse.warehouseNumber || '-'}</span>
      </div>

      <DocumentLockBanner lockStatus={lockStatus} />

      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
          <div className="grid gap-4 md:grid-cols-2">
            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.warehouseNameLabel ?? 'اسم المستودع'}</FormLabel>
                  <FormControl><Input {...field} /></FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="branchName"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.branchLabel ?? 'الفرع'}</FormLabel>
                  <Select value={field.value && field.value.length > 0 ? field.value : 'none'} onValueChange={(value) => field.onChange(value === 'none' ? '' : value)}>
                    <FormControl>
                      <SelectTrigger><SelectValue placeholder={t?.branchPlaceholder ?? 'اختر الفرع'} /></SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="none">{t?.select ?? 'غير محدد'}</SelectItem>
                      {branchOptions.map((branch) => (
                        <SelectItem key={branch} value={branch}>{branch}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="departmentsText"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.departmentsLabel ?? 'الأقسام التابعة'}</FormLabel>
                  <FormControl><Input {...field} placeholder={t?.departmentsPlaceholder ?? 'مثال: مبيعات, مشتريات, تشغيل'} /></FormControl>
                  <p className="text-xs text-muted-foreground">{t?.departmentsHint ?? 'افصل بين الأقسام بفاصلة (,).'}</p>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="warehouseType"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.warehouseTypeLabel ?? 'نوع المستودع'}</FormLabel>
                  <Select value={field.value} onValueChange={field.onChange}>
                    <FormControl>
                      <SelectTrigger><SelectValue /></SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="main">{t?.warehouseTypeMain ?? 'رئيسي'}</SelectItem>
                      <SelectItem value="branch">{t?.warehouseTypeBranch ?? 'فرعي'}</SelectItem>
                      <SelectItem value="returns">{t?.warehouseTypeReturns ?? 'مرتجعات'}</SelectItem>
                      <SelectItem value="transit">{t?.warehouseTypeTransit ?? 'انتقالي'}</SelectItem>
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="managerEmployeeId"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.warehouseManagerLabel ?? 'مسؤول المستودع'}</FormLabel>
                  <Select value={field.value && field.value.length > 0 ? field.value : 'none'} onValueChange={(value) => field.onChange(value === 'none' ? '' : value)}>
                    <FormControl>
                      <SelectTrigger><SelectValue placeholder={t?.warehouseManagerPlaceholder ?? 'اختر المسؤول'} /></SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="none">{t?.select ?? 'غير محدد'}</SelectItem>
                      {employees.map((employee) => (
                        <SelectItem key={employee.id} value={employee.id}>{employee.name}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="operatingStatus"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.warehouseOperatingStatusLabel ?? 'حالة التشغيل'}</FormLabel>
                  <Select value={field.value} onValueChange={field.onChange}>
                    <FormControl>
                      <SelectTrigger><SelectValue /></SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="active">{t?.warehouseStatusActive ?? 'نشط'}</SelectItem>
                      <SelectItem value="stopped">{t?.warehouseStatusStopped ?? 'موقوف'}</SelectItem>
                      <SelectItem value="inventory">{t?.warehouseStatusInventory ?? 'تحت الجرد'}</SelectItem>
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="city"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.warehouseCityLabel ?? 'المدينة'}</FormLabel>
                  <FormControl><Input {...field} /></FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="address"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.warehouseAddressLabel ?? 'العنوان'}</FormLabel>
                  <FormControl><Input {...field} /></FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="contactPhone"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.warehouseContactPhoneLabel ?? 'رقم التواصل'}</FormLabel>
                  <FormControl><Input {...field} /></FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="allowIssueWithoutStock"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.allowIssueWithoutStockLabel ?? 'يسمح بالصرف بدون رصيد'}</FormLabel>
                  <Select value={field.value} onValueChange={field.onChange}>
                    <FormControl>
                      <SelectTrigger><SelectValue /></SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="yes">{t?.yesLabel ?? 'نعم'}</SelectItem>
                      <SelectItem value="no">{t?.noLabel ?? 'لا'}</SelectItem>
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="useInPos"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.warehouseUseInPosLabel ?? 'استخدامه في POS'}</FormLabel>
                  <Select value={field.value} onValueChange={field.onChange}>
                    <FormControl>
                      <SelectTrigger><SelectValue /></SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="yes">{t?.yesLabel ?? 'نعم'}</SelectItem>
                      <SelectItem value="no">{t?.noLabel ?? 'لا'}</SelectItem>
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="notes"
              render={({ field }) => (
                <FormItem className="md:col-span-2">
                  <FormLabel>{t?.notesLabel ?? 'ملاحظات'}</FormLabel>
                  <FormControl><Textarea {...field} rows={4} /></FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>

          <div className="flex justify-end gap-3 pt-2">
            <Button type="button" variant="outline" onClick={() => router.push('/admin/data/warehouses')} disabled={isPending}>
              {tGlobal?.cancel ?? 'إلغاء'}
            </Button>
            <Button type="submit" disabled={isPending || isEditLocked}>
              {tGlobal?.save ?? 'حفظ'}
            </Button>
          </div>
        </form>
      </Form>
    </div>
  );
}
