'use client';

import { useState, useTransition } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/hooks/use-toast';
import { Store } from 'lucide-react';
import { Switch } from '@/components/ui/switch';

type StoreSettingsFormProps = {
  currentSettings: Record<string, unknown>;
};

export default function StoreSettingsForm({ currentSettings }: StoreSettingsFormProps) {
  const { toast } = useToast();
  const [isPending, startTransition] = useTransition();

  const [storeName, setStoreName] = useState(String(currentSettings?.storeName || ''));
  const [storeDescription, setStoreDescription] = useState(String(currentSettings?.storeDescription || ''));
  const [storeContactPhone, setStoreContactPhone] = useState(String(currentSettings?.storeContactPhone || ''));
  const [storeLogoUrl, setStoreLogoUrl] = useState(String(currentSettings?.storeLogoUrl || ''));
  const [storeModuleEnabled, setStoreModuleEnabled] = useState(
    currentSettings?.storeModuleEnabled === true || currentSettings?.storeModuleEnabled === 'true'
  );

  const handleSave = () => {
    startTransition(async () => {
      try {
        const response = await fetch('/api/admin/settings/store', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            storeModuleEnabled,
            storeName: storeName.trim(),
            storeDescription: storeDescription.trim(),
            storeContactPhone: storeContactPhone.trim(),
            storeLogoUrl: storeLogoUrl.trim(),
          }),
        });
        const data = await response.json().catch(() => ({}));
        if (!response.ok) {
          toast({ title: 'خطأ', description: data?.error || 'فشل حفظ الإعدادات', variant: 'destructive' });
          return;
        }
        toast({ title: 'تم الحفظ', description: 'تم تحديث إعدادات المتجر بنجاح' });
      } catch {
        toast({ title: 'خطأ', description: 'تعذر الاتصال بالخادم', variant: 'destructive' });
      }
    });
  };

  return (
    <div className="space-y-6 max-w-2xl">
      <div className="flex items-center justify-between rounded-md border px-4 py-3">
        <div>
          <p className="text-sm font-medium">تفعيل المتجر الإلكتروني</p>
          <p className="text-xs text-muted-foreground">
            عند التفعيل تظهر أعمدة المتجر في جداول الأصناف ويمكن تصفح المتجر على رابط{' '}
            <a href="/store" target="_blank" className="text-primary underline">/store</a>
          </p>
        </div>
        <Switch checked={storeModuleEnabled} onCheckedChange={setStoreModuleEnabled} />
      </div>

      <div className="space-y-2">
        <Label htmlFor="store-name">اسم المتجر</Label>
        <Input
          id="store-name"
          value={storeName}
          onChange={(e) => setStoreName(e.target.value)}
          placeholder="مثال: متجر الشركة"
          maxLength={100}
        />
      </div>

      <div className="space-y-2">
        <Label htmlFor="store-desc">نص ترحيبي / وصف المتجر</Label>
        <Textarea
          id="store-desc"
          value={storeDescription}
          onChange={(e) => setStoreDescription(e.target.value)}
          placeholder="مثال: أهلاً بك في متجرنا، تصفح منتجاتنا..."
          rows={3}
          maxLength={300}
        />
      </div>

      <div className="space-y-2">
        <Label htmlFor="store-phone">رقم التواصل (يظهر في المتجر)</Label>
        <Input
          id="store-phone"
          value={storeContactPhone}
          onChange={(e) => setStoreContactPhone(e.target.value)}
          placeholder="05xxxxxxxx"
          dir="ltr"
          maxLength={20}
        />
      </div>

      <div className="space-y-2">
        <Label htmlFor="store-logo">رابط الشعار (اختياري)</Label>
        <Input
          id="store-logo"
          value={storeLogoUrl}
          onChange={(e) => setStoreLogoUrl(e.target.value)}
          placeholder="https://..."
          dir="ltr"
          maxLength={500}
        />
        <p className="text-xs text-muted-foreground">رابط مباشر لصورة الشعار (HTTPS فقط)</p>
      </div>

      <Button onClick={handleSave} disabled={isPending}>
        {isPending ? 'جاري الحفظ...' : 'حفظ إعدادات المتجر'}
      </Button>
    </div>
  );
}
