import { useState, useEffect } from "react";
import { Switch } from "~/components/ui/switch";
import { RadioGroup, RadioGroupItem } from "~/components/ui/radio-group";
import { Label } from "~/components/ui/label";

interface AutodraftSettingsProps {
  seasonId: string;
  teamId: string;
  isEnabled: boolean;
  mode: "next_pick" | "while_on";
  isMyTurn: boolean;
  onUpdate: (isEnabled: boolean, mode: "next_pick" | "while_on") => void;
}

export function AutodraftSettings({
  seasonId,
  teamId,
  isEnabled,
  mode,
  isMyTurn,
  onUpdate,
}: AutodraftSettingsProps) {
  const [localEnabled, setLocalEnabled] = useState(isEnabled);
  const [localMode, setLocalMode] = useState<"next_pick" | "while_on">(mode);

  // Sync local state with props when they change (from socket events)
  useEffect(() => {
    setLocalEnabled(isEnabled);
  }, [isEnabled]);

  useEffect(() => {
    setLocalMode(mode);
  }, [mode]);

  const handleToggle = async (checked: boolean) => {
    setLocalEnabled(checked);

    try {
      const formData = new FormData();
      formData.append("seasonId", seasonId);
      formData.append("teamId", teamId);
      formData.append("isEnabled", checked.toString());
      formData.append("mode", localMode);

      const response = await fetch("/api/autodraft/update", {
        method: "POST",
        body: formData,
      });

      if (response.ok) {
        onUpdate(checked, localMode);
      } else {
        // Revert on error
        setLocalEnabled(!checked);
        console.error("Failed to update autodraft settings");
      }
    } catch (error) {
      // Revert on error
      setLocalEnabled(!checked);
      console.error("Error updating autodraft settings:", error);
    }
  };

  const handleModeChange = async (newMode: "next_pick" | "while_on") => {
    setLocalMode(newMode);

    try {
      const formData = new FormData();
      formData.append("seasonId", seasonId);
      formData.append("teamId", teamId);
      formData.append("isEnabled", localEnabled.toString());
      formData.append("mode", newMode);

      const response = await fetch("/api/autodraft/update", {
        method: "POST",
        body: formData,
      });

      if (response.ok) {
        onUpdate(localEnabled, newMode);
      } else {
        // Revert on error
        setLocalMode(localMode);
        console.error("Failed to update autodraft mode");
      }
    } catch (error) {
      // Revert on error
      setLocalMode(localMode);
      console.error("Error updating autodraft mode:", error);
    }
  };

  return (
    <div className="border-t pt-4 mt-4">
      <div className="flex items-center justify-between mb-3">
        <Label htmlFor="autodraft-switch" className="text-sm font-semibold">
          Autodraft
        </Label>
        <Switch
          id="autodraft-switch"
          checked={localEnabled}
          onCheckedChange={handleToggle}
          disabled={isMyTurn}
        />
      </div>

      {localEnabled && (
        <RadioGroup
          value={localMode}
          onValueChange={(value) => handleModeChange(value as "next_pick" | "while_on")}
          disabled={isMyTurn}
          className="space-y-2"
        >
          <div className="flex items-center space-x-2">
            <RadioGroupItem value="next_pick" id="next_pick" disabled={isMyTurn} />
            <Label
              htmlFor="next_pick"
              className={`text-sm ${isMyTurn ? "text-muted-foreground" : "cursor-pointer"}`}
            >
              Next Pick
            </Label>
          </div>
          <div className="flex items-center space-x-2">
            <RadioGroupItem value="while_on" id="while_on" disabled={isMyTurn} />
            <Label
              htmlFor="while_on"
              className={`text-sm ${isMyTurn ? "text-muted-foreground" : "cursor-pointer"}`}
            >
              While On
            </Label>
          </div>
        </RadioGroup>
      )}

      {isMyTurn && (
        <p className="text-xs text-muted-foreground mt-2">
          Autodraft settings are disabled during your pick
        </p>
      )}
    </div>
  );
}
