
"use client";

import { useState, useEffect } from 'react';
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { toast } from "@/hooks/use-toast";
import https from '@/services/https';

export default function SettingsPage() {
  const [commissionRates, setCommissionRates] = useState({
    general_agent_commission_rate: '',
    general_super_agent_commission_rate: '',
  });
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    const fetchCommissionRates = async () => {
      try {
        const token = localStorage.getItem('token');
        const response = await fetch(`${https.baseUrl}/admin/settings/commission`, {
          headers: { 'x-auth-token': token },
        });
        if (!response.ok) {
          throw new Error('Failed to fetch commission rates');
        }
        const data = await response.json();
        setCommissionRates(data);
      } catch (error) {
        console.error('Error fetching commission rates:', error);
        toast({
          title: 'Error',
          description: 'Failed to load commission rates.',
          variant: 'destructive',
        });
      }
    };

    fetchCommissionRates();
  }, []);

  const handleInputChange = (field, value) => {
    setCommissionRates((prev) => ({ ...prev, [field]: value }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsLoading(true);
    try {
      const token = localStorage.getItem('token');
      const response = await fetch(`${https.baseUrl}/admin/settings/commission`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'x-auth-token': token,
        },
        body: JSON.stringify({
          agent_rate: parseFloat(commissionRates.general_agent_commission_rate),
          super_agent_rate: parseFloat(commissionRates.general_super_agent_commission_rate),
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.msg || 'Failed to update commission rates');
      }

      toast({
        title: 'Success',
        description: 'General commission rates have been updated successfully.',
      });
    } catch (error) {
      console.error('Error updating commission rates:', error);
      toast({
        title: 'Failed to Update',
        description: error.message || 'There was an error updating the rates. Please try again.',
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="container mx-auto p-4">
      <h1 className="text-2xl font-bold mb-4">General Commission Rate Settings</h1>
      <form onSubmit={handleSubmit} className="space-y-4 max-w-md">
        <div className="space-y-2">
          <Label htmlFor="agent_rate">Agent Commission Rate (%)</Label>
          <Input
            id="agent_rate"
            type="number"
            value={commissionRates.general_agent_commission_rate}
            onChange={(e) => handleInputChange('general_agent_commission_rate', e.target.value)}
            placeholder="e.g., 5"
          />
        </div>
        <div className="space-y-2">
          <Label htmlFor="super_agent_rate">Super Agent Commission Rate (%)</Label>
          <Input
            id="super_agent_rate"
            type="number"
            value={commissionRates.general_super_agent_commission_rate}
            onChange={(e) => handleInputChange('general_super_agent_commission_rate', e.target.value)}
            placeholder="e.g., 2"
          />
        </div>
        <Button type="submit" disabled={isLoading}>
          {isLoading ? 'Saving...' : 'Save Settings'}
        </Button>
      </form>
    </div>
  );
}
