"use client";

import { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { toast } from "@/hooks/use-toast";
import https from '@/services/https';

export default function AssignSplitCodeModal({ isOpen, onClose, selectedAgentIds, onAssignmentSuccess }) {
  const [splits, setSplits] = useState([]);
  const [selectedSplit, setSelectedSplit] = useState('');
  const [bearerSubaccount, setBearerSubaccount] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    if (isOpen) {
      const fetchSplits = async () => {
        try {
          const token = localStorage.getItem('token');
          const response = await fetch(`${https.baseUrl}/businesses/splits`, {
            headers: { 'x-auth-token': token },
          });
          if (!response.ok) {
            throw new Error('Failed to fetch split codes');
          }
          const data = await response.json();
          setSplits(data);
        } catch (error) {
          console.error('Failed to fetch splits:', error);
          toast({
            title: 'Error',
            description: 'Failed to fetch split codes.',
            variant: 'destructive',
          });
        }
      };
      fetchSplits();
    }
  }, [isOpen]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsLoading(true);
    try {
      const token = localStorage.getItem('token');
      const response = await fetch(`${https.baseUrl}/admin/dva/bulk-split-assignment`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-auth-token': token,
        },
        body: JSON.stringify({
          split_code: selectedSplit,
          user_ids: selectedAgentIds,
          bearer_subaccount: bearerSubaccount,
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.msg || 'Failed to assign split code');
      }

      toast({
        title: 'Success',
        description: 'Split code assigned to agents successfully.',
      });
      onAssignmentSuccess();
    } catch (error) {
      console.error('Failed to assign split code:', error);
      toast({
        title: 'Error',
        description: error.message || 'Failed to assign split code.',
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Assign Split Code</DialogTitle>
          <DialogDescription>
            Select a split code and enter a bearer subaccount to assign to the selected {selectedAgentIds.length} agents.
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="split_code">Split Code</Label>
            <Select onValueChange={setSelectedSplit} value={selectedSplit}>
              <SelectTrigger>
                <SelectValue placeholder="Select a split code" />
              </SelectTrigger>
              <SelectContent>
                {splits.map((split) => (
                  <SelectItem key={split.id} value={split.split_code}>
                    {split.split_name} ({split.split_code})
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label htmlFor="bearer_subaccount">Bearer Subaccount (Optional)</Label>
            <Input
              id="bearer_subaccount"
              value={bearerSubaccount}
              onChange={(e) => setBearerSubaccount(e.target.value)}
              placeholder="Enter bearer subaccount"
            />
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={onClose}>Cancel</Button>
            <Button type="submit" disabled={isLoading || !selectedSplit}>
              {isLoading ? 'Assigning...' : 'Assign'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
