import { useState, useEffect } from 'react';
import { Save } from 'lucide-react';
import { GradientButton } from '../../components/ui/GradientButton';
import { Input } from '../../components/ui/Input';
import { api } from '../../api/client';
import type { PlatformConfig } from '../../types';

export function AdminSettingsPage() {
  const [config, setConfig] = useState<PlatformConfig | null>(null);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [keywordsText, setKeywordsText] = useState('');

  useEffect(() => {
    api.get<PlatformConfig>('/admin/settings').then((c) => {
      setConfig(c);
      setKeywordsText(c.blockedKeywords.join(', '));
    }).catch(() => {});
  }, []);

  const handleSave = async () => {
    if (!config) return;
    setSaving(true);
    try {
      const keywords = keywordsText.split(',').map(k => k.trim()).filter(Boolean);
      const updated = await api.patch<PlatformConfig>('/admin/settings', { ...config, blockedKeywords: keywords });
      setConfig(updated);
      setSaved(true);
      setTimeout(() => setSaved(false), 2000);
    } catch {} finally {
      setSaving(false);
    }
  };

  if (!config) return <div className="text-center text-gray-400 py-12">Loading settings...</div>;

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-gray-900">Platform Settings</h1>
        <GradientButton onClick={handleSave} disabled={saving}>
          <Save className="w-4 h-4 mr-2" /> {saved ? 'Saved!' : saving ? 'Saving...' : 'Save Changes'}
        </GradientButton>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div className="bg-white rounded-xl border border-gray-200 p-6">
          <h2 className="font-semibold text-gray-900 mb-4">Fees & Commission</h2>
          <div className="space-y-4">
            <Input
              label="Listing Fee ($)"
              type="number"
              value={String(config.listingFee)}
              onChange={(e) => setConfig({ ...config, listingFee: parseFloat(e.target.value) || 0 })}
            />
            <Input
              label="Commission (%)"
              type="number"
              value={String(config.commissionPercent)}
              onChange={(e) => setConfig({ ...config, commissionPercent: parseFloat(e.target.value) || 0 })}
            />
            <Input
              label="Promotion Day Price ($)"
              type="number"
              value={String(config.promotionDayPrice)}
              onChange={(e) => setConfig({ ...config, promotionDayPrice: parseFloat(e.target.value) || 0 })}
            />
          </div>
        </div>

        <div className="bg-white rounded-xl border border-gray-200 p-6">
          <h2 className="font-semibold text-gray-900 mb-4">Subscription Pricing</h2>
          <div className="space-y-4">
            <Input
              label="Pro Plan ($/month)"
              type="number"
              value={String(config.proPrice)}
              onChange={(e) => setConfig({ ...config, proPrice: parseFloat(e.target.value) || 0 })}
            />
            <Input
              label="Business Plan ($/month)"
              type="number"
              value={String(config.businessPrice)}
              onChange={(e) => setConfig({ ...config, businessPrice: parseFloat(e.target.value) || 0 })}
            />
          </div>
        </div>

        <div className="bg-white rounded-xl border border-gray-200 p-6">
          <h2 className="font-semibold text-gray-900 mb-4">Listing Limits</h2>
          <div className="space-y-4">
            <Input
              label="Max Images Per Listing"
              type="number"
              value={String(config.maxImagesPerListing)}
              onChange={(e) => setConfig({ ...config, maxImagesPerListing: parseInt(e.target.value) || 1 })}
            />
            <Input
              label="Max Listings (Free Tier)"
              type="number"
              value={String(config.maxListingsFreeTier)}
              onChange={(e) => setConfig({ ...config, maxListingsFreeTier: parseInt(e.target.value) || 1 })}
            />
          </div>
        </div>

        <div className="bg-white rounded-xl border border-gray-200 p-6">
          <h2 className="font-semibold text-gray-900 mb-4">Rental Settings</h2>
          <div className="space-y-4">
            <Input
              label="Rental Commission (%)"
              type="number"
              value={String((config as any).rentalCommissionPercent ?? 10)}
              onChange={(e) => setConfig({ ...config, rentalCommissionPercent: parseFloat(e.target.value) || 0 } as any)}
            />
            <Input
              label="Max Rental Images Per Listing"
              type="number"
              value={String((config as any).maxRentalImagesPerListing ?? 10)}
              onChange={(e) => setConfig({ ...config, maxRentalImagesPerListing: parseInt(e.target.value) || 1 } as any)}
            />
            <Input
              label="Booking Expiry Hours"
              type="number"
              value={String((config as any).bookingExpiryHours ?? 48)}
              onChange={(e) => setConfig({ ...config, bookingExpiryHours: parseInt(e.target.value) || 48 } as any)}
            />
            <Input
              label="Rental Promotion Day Price ($)"
              type="number"
              value={String((config as any).rentalPromotionDayPrice ?? 3.99)}
              onChange={(e) => setConfig({ ...config, rentalPromotionDayPrice: parseFloat(e.target.value) || 0 } as any)}
            />
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-700">Auto-Approve Rentals</p>
                <p className="text-xs text-gray-400">Rental listings go live immediately when enabled</p>
              </div>
              <button
                onClick={() => setConfig({ ...config, rentalAutoApprove: !(config as any).rentalAutoApprove } as any)}
                className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors cursor-pointer ${
                  (config as any).rentalAutoApprove ? 'bg-primary-600' : 'bg-gray-200'
                }`}
              >
                <span className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                  (config as any).rentalAutoApprove ? 'translate-x-6' : 'translate-x-1'
                }`} />
              </button>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl border border-gray-200 p-6">
          <h2 className="font-semibold text-gray-900 mb-4">Moderation</h2>
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-700">Auto-Approve Listings</p>
                <p className="text-xs text-gray-400">Listings go live immediately when enabled</p>
              </div>
              <button
                onClick={() => setConfig({ ...config, autoApprove: !config.autoApprove })}
                className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors cursor-pointer ${
                  config.autoApprove ? 'bg-primary-600' : 'bg-gray-200'
                }`}
              >
                <span className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                  config.autoApprove ? 'translate-x-6' : 'translate-x-1'
                }`} />
              </button>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1.5">Blocked Keywords</label>
              <textarea
                value={keywordsText}
                onChange={(e) => setKeywordsText(e.target.value)}
                rows={3}
                placeholder="Enter keywords separated by commas..."
                className="w-full rounded-xl border border-gray-200 bg-white px-4 py-2.5 text-sm placeholder:text-gray-400 focus:border-primary-400 focus:ring-2 focus:ring-primary-100 focus:outline-none resize-none"
              />
              <p className="text-xs text-gray-400 mt-1">Listings containing these words will be sent for review</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
